-
-
Notifications
You must be signed in to change notification settings - Fork 132
/
index.js
532 lines (426 loc) · 14.6 KB
/
index.js
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
// @flow
import pg, {
types
} from 'pg';
import {
parse as parseConnectionString
} from 'pg-connection-string';
import {
get as getStackTrace
} from 'stack-trace';
import serializeError from 'serialize-error';
import prettyHrtime from 'pretty-hrtime';
import {
factory as ulidFactory,
detectPrng
} from 'ulid';
import {
DataIntegrityError,
NotFoundError,
SlonikError,
UniqueViolationError
} from './errors';
import {
mapTaggedTemplateLiteralInvocation,
normalizeAnonymousValuePlaceholders,
normalizeNamedValuePlaceholders,
stripComments
} from './utilities';
import type {
AnonymouseValuePlaceholderValuesType,
ClientConfigurationType,
DatabaseConfigurationType,
DatabasePoolType,
DatabaseSingleConnectionType,
InternalQueryAnyFirstFunctionType,
InternalQueryAnyFunctionType,
InternalQueryFunctionType,
InternalQueryManyFirstFunctionType,
InternalQueryManyFunctionType,
InternalQueryMaybeOneFirstFunctionType,
InternalQueryMaybeOneFunctionType,
InternalQueryOneFirstFunctionType,
InternalQueryOneFunctionType,
InternalTransactionFunctionType,
TaggledTemplateLiteralInvocationType
} from './types';
import Logger from './Logger';
import {
SLONIK_LOG_NORMALISED,
SLONIK_LOG_STACK_TRACE,
SLONIK_LOG_VALUES
} from './config';
// @see https://github.com/facebook/flow/issues/2977#issuecomment-390613203
const defaultClientConfiguration = Object.freeze({});
// eslint-disable-next-line id-match
const INT8_OID = 20;
const TIMESTAMPTZ_OID = 1184;
const TIMESTAMP_OID = 1114;
types.setTypeParser(INT8_OID, (value) => {
return parseInt(value, 10);
});
types.setTypeParser(TIMESTAMPTZ_OID, (value) => {
return value === null ? value : Date.parse(value);
});
types.setTypeParser(TIMESTAMP_OID, (value) => {
return value === null ? value : Date.parse(value);
});
const log = Logger.child({
namespace: 'slonik'
});
const ulid = ulidFactory(detectPrng(true));
export type {
DatabaseConnectionType,
DatabasePoolConnectionType,
DatabasePoolType,
DatabaseSingleConnectionType,
InterceptorType
} from './types';
export {
DataIntegrityError,
UniqueViolationError,
SlonikError,
NotFoundError
};
// eslint-disable-next-line complexity
export const query: InternalQueryFunctionType<*> = async (connection, clientConfiguration, rawSql, values, queryId = ulid()) => {
let stackTrace;
if (SLONIK_LOG_STACK_TRACE) {
stackTrace = getStackTrace()
.map((callSite) => {
return callSite.getFileName() + ':' + callSite.getLineNumber() + ':' + callSite.getColumnNumber();
});
}
const strippedSql = stripComments(rawSql);
let rowCount: number | null = null;
let normalized;
const start = process.hrtime();
const interceptors = clientConfiguration && clientConfiguration.interceptors || [];
try {
let result;
for (const interceptor of interceptors) {
if (interceptor.beforeQuery) {
const maybeResult = await interceptor.beforeQuery({
sql: rawSql,
values
});
if (maybeResult) {
return maybeResult;
}
}
}
if (Array.isArray(values)) {
normalized = normalizeAnonymousValuePlaceholders(strippedSql, values);
} else if (values) {
normalized = normalizeNamedValuePlaceholders(strippedSql, values);
}
if (normalized) {
result = connection.query(normalized.sql, normalized.values);
} else {
result = connection.query(strippedSql);
}
result = await result;
for (const interceptor of interceptors) {
if (interceptor.afterQuery) {
await interceptor.afterQuery({
sql: rawSql,
values
}, result);
}
}
// @todo Use rowCount only if the query is UPDATE/ INSERT.
if (result.rowCount) {
rowCount = result.rowCount;
} else if (Array.isArray(result)) {
rowCount = result.length;
}
return result;
} catch (error) {
log.error({
error: serializeError(error),
queryId
}, 'query produced an error');
if (error.code === '23505') {
throw new UniqueViolationError(error.constraint);
}
throw error;
} finally {
const end = process.hrtime(start);
// eslint-disable-next-line flowtype/no-weak-types
const payload: Object = {
executionTime: prettyHrtime(end),
queryId,
rowCount,
sql: strippedSql
};
if (SLONIK_LOG_STACK_TRACE) {
payload.stackTrace = stackTrace;
}
if (SLONIK_LOG_VALUES) {
payload.values = values;
}
if (SLONIK_LOG_NORMALISED) {
payload.normalized = normalized;
}
log.debug(payload, 'query');
}
};
/**
* Makes a query and expects exactly one result.
*
* @throws NotFoundError If query returns no rows.
* @throws DataIntegrityError If query returns multiple rows.
*/
export const one: InternalQueryOneFunctionType = async (connection, clientConfiguration, rawSql, values, queryId = ulid()) => {
const {
rows
} = await query(connection, clientConfiguration, rawSql, values, queryId);
if (rows.length === 0) {
log.error({
queryId
}, 'NotFoundError');
const ConfigurableNotFoundError = clientConfiguration.errors && clientConfiguration.errors.NotFoundError ? clientConfiguration.errors.NotFoundError : NotFoundError;
throw new ConfigurableNotFoundError();
}
if (rows.length > 1) {
log.error({
queryId
}, 'DataIntegrityError');
throw new DataIntegrityError();
}
return rows[0];
};
/**
* Makes a query and expects exactly one result.
*
* @throws DataIntegrityError If query returns multiple rows.
*/
export const maybeOne: InternalQueryMaybeOneFunctionType = async (connection, clientConfiguration, rawSql, values, queryId = ulid()) => {
const {
rows
} = await query(connection, clientConfiguration, rawSql, values, queryId);
if (rows.length === 0) {
return null;
}
if (rows.length > 1) {
log.error({
queryId
}, 'DataIntegrityError');
throw new DataIntegrityError();
}
return rows[0];
};
/**
* Makes a query and expects exactly one result.
* Returns value of the first column.
*
* @throws NotFoundError If query returns no rows.
* @throws DataIntegrityError If query returns multiple rows.
*/
export const oneFirst: InternalQueryOneFirstFunctionType = async (connection, clientConfiguration, rawSql, values, queryId = ulid()) => {
const row = await one(connection, clientConfiguration, rawSql, values, queryId);
const keys = Object.keys(row);
if (keys.length !== 1) {
log.error({
queryId
}, 'DataIntegrityError');
throw new DataIntegrityError();
}
return row[keys[0]];
};
/**
* Makes a query and expects exactly one result.
* Returns value of the first column.
*
* @throws DataIntegrityError If query returns multiple rows.
*/
export const maybeOneFirst: InternalQueryMaybeOneFirstFunctionType = async (connection, clientConfiguration, rawSql, values, queryId = ulid()) => {
const row = await maybeOne(connection, clientConfiguration, rawSql, values, queryId);
if (!row) {
return null;
}
const keys = Object.keys(row);
if (keys.length !== 1) {
log.error({
queryId
}, 'DataIntegrityError');
throw new DataIntegrityError();
}
return row[keys[0]];
};
/**
* Makes a query and expects at least 1 result.
*
* @throws NotFoundError If query returns no rows.
*/
export const many: InternalQueryManyFunctionType = async (connection, clientConfiguration, rawSql, values, queryId = ulid()) => {
const {
rows
} = await query(connection, clientConfiguration, rawSql, values, queryId);
if (rows.length === 0) {
log.error({
queryId
}, 'NotFoundError');
const ConfigurableNotFoundError = clientConfiguration.errors && clientConfiguration.errors.NotFoundError ? clientConfiguration.errors.NotFoundError : NotFoundError;
throw new ConfigurableNotFoundError();
}
return rows;
};
export const manyFirst: InternalQueryManyFirstFunctionType = async (connection, clientConfigurationType, rawSql, values, queryId = ulid()) => {
const rows = await many(connection, clientConfigurationType, rawSql, values, queryId);
if (rows.length === 0) {
log.error({
queryId
}, 'DataIntegrityError');
throw new DataIntegrityError();
}
const keys = Object.keys(rows[0]);
if (keys.length !== 1) {
log.error({
queryId
}, 'DataIntegrityError');
throw new DataIntegrityError();
}
const firstColumnName = keys[0];
if (typeof firstColumnName !== 'string') {
log.error({
queryId
}, 'DataIntegrityError');
throw new DataIntegrityError();
}
return rows.map((row) => {
return row[firstColumnName];
});
};
/**
* Makes a query and expects any number of results.
*/
export const any: InternalQueryAnyFunctionType = async (connection, clientConfiguration, rawSql, values, queryId = ulid()) => {
const {
rows
} = await query(connection, clientConfiguration, rawSql, values, queryId);
return rows;
};
export const anyFirst: InternalQueryAnyFirstFunctionType = async (connection, clientConfigurationType, rawSql, values, queryId = ulid()) => {
const rows = await any(connection, clientConfigurationType, rawSql, values, queryId);
if (rows.length === 0) {
return [];
}
const keys = Object.keys(rows[0]);
if (keys.length !== 1) {
log.error({
queryId
}, 'DataIntegrityError');
throw new DataIntegrityError();
}
const firstColumnName = keys[0];
if (typeof firstColumnName !== 'string') {
log.error({
queryId
}, 'DataIntegrityError');
throw new DataIntegrityError();
}
return rows.map((row) => {
return row[firstColumnName];
});
};
export const transaction: InternalTransactionFunctionType = async (connection, handler) => {
await connection.query('START TRANSACTION');
try {
const result = await handler(connection);
await connection.query('COMMIT');
return result;
} catch (error) {
await connection.query('ROLLBACK');
log.error({
error: serializeError(error)
}, 'rolling back transaction due to an error');
throw error;
}
};
export const sql = (parts: $ReadOnlyArray<string>, ...values: AnonymouseValuePlaceholderValuesType): TaggledTemplateLiteralInvocationType => {
return {
sql: parts.join('?'),
values
};
};
export const createConnection = async (
connectionConfiguration: DatabaseConfigurationType,
clientConfiguration: ClientConfigurationType = defaultClientConfiguration
): Promise<DatabaseSingleConnectionType> => {
const pool = new pg.Pool(typeof connectionConfiguration === 'string' ? parseConnectionString(connectionConfiguration) : connectionConfiguration);
const connection = await pool.connect();
let ended = false;
const bindConnection = {
any: mapTaggedTemplateLiteralInvocation(any.bind(null, connection, clientConfiguration)),
anyFirst: mapTaggedTemplateLiteralInvocation(anyFirst.bind(null, connection, clientConfiguration)),
end: async () => {
if (ended) {
return ended;
}
await connection.release();
ended = pool.end();
return ended;
},
many: mapTaggedTemplateLiteralInvocation(many.bind(null, connection, clientConfiguration)),
manyFirst: mapTaggedTemplateLiteralInvocation(manyFirst.bind(null, connection, clientConfiguration)),
maybeOne: mapTaggedTemplateLiteralInvocation(maybeOne.bind(null, connection, clientConfiguration)),
maybeOneFirst: mapTaggedTemplateLiteralInvocation(maybeOneFirst.bind(null, connection, clientConfiguration)),
one: mapTaggedTemplateLiteralInvocation(one.bind(null, connection, clientConfiguration)),
oneFirst: mapTaggedTemplateLiteralInvocation(oneFirst.bind(null, connection, clientConfiguration)),
query: mapTaggedTemplateLiteralInvocation(query.bind(null, connection, clientConfiguration)),
transaction: (handler) => {
return transaction(bindConnection, handler);
}
};
return bindConnection;
};
export const createPool = (
connectionConfiguration: DatabaseConfigurationType,
clientConfiguration: ClientConfigurationType = defaultClientConfiguration
): DatabasePoolType => {
const pool = new pg.Pool(typeof connectionConfiguration === 'string' ? parseConnectionString(connectionConfiguration) : connectionConfiguration);
const connect = async () => {
const connection = await pool.connect();
const bindConnection = {
any: mapTaggedTemplateLiteralInvocation(any.bind(null, connection, clientConfiguration)),
anyFirst: mapTaggedTemplateLiteralInvocation(anyFirst.bind(null, connection, clientConfiguration)),
many: mapTaggedTemplateLiteralInvocation(many.bind(null, connection, clientConfiguration)),
manyFirst: mapTaggedTemplateLiteralInvocation(manyFirst.bind(null, connection, clientConfiguration)),
maybeOne: mapTaggedTemplateLiteralInvocation(maybeOne.bind(null, connection, clientConfiguration)),
maybeOneFirst: mapTaggedTemplateLiteralInvocation(maybeOneFirst.bind(null, connection, clientConfiguration)),
one: mapTaggedTemplateLiteralInvocation(one.bind(null, connection, clientConfiguration)),
oneFirst: mapTaggedTemplateLiteralInvocation(oneFirst.bind(null, connection, clientConfiguration)),
query: mapTaggedTemplateLiteralInvocation(query.bind(null, connection, clientConfiguration)),
release: connection.release.bind(connection),
transaction: (handler) => {
return transaction(bindConnection, handler);
}
};
return bindConnection;
};
return {
any: mapTaggedTemplateLiteralInvocation(any.bind(null, pool, clientConfiguration)),
anyFirst: mapTaggedTemplateLiteralInvocation(anyFirst.bind(null, pool, clientConfiguration)),
connect,
many: mapTaggedTemplateLiteralInvocation(many.bind(null, pool, clientConfiguration)),
manyFirst: mapTaggedTemplateLiteralInvocation(manyFirst.bind(null, pool, clientConfiguration)),
maybeOne: mapTaggedTemplateLiteralInvocation(maybeOne.bind(null, pool, clientConfiguration)),
maybeOneFirst: mapTaggedTemplateLiteralInvocation(maybeOneFirst.bind(null, pool, clientConfiguration)),
one: mapTaggedTemplateLiteralInvocation(one.bind(null, pool, clientConfiguration)),
oneFirst: mapTaggedTemplateLiteralInvocation(oneFirst.bind(null, pool, clientConfiguration)),
query: mapTaggedTemplateLiteralInvocation(query.bind(null, pool, clientConfiguration)),
transaction: async (handler) => {
log.debug('allocating a new connection to execute the transaction');
const connection = await connect();
let result;
try {
result = await connection.transaction(handler);
} finally {
log.debug('releasing the connection that was earlier secured to execute the transaction');
await connection.release();
}
return result;
}
};
};