-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathadapters.ts
291 lines (255 loc) · 9.63 KB
/
adapters.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import { LibAdapters, IMemoryDb, NotSupported, QueryResult } from './interfaces';
import { literal } from './pg-escape';
import moment from 'moment';
import lru from 'lru-cache';
import { bufToString, isBuf } from './buffer-node';
import { compareVersions } from './utils';
declare var __non_webpack_require__: any;
const delay = (time: number | undefined) => new Promise(done => setTimeout(done, time ?? 0));
function replaceQueryArgs$(this: void, sql: string, values: any[]) {
return sql.replace(/\$(\d+)/g, (str: any, istr: any) => {
const i = Number.parseInt(istr);
if (i > values.length) {
throw new Error('Unmatched parameter in query ' + str);
}
const val = values[i - 1];
switch (typeof val) {
case 'string':
return literal(val);
case 'boolean':
return val ? 'true' : 'false';
case 'number':
return val.toString(10);
default:
if (val === null || val === undefined) {
return 'null';
}
if (val instanceof Date) {
return `'${moment(val).toISOString()}'`;
}
if (isBuf(val)) {
return literal(bufToString(val));
}
if (typeof val === 'object') {
return literal(JSON.stringify(val));
}
throw new Error('Invalid query parameter')
}
});
}
export class Adapters implements LibAdapters {
constructor(private db: IMemoryDb) {
}
createPg(queryLatency?: number): { Pool: any; Client: any } {
const that = this;
// https://node-postgres.com/features/queries
interface PgQuery {
text: string;
values?: any[];
rowMode?: 'array';
types?: any;
}
class MemPg {
connection = this;
on() {
// nop
}
release() {
}
removeListener() {
}
once(what: string, handler: () => void) {
if (what === 'connect') {
setTimeout(handler, queryLatency ?? 0);
}
}
end(callback: any) {
if (callback) {
callback();
return null;
} else {
return Promise.resolve();
}
}
connect(callback: any) {
if (callback) {
callback(null, this, () => { });
return null;
} else {
return Promise.resolve(this);
}
}
query(query: any, valuesOrCallback: any, callback: any) {
let values: any = null;
if (Array.isArray(valuesOrCallback)) {
values = valuesOrCallback;
}
if (callback == null && typeof valuesOrCallback === 'function') {
callback = valuesOrCallback;
}
const pgquery = this.adaptQuery(query, values);
try {
const result = this.adaptResults(query, that.db.public.query(pgquery.text));
if (callback) {
setTimeout(() => callback(null, result), queryLatency ?? 0);
return null;
} else {
return new Promise(res => setTimeout(() => res(result), queryLatency ?? 0));
}
} catch (e) {
if (callback) {
setTimeout(() => callback(e), queryLatency ?? 0);
return null;
} else {
return new Promise((_, rej) => setTimeout(() => rej(e), queryLatency ?? 0));
}
}
}
private adaptResults(query: PgQuery, rows: QueryResult) {
if (query.rowMode) {
throw new NotSupported('pg rowMode')
}
return {
...rows,
get fields() {
throw new NotSupported('get pg fields');
}
}
}
private adaptQuery(query: string | PgQuery, values: any): PgQuery {
if (typeof query === 'string') {
query = {
text: query,
values,
};
} else {
// clean copy to avoid mutating things outside our scope
query = { ...query };
}
if (!query.values?.length) {
return query;
}
if (query.types?.getTypeParser) {
throw new NotSupported('getTypeParser is not supported');
}
// console.log(query);
// console.log('\n');
query.text = replaceQueryArgs$(query.text, query.values);
return query;
}
}
return {
Pool: MemPg,
Client: MemPg,
};
}
createTypeormConnection(postgresOptions: any, queryLatency?: number) {
const that = this;
(postgresOptions as any).postgres = that.createPg(queryLatency);
if (postgresOptions?.type !== 'postgres') {
throw new NotSupported('Only postgres supported, found ' + postgresOptions?.type ?? '<null>')
}
const { getConnectionManager } = __non_webpack_require__('typeorm')
const created = getConnectionManager().create(postgresOptions);
created.driver.postgres = that.createPg(queryLatency);
return created.connect();
}
createSlonik(queryLatency?: number) {
const { createMockPool, createMockQueryResult } = __non_webpack_require__('slonik');
return createMockPool({
query: async (sql: string, args: any[]) => {
await delay(queryLatency ?? 0);
const formatted = replaceQueryArgs$(sql, args);
const ret = this.db.public.many(formatted);
return createMockQueryResult(ret);
},
});
}
createPgPromise(queryLatency?: number) {
// https://vitaly-t.github.io/pg-promise/module-pg-promise.html
// https://github.com/vitaly-t/pg-promise/issues/743#issuecomment-756110347
const pgp = __non_webpack_require__('pg-promise')();
pgp.pg = this.createPg(queryLatency);
const db = pgp('pg-mem');
if (compareVersions('10.8.7', db.$config.version) < 0) {
throw new Error(`💀 pg-mem cannot be used with pg-promise@${db.$config.version},
👉 you must install version pg-promise@10.8.7 or newer:
npm i pg-promise@latest -S
See https://github.com/vitaly-t/pg-promise/issues/743 for details`);
}
return db;
}
createPgNative(queryLatency?: number) {
queryLatency = queryLatency ?? 0;
const prepared = new lru<string, string>({
max: 1000,
maxAge: 5000,
});
function handlerFor(a: any, b: any) {
return typeof a === 'function' ? a : b;
}
const that = this;
return class Client {
async connect(a: any, b: any) {
const handler = handlerFor(a, b);
await delay(queryLatency);
handler?.();
}
connectSync() {
// nop
}
async prepare(name: string, sql: string, npar: number, callback: any) {
await delay(queryLatency);
this.prepareSync(name, sql, npar);
callback();
}
prepareSync(name: string, sql: string, npar: number) {
prepared.set(name, sql);
}
async execute(name: string, a: any, b: any) {
const handler = handlerFor(a, b);
const pars = Array.isArray(a) ? a : [];
await delay(queryLatency);
try {
const rows = this.executeSync(name, pars);
handler(null, rows);
} catch (e) {
handler(e);
}
}
executeSync(name: string, pars?: any) {
pars = Array.isArray(pars) ? pars : [];
const prep = prepared.get(name);
if (!prep) {
throw new Error('Unkown prepared statement ' + name);
}
return this.querySync(prep, pars);
}
async query(sql: string, b: any, c: any) {
const handler = handlerFor(b, c);
const params = Array.isArray(b) ? b : [];
try {
await delay(queryLatency);
const result = this.querySync(sql, params);
handler(null, result);
} catch (e) {
handler?.(e);
}
}
querySync(sql: string, params: any[]) {
sql = replaceQueryArgs$(sql, params);
const ret = that.db.public.many(sql);
return ret;
}
}
}
createKnex(queryLatency?: number): any {
const knex = __non_webpack_require__('knex')({
client: 'pg',
connection: {},
});
knex.client.driver = this.createPg(queryLatency);
knex.client.version = 'pg-mem';
return knex;
}
}