forked from gajus/slonik
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtypes.ts
525 lines (466 loc) · 16.5 KB
/
types.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
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
import {
type SlonikError,
} from './errors.js';
import type * as tokens from './tokens.js';
import {
type Pool as PgPool,
type PoolClient as PgPoolClient,
type PoolConfig,
} from 'pg';
import {
type NoticeMessage as Notice,
} from 'pg-protocol/dist/messages.js';
import {
type Logger,
} from 'roarr';
import {
type Readable,
type ReadableOptions,
} from 'stream';
import {
type ConnectionOptions as TlsConnectionOptions,
} from 'tls';
/**
* @see https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS
*/
export type ConnectionOptions = {
applicationName?: string,
databaseName?: string,
host?: string,
password?: string,
port?: number,
sslMode?: 'disable' | 'no-verify' | 'require',
username?: string,
};
/**
* "string" type covers all type name identifiers – the literal values are added only to assist developer
* experience with auto suggestions for commonly used type name identifiers.
*/
export type TypeNameIdentifier =
| string
| 'bool'
| 'bytea'
| 'float4'
| 'float8'
| 'int2'
| 'int4'
| 'int8'
| 'json'
| 'text'
| 'timestamptz'
| 'uuid';
export type SerializableValue =
boolean | number | string | readonly SerializableValue[] | {
[key: string]: SerializableValue | undefined,
} | null;
export type QueryId = string;
export type MaybePromise<T> = Promise<T> | T;
export type StreamHandler = (stream: Readable) => void;
export type Connection = 'EXPLICIT' | 'IMPLICIT_QUERY' | 'IMPLICIT_TRANSACTION';
export type Field = {
readonly dataTypeId: number,
readonly name: string,
};
export type QueryResult<T> = {
readonly command: 'COPY' | 'DELETE' | 'INSERT' | 'SELECT' | 'UPDATE',
readonly fields: readonly Field[],
readonly notices: readonly Notice[],
readonly rowCount: number,
readonly rows: readonly T[],
};
export type ClientConfiguration = {
/**
* Override the underlying PostgreSQL driver. *
*/
readonly PgPool?: new (poolConfig: PoolConfig) => PgPool,
/**
* Dictates whether to capture stack trace before executing query. Middlewares access stack trace through query execution context. (Default: true)
*/
readonly captureStackTrace: boolean,
/**
* Number of times to retry establishing a new connection. (Default: 3)
*/
readonly connectionRetryLimit: number,
/**
* Timeout (in milliseconds) after which an error is raised if connection cannot cannot be established. (Default: 5000)
*/
readonly connectionTimeout: number | 'DISABLE_TIMEOUT',
/**
* Timeout (in milliseconds) after which idle clients are closed. Use 'DISABLE_TIMEOUT' constant to disable the timeout. (Default: 60000)
*/
readonly idleInTransactionSessionTimeout: number | 'DISABLE_TIMEOUT',
/**
* Timeout (in milliseconds) after which idle clients are closed. Use 'DISABLE_TIMEOUT' constant to disable the timeout. (Default: 5000)
*/
readonly idleTimeout: number | 'DISABLE_TIMEOUT',
/**
* An array of [Slonik interceptors](https://github.com/gajus/slonik#slonik-interceptors).
*/
readonly interceptors: readonly Interceptor[],
/**
* Do not allow more than this many connections. Use 'DISABLE_TIMEOUT' constant to disable the timeout. (Default: 10)
*/
readonly maximumPoolSize: number,
/**
* Number of times a query failing with Transaction Rollback class error, that doesn't belong to a transaction, is retried. (Default: 5)
*/
readonly queryRetryLimit: number,
/**
* tls.connect options *
*/
readonly ssl?: TlsConnectionOptions,
/**
* Timeout (in milliseconds) after which database is instructed to abort the query. Use 'DISABLE_TIMEOUT' constant to disable the timeout. (Default: 60000)
*/
readonly statementTimeout: number | 'DISABLE_TIMEOUT',
/**
* Number of times a transaction failing with Transaction Rollback class error is retried. (Default: 5)
*/
readonly transactionRetryLimit: number,
/**
* An array of [Slonik type parsers](https://github.com/gajus/slonik#slonik-type-parsers).
*/
readonly typeParsers: readonly TypeParser[],
};
export type ClientConfigurationInput = Partial<ClientConfiguration>;
export type QueryStreamConfig = ReadableOptions & {batchSize?: number, };
export type StreamFunction = (
sql: TaggedTemplateLiteralInvocation,
streamHandler: StreamHandler,
config?: QueryStreamConfig
) => Promise<Record<string, unknown> | null>;
export type CommonQueryMethods = {
readonly any: QueryAnyFunction,
readonly anyFirst: QueryAnyFirstFunction,
readonly exists: QueryExistsFunction,
readonly many: QueryManyFunction,
readonly manyFirst: QueryManyFirstFunction,
readonly maybeOne: QueryMaybeOneFunction,
readonly maybeOneFirst: QueryMaybeOneFirstFunction,
readonly one: QueryOneFunction,
readonly oneFirst: QueryOneFirstFunction,
readonly query: QueryFunction,
readonly transaction: <T>(handler: TransactionFunction<T>, transactionRetryLimit?: number) => Promise<T>,
};
export type DatabaseTransactionConnection = CommonQueryMethods & {
readonly stream: StreamFunction,
};
export type TransactionFunction<T> = (connection: DatabaseTransactionConnection) => Promise<T>;
export type DatabasePoolConnection = CommonQueryMethods & {
readonly stream: StreamFunction,
};
export type ConnectionRoutine<T> = (connection: DatabasePoolConnection) => Promise<T>;
export type PoolState = {
readonly activeConnectionCount: number,
readonly ended: boolean,
readonly idleConnectionCount: number,
readonly waitingClientCount: number,
};
export type DatabasePool = CommonQueryMethods & {
readonly configuration: ClientConfiguration,
readonly connect: <T>(connectionRoutine: ConnectionRoutine<T>) => Promise<T>,
readonly end: () => Promise<void>,
readonly getPoolState: () => PoolState,
readonly stream: StreamFunction,
};
export type DatabaseConnection = DatabasePool | DatabasePoolConnection;
export type QueryResultRowColumn = PrimitiveValueExpression;
export type QueryResultRow = Record<string, QueryResultRowColumn>;
export type Query = {
readonly sql: string,
readonly values: readonly PrimitiveValueExpression[],
};
export type SqlFragment = {
readonly sql: string,
readonly values: readonly PrimitiveValueExpression[],
};
/**
* @property name Value of "pg_type"."typname" (e.g. "int8", "timestamp", "timestamptz").
*/
export type TypeParser<T = unknown> = {
readonly name: string,
readonly parse: (value: string) => T,
};
/**
* @property log Instance of Roarr logger with bound connection context parameters.
* @property poolId Unique connection pool ID.
* @property query The query that is initiating the connection.
*/
export type PoolContext = {
readonly log: Logger,
readonly poolId: string,
readonly query: TaggedTemplateLiteralInvocation | null,
};
/**
* @property connectionId Unique connection ID.
* @property log Instance of Roarr logger with bound connection context parameters.
* @property poolId Unique connection pool ID.
*/
export type ConnectionContext = {
readonly connectionId: string,
readonly connectionType: Connection,
readonly log: Logger,
readonly poolId: string,
};
type CallSite = {
readonly columnNumber: number,
readonly fileName: string | null,
readonly functionName: string | null,
readonly lineNumber: number,
};
export type IntervalInput = {
days?: number,
hours?: number,
minutes?: number,
months?: number,
seconds?: number,
weeks?: number,
years?: number,
};
/**
* @property connectionId Unique connection ID.
* @property log Instance of Roarr logger with bound query context parameters.
* @property originalQuery A copy of the query before `transformQuery` middleware.
* @property poolId Unique connection pool ID.
* @property queryId Unique query ID.
* @property queryInputTime `process.hrtime.bigint()` for when query was received.
* @property sandbox Object used by interceptors to assign interceptor-specific, query-specific context.
* @property transactionId Unique transaction ID.
*/
export type QueryContext = {
readonly connectionId: string,
readonly log: Logger,
readonly originalQuery: Query,
readonly poolId: string,
readonly queryId: QueryId,
readonly queryInputTime: bigint | number,
readonly sandbox: Record<string, unknown>,
readonly stackTrace: readonly CallSite[] | null,
readonly transactionId: string | null,
};
export type ArraySqlToken = {
readonly memberType: SqlToken | TypeNameIdentifier,
readonly type: typeof tokens.ArrayToken,
readonly values: readonly PrimitiveValueExpression[],
};
export type BinarySqlToken = {
readonly data: Buffer,
readonly type: typeof tokens.BinaryToken,
};
export type DateSqlToken = {
readonly date: Date,
readonly type: typeof tokens.DateToken,
};
export type IdentifierSqlToken = {
readonly names: readonly string[],
readonly type: typeof tokens.IdentifierToken,
};
export type ListSqlToken = {
readonly glue: SqlSqlToken,
readonly members: readonly ValueExpression[],
readonly type: typeof tokens.ListToken,
};
export type JsonBinarySqlToken = {
readonly type: typeof tokens.JsonBinaryToken,
readonly value: SerializableValue,
};
export type JsonSqlToken = {
readonly type: typeof tokens.JsonToken,
readonly value: SerializableValue,
};
export type SqlSqlToken = {
readonly sql: string,
readonly type: typeof tokens.SqlToken,
readonly values: readonly PrimitiveValueExpression[],
};
export type TimestampSqlToken = {
readonly date: Date,
readonly type: typeof tokens.TimestampToken,
};
export type UnnestSqlToken = {
readonly columnTypes: Array<[...string[], TypeNameIdentifier]> | Array<SqlSqlToken | TypeNameIdentifier>,
readonly tuples: ReadonlyArray<readonly ValueExpression[]>,
readonly type: typeof tokens.UnnestToken,
};
export type PrimitiveValueExpression =
Buffer |
boolean |
number |
string |
readonly PrimitiveValueExpression[] |
null;
export type SqlToken =
| ArraySqlToken
| BinarySqlToken
| DateSqlToken
| IdentifierSqlToken
| JsonBinarySqlToken
| JsonSqlToken
| ListSqlToken
| SqlSqlToken
| TimestampSqlToken
| UnnestSqlToken;
export type ValueExpression = PrimitiveValueExpression | SqlToken;
export type NamedAssignment = {
readonly [key: string]: ValueExpression,
};
// @todo may want to think how to make this extendable.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type UserQueryResultRow = Record<string, any>;
export type SqlTaggedTemplate<T extends UserQueryResultRow = QueryResultRow> = {
<U extends UserQueryResultRow = T>(template: TemplateStringsArray, ...values: ValueExpression[]): TaggedTemplateLiteralInvocation<U>,
array: (
values: readonly PrimitiveValueExpression[],
memberType: SqlToken | TypeNameIdentifier,
) => ArraySqlToken,
binary: (data: Buffer) => BinarySqlToken,
date: (date: Date) => DateSqlToken,
identifier: (names: readonly string[]) => IdentifierSqlToken,
join: (members: readonly ValueExpression[], glue: SqlSqlToken) => ListSqlToken,
json: (value: SerializableValue) => JsonSqlToken,
jsonb: (value: SerializableValue) => JsonBinarySqlToken,
literalValue: (value: string) => SqlSqlToken,
/**
* **CAUTION:** Use this function with care.
*
* Directly injects a raw SQL string into the query.
*/
raw: (rawSql: string) => SqlSqlToken,
timestamp: (date: Date) => TimestampSqlToken,
unnest: (
// Value might be ReadonlyArray<ReadonlyArray<PrimitiveValueExpression>>,
// or it can be infinitely nested array, e.g.
// https://github.com/gajus/slonik/issues/44
// eslint-disable-next-line @typescript-eslint/no-explicit-any
tuples: ReadonlyArray<readonly any[]>,
columnTypes: Array<[...string[], TypeNameIdentifier]> | Array<SqlSqlToken | TypeNameIdentifier>
) => UnnestSqlToken,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type InternalQueryMethod<R = any> = (
log: Logger,
connection: PgPoolClient,
clientConfiguration: ClientConfiguration,
slonikSql: TaggedTemplateLiteralInvocation,
uid?: QueryId,
) => R;
export type InternalStreamFunction = (
log: Logger,
connection: PgPoolClient,
clientConfiguration: ClientConfiguration,
slonikSql: TaggedTemplateLiteralInvocation,
streamHandler: StreamHandler,
uid?: QueryId,
config?: QueryStreamConfig,
) => Promise<Record<string, unknown>>;
export type InternalTransactionFunction = <T>(
log: Logger,
connection: PgPoolClient,
clientConfiguration: ClientConfiguration,
handler: TransactionFunction<T>,
transactionRetryLimit?: number,
) => Promise<T>;
export type InternalNestedTransactionFunction = <T>(
log: Logger,
connection: PgPoolClient,
clientConfiguration: ClientConfiguration,
handler: TransactionFunction<T>,
transactionDepth: number,
transactionRetryLimit?: number,
) => Promise<T>;
// eslint-disable-next-line @typescript-eslint/no-empty-interface, @typescript-eslint/consistent-type-definitions, @typescript-eslint/no-unused-vars
export interface TaggedTemplateLiteralInvocation<Result extends UserQueryResultRow = QueryResultRow> extends SqlSqlToken { }
export type QueryAnyFirstFunction = <T, Row extends UserQueryResultRow = Record<string, T>>(
sql: TaggedTemplateLiteralInvocation<Row>,
values?: PrimitiveValueExpression[],
) => Promise<ReadonlyArray<Row[keyof Row]>>;
export type QueryAnyFunction = <T extends UserQueryResultRow = UserQueryResultRow>(
sql: TaggedTemplateLiteralInvocation<T>,
values?: PrimitiveValueExpression[],
) => Promise<readonly T[]>;
export type QueryExistsFunction = (
sql: TaggedTemplateLiteralInvocation,
values?: PrimitiveValueExpression[],
) => Promise<boolean>;
export type QueryFunction = <T extends UserQueryResultRow = UserQueryResultRow>(
sql: TaggedTemplateLiteralInvocation<T>,
values?: PrimitiveValueExpression[],
) => Promise<QueryResult<T>>;
export type QueryManyFirstFunction = <T, Row extends UserQueryResultRow = Record<string, T>>(
sql: TaggedTemplateLiteralInvocation<Row>,
values?: PrimitiveValueExpression[],
) => Promise<ReadonlyArray<Row[keyof Row]>>;
export type QueryManyFunction = <T extends UserQueryResultRow>(
sql: TaggedTemplateLiteralInvocation<T>,
values?: PrimitiveValueExpression[],
) => Promise<readonly T[]>;
export type QueryMaybeOneFirstFunction = <T, Row extends UserQueryResultRow = Record<string, T>>(
sql: TaggedTemplateLiteralInvocation<Row>,
values?: PrimitiveValueExpression[],
) => Promise<Row[keyof Row] | null>;
export type QueryMaybeOneFunction = <T extends UserQueryResultRow>(
sql: TaggedTemplateLiteralInvocation<T>,
values?: PrimitiveValueExpression[],
) => Promise<T | null>;
export type QueryOneFirstFunction = <T, Row extends UserQueryResultRow = Record<string, T>>(
sql: TaggedTemplateLiteralInvocation<Row>,
values?: PrimitiveValueExpression[],
) => Promise<Row[keyof Row]>;
export type QueryOneFunction = <T extends UserQueryResultRow = UserQueryResultRow>(
sql: TaggedTemplateLiteralInvocation<T>,
values?: PrimitiveValueExpression[],
) => Promise<T>;
export type Interceptor = {
readonly afterPoolConnection?: (
connectionContext: ConnectionContext,
connection: DatabasePoolConnection,
) => MaybePromise<null>,
readonly afterQueryExecution?: (
queryContext: QueryContext,
query: Query,
result: QueryResult<QueryResultRow>,
) => MaybePromise<null>,
readonly beforePoolConnection?: (
connectionContext: PoolContext,
) => MaybePromise<DatabasePool | null | undefined>,
readonly beforePoolConnectionRelease?: (
connectionContext: ConnectionContext,
connection: DatabasePoolConnection,
) => MaybePromise<null>,
readonly beforeQueryExecution?: (
queryContext: QueryContext,
query: Query,
) => MaybePromise<QueryResult<QueryResultRow> | null>,
readonly beforeQueryResult?: (
queryContext: QueryContext,
query: Query,
result: QueryResult<QueryResultRow>,
) => MaybePromise<null>,
readonly beforeTransformQuery?: (queryContext: QueryContext, query: Query) => MaybePromise<null>,
readonly queryExecutionError?: (
queryContext: QueryContext,
query: Query,
error: SlonikError,
notices: readonly Notice[],
) => MaybePromise<null>,
readonly transformQuery?: (queryContext: QueryContext, query: Query) => Query,
readonly transformRow?: (
queryContext: QueryContext,
query: Query,
row: QueryResultRow,
fields: readonly Field[],
) => QueryResultRow,
};
export type IdentifierNormalizer = (identifierName: string) => string;
export type MockPoolOverrides = {
readonly query: (sql: string, values: readonly PrimitiveValueExpression[]) => Promise<QueryResult<QueryResultRow>>,
};
export type {
Logger,
} from 'roarr';
export type TypeOverrides = {
setTypeParser: (type: string, parser: (value: string) => unknown) => void,
};
export {
NoticeMessage as Notice,
} from 'pg-protocol/dist/messages.js';