@contember/database 1.1.0-rc.0 → 1.2.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/src/client/Connection.d.ts +11 -17
  2. package/dist/src/client/Connection.d.ts.map +1 -1
  3. package/dist/src/client/Connection.js +21 -20
  4. package/dist/src/client/Connection.js.map +1 -1
  5. package/dist/src/client/Pool.d.ts +124 -0
  6. package/dist/src/client/Pool.d.ts.map +1 -0
  7. package/dist/src/client/Pool.js +368 -0
  8. package/dist/src/client/Pool.js.map +1 -0
  9. package/dist/src/client/SingleConnection.d.ts +3 -2
  10. package/dist/src/client/SingleConnection.d.ts.map +1 -1
  11. package/dist/src/client/SingleConnection.js +16 -10
  12. package/dist/src/client/SingleConnection.js.map +1 -1
  13. package/dist/src/client/errors.d.ts +1 -1
  14. package/dist/src/client/errors.d.ts.map +1 -1
  15. package/dist/src/client/errors.js +7 -5
  16. package/dist/src/client/errors.js.map +1 -1
  17. package/dist/src/client/execution.d.ts +0 -1
  18. package/dist/src/client/execution.d.ts.map +1 -1
  19. package/dist/src/client/execution.js +1 -10
  20. package/dist/src/client/execution.js.map +1 -1
  21. package/dist/src/client/index.d.ts +1 -0
  22. package/dist/src/client/index.d.ts.map +1 -1
  23. package/dist/src/client/index.js +1 -0
  24. package/dist/src/client/index.js.map +1 -1
  25. package/dist/src/index.d.ts +1 -1
  26. package/dist/src/index.d.ts.map +1 -1
  27. package/dist/src/index.js +2 -1
  28. package/dist/src/index.js.map +1 -1
  29. package/dist/src/tsconfig.tsbuildinfo +1 -1
  30. package/dist/src/types.d.ts +4 -1
  31. package/dist/src/types.d.ts.map +1 -1
  32. package/dist/src/utils/createDatabaseIfNotExists.d.ts +2 -2
  33. package/dist/src/utils/createDatabaseIfNotExists.d.ts.map +1 -1
  34. package/dist/src/utils/createDatabaseIfNotExists.js +2 -2
  35. package/dist/src/utils/createDatabaseIfNotExists.js.map +1 -1
  36. package/dist/src/utils/index.d.ts +1 -0
  37. package/dist/src/utils/index.d.ts.map +1 -1
  38. package/dist/src/utils/index.js +1 -0
  39. package/dist/src/utils/index.js.map +1 -1
  40. package/dist/src/utils/pgClientFactory.d.ts +5 -0
  41. package/dist/src/utils/pgClientFactory.d.ts.map +1 -0
  42. package/dist/src/utils/pgClientFactory.js +12 -0
  43. package/dist/src/utils/pgClientFactory.js.map +1 -0
  44. package/dist/tests/cases/unit/pool.test.d.ts +2 -0
  45. package/dist/tests/cases/unit/pool.test.d.ts.map +1 -0
  46. package/dist/tests/cases/unit/pool.test.js +323 -0
  47. package/dist/tests/cases/unit/pool.test.js.map +1 -0
  48. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  49. package/package.json +3 -3
  50. package/src/client/Connection.ts +29 -31
  51. package/src/client/Pool.ts +455 -0
  52. package/src/client/SingleConnection.ts +18 -11
  53. package/src/client/errors.ts +10 -6
  54. package/src/client/execution.ts +0 -9
  55. package/src/client/index.ts +1 -0
  56. package/src/index.ts +1 -0
  57. package/src/types.ts +4 -1
  58. package/src/utils/createDatabaseIfNotExists.ts +5 -5
  59. package/src/utils/index.ts +1 -0
  60. package/src/utils/pgClientFactory.ts +10 -0
  61. package/tests/cases/unit/pool.test.ts +350 -0
@@ -9,7 +9,6 @@ import {
9
9
  SerializationFailureError,
10
10
  TransactionAbortedError,
11
11
  UniqueViolationError,
12
- ClientError,
13
12
  } from './errors'
14
13
  import { ClientErrorCodes } from './errorCodes'
15
14
 
@@ -83,11 +82,3 @@ export async function executeQuery<Row extends Record<string, any>>(
83
82
  }
84
83
  }
85
84
  }
86
-
87
- export const executeClientOperation = async <T>(cb: () => Promise<T>): Promise<T> => {
88
- try {
89
- return await cb()
90
- } catch (e) {
91
- throw new ClientError(e)
92
- }
93
- }
@@ -3,5 +3,6 @@ export * from './errorCodes'
3
3
  export * from './errors'
4
4
  export * from './Connection'
5
5
  export * from './EventManager'
6
+ export * from './Pool'
6
7
  export * from './Transaction'
7
8
  export * from './SingleConnection'
package/src/index.ts CHANGED
@@ -17,4 +17,5 @@ export {
17
17
  ConstraintHelper,
18
18
  withDatabaseAdvisoryLock,
19
19
  createDatabaseIfNotExists,
20
+ createPgClientFactory,
20
21
  } from './utils'
package/src/types.ts CHANGED
@@ -15,11 +15,14 @@ export interface Raw {
15
15
  bindings: Value[]
16
16
  }
17
17
 
18
- export interface DatabaseCredentials {
18
+ export interface DatabaseConfig {
19
19
  readonly host: string
20
20
  readonly port: number
21
21
  readonly user: string
22
22
  readonly password: string
23
23
  readonly database: string
24
24
  readonly ssl?: boolean
25
+ readonly queryTimeoutMs?: number
26
+ readonly statementTimeoutMs?: number
27
+ readonly connectionTimeoutMs?: number
25
28
  }
@@ -1,10 +1,10 @@
1
- import { DatabaseCredentials } from '../types'
2
- import { ClientError, ClientErrorCodes, Connection } from '../client'
1
+ import { DatabaseConfig } from '../types'
2
+ import { ClientError, ClientErrorCodes, SingleConnection } from '../client'
3
3
  import { wrapIdentifier } from './sql'
4
4
 
5
- export const createDatabaseIfNotExists = async (db: DatabaseCredentials, log: (message: string) => void) => {
5
+ export const createDatabaseIfNotExists = async (db: DatabaseConfig, log: (message: string) => void) => {
6
6
  try {
7
- const connection = new Connection(db, {})
7
+ const connection = new SingleConnection(db, {})
8
8
  await connection.query('SELECT 1')
9
9
  await connection.end()
10
10
  return
@@ -15,7 +15,7 @@ export const createDatabaseIfNotExists = async (db: DatabaseCredentials, log: (m
15
15
  }
16
16
 
17
17
  log(`Database ${db.database} does not exist, attempting to create it...`)
18
- const connection = new Connection({ ...db, database: 'postgres' }, {})
18
+ const connection = new SingleConnection({ ...db, database: 'postgres' }, {})
19
19
  await connection.query(`CREATE DATABASE ${wrapIdentifier(db.database)}`)
20
20
  await connection.end()
21
21
  }
@@ -4,3 +4,4 @@ export * from './createDatabaseIfNotExists'
4
4
  export * from './sql'
5
5
  export * from './retryTransaction'
6
6
  export * from './withDatabaseAdvisoryLock'
7
+ export * from './pgClientFactory'
@@ -0,0 +1,10 @@
1
+ import { Client as PgClient } from 'pg'
2
+ import { DatabaseConfig } from '../types'
3
+
4
+ export type PgClientFactory = () => PgClient
5
+ export const createPgClientFactory = ({ queryTimeoutMs, statementTimeoutMs, connectionTimeoutMs, ...config }: DatabaseConfig) => () => new PgClient({
6
+ query_timeout: queryTimeoutMs,
7
+ statement_timeout: statementTimeoutMs,
8
+ connectionTimeoutMillis: connectionTimeoutMs,
9
+ ...config,
10
+ })
@@ -0,0 +1,350 @@
1
+ import { expect, it, beforeAll } from 'vitest'
2
+ import { ClientErrorCodes, Pool, PoolLogger } from '../../../src'
3
+ import { Client as PgClient } from 'pg'
4
+ import EventEmitter from 'events'
5
+
6
+ const createPoolLogger = () => {
7
+ const logger: PoolLogger & {messages: string; clear: () => void} = (message, pool) => {
8
+ logger.messages += `${pool.connecting}${pool.active}${pool.idle} ${pool.pending}: ${message}\n`
9
+ }
10
+ logger.messages = '\nCAI P\n'
11
+ logger.clear = () => logger.messages = 'CAI P\n'
12
+ return logger
13
+ }
14
+
15
+ const timeout = async (ms = 1) => await new Promise(resolve => setTimeout(resolve, ms))
16
+
17
+ beforeAll(() => {
18
+ expect.addSnapshotSerializer({
19
+ test: val => typeof val === 'string',
20
+ print: val => String(val),
21
+ })
22
+ })
23
+
24
+ it('acquires and releases new connection from pool', async () => {
25
+ const logger = createPoolLogger()
26
+ const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
27
+ log: logger,
28
+ })
29
+ const connection = await pool.acquire()
30
+ await pool.release(connection)
31
+ await timeout()
32
+ expect(logger.messages).toMatchInlineSnapshot(`
33
+ CAI P
34
+ 000 1: Item added to a queue.
35
+ 000 1: Creating a new connection
36
+ 100 1: Connection established
37
+ 010 0: Queued item fulfilled with new connection.
38
+ 010 0: Not connecting, queue is empty.
39
+ 010 0: Releasing a connection.
40
+ 001 0: Connection is idle and available.
41
+ `)
42
+ })
43
+
44
+
45
+ it('disposes connection when maxIdle is reached', async () => {
46
+ const logger = createPoolLogger()
47
+ const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
48
+ log: logger,
49
+ maxIdle: 0,
50
+ })
51
+ const connection = await pool.acquire()
52
+ await pool.release(connection)
53
+ await timeout()
54
+ expect(logger.messages).toMatchInlineSnapshot(`
55
+ CAI P
56
+ 000 1: Item added to a queue.
57
+ 000 1: Creating a new connection
58
+ 100 1: Connection established
59
+ 010 0: Queued item fulfilled with new connection.
60
+ 010 0: Not connecting, queue is empty.
61
+ 010 0: Releasing a connection.
62
+ 000 0: Too many idle connections, connection disposed.
63
+ `)
64
+ })
65
+
66
+ it('disposes connection after max uses', async () => {
67
+ const logger = createPoolLogger()
68
+ const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
69
+ log: logger,
70
+ maxUses: 1,
71
+ })
72
+ const connection = await pool.acquire()
73
+ await pool.release(connection)
74
+ await timeout()
75
+ expect(logger.messages).toMatchInlineSnapshot(`
76
+ CAI P
77
+ 000 1: Item added to a queue.
78
+ 000 1: Creating a new connection
79
+ 100 1: Connection established
80
+ 010 0: Queued item fulfilled with new connection.
81
+ 010 0: Not connecting, queue is empty.
82
+ 010 0: Releasing a connection.
83
+ 000 0: Not connecting, queue is empty.
84
+ 000 0: Connection has reached max age or usage and was disposed.
85
+ `)
86
+ })
87
+
88
+ it('disposes errored connection', async () => {
89
+ const logger = createPoolLogger()
90
+ const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
91
+ log: logger,
92
+ maxIdle: 0,
93
+ })
94
+ const connection = await pool.acquire()
95
+ await pool.dispose(connection)
96
+ await timeout()
97
+ expect(logger.messages).toMatchInlineSnapshot(`
98
+ CAI P
99
+ 000 1: Item added to a queue.
100
+ 000 1: Creating a new connection
101
+ 100 1: Connection established
102
+ 010 0: Queued item fulfilled with new connection.
103
+ 010 0: Not connecting, queue is empty.
104
+ 010 0: Releasing and disposing a connection.
105
+ 000 0: Not connecting, queue is empty.
106
+ 000 0: Connection errored and was disposed.
107
+ `)
108
+ })
109
+
110
+
111
+ it('time outs when waiting for a connection', async () => {
112
+ const logger = createPoolLogger()
113
+ const clientMock = new PgClientMock()
114
+ clientMock.connections.push(createSuccessfulPromise(5))
115
+ const pool = new Pool(() => clientMock as unknown as PgClient, {
116
+ log: logger,
117
+ acquireTimeoutMs: 2,
118
+ })
119
+ await expect(pool.acquire.bind(pool)).rejects.toThrowError('Failed to acquire a connection')
120
+ await timeout(4)
121
+
122
+ expect(logger.messages).toMatchInlineSnapshot(`
123
+ CAI P
124
+ 000 1: Item added to a queue.
125
+ 000 1: Creating a new connection
126
+ 100 0: Queued item timed out
127
+ 100 0: Connection established
128
+ 001 0: Connection is idle and available.
129
+ 001 0: Not connecting, queue is empty.
130
+ `)
131
+ })
132
+
133
+
134
+ it('acquires idle connection from pool', async () => {
135
+ const logger = createPoolLogger()
136
+ const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
137
+ log: logger,
138
+ })
139
+ const connection = await pool.acquire()
140
+ await pool.release(connection)
141
+ logger.clear()
142
+ const connection2 = await pool.acquire()
143
+ await pool.release(connection2)
144
+ await timeout()
145
+ expect(logger.messages).toMatchInlineSnapshot(`
146
+ CAI P
147
+ 010 0: Item fulfilled with an idle connection.
148
+ 010 0: Releasing a connection.
149
+ 001 0: Connection is idle and available.
150
+ `)
151
+ })
152
+
153
+ it('acquires multiple new connections from pool', async () => {
154
+ const logger = createPoolLogger()
155
+ const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
156
+ log: logger,
157
+ })
158
+ const conn1 = await pool.acquire()
159
+ const conn2 = await pool.acquire()
160
+ await pool.release(conn1)
161
+ await pool.release(conn2)
162
+ await timeout()
163
+ expect(logger.messages).toMatchInlineSnapshot(`
164
+ CAI P
165
+ 000 1: Item added to a queue.
166
+ 000 1: Creating a new connection
167
+ 100 1: Connection established
168
+ 010 0: Queued item fulfilled with new connection.
169
+ 010 0: Not connecting, queue is empty.
170
+ 010 1: Item added to a queue.
171
+ 010 1: Creating a new connection
172
+ 110 1: Connection established
173
+ 020 0: Queued item fulfilled with new connection.
174
+ 020 0: Not connecting, queue is empty.
175
+ 020 0: Releasing a connection.
176
+ 011 0: Connection is idle and available.
177
+ 011 0: Releasing a connection.
178
+ 002 0: Connection is idle and available.
179
+ `)
180
+ })
181
+
182
+
183
+ it('releases idle connection', async () => {
184
+ const logger = createPoolLogger()
185
+ const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
186
+ log: logger,
187
+ idleTimeoutMs: 2,
188
+ })
189
+ const conn1 = await pool.acquire()
190
+ await pool.release(conn1)
191
+ await timeout(4)
192
+ expect(logger.messages).toMatchInlineSnapshot(`
193
+ CAI P
194
+ 000 1: Item added to a queue.
195
+ 000 1: Creating a new connection
196
+ 100 1: Connection established
197
+ 010 0: Queued item fulfilled with new connection.
198
+ 010 0: Not connecting, queue is empty.
199
+ 010 0: Releasing a connection.
200
+ 001 0: Connection is idle and available.
201
+ 000 0: Idle connection disposed after timeout.
202
+ `)
203
+ })
204
+
205
+
206
+ it('waits for idle connection when pool is full', async () => {
207
+ const logger = createPoolLogger()
208
+ const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
209
+ maxConnections: 1,
210
+ log: logger,
211
+ })
212
+ const conn1 = await pool.acquire()
213
+ setTimeout(async () => {
214
+ await pool.release(conn1)
215
+ }, 20)
216
+ const conn2 = await pool.acquire()
217
+ await pool.release(conn2)
218
+ await timeout()
219
+ expect(logger.messages).toMatchInlineSnapshot(`
220
+ CAI P
221
+ 000 1: Item added to a queue.
222
+ 000 1: Creating a new connection
223
+ 100 1: Connection established
224
+ 010 0: Queued item fulfilled with new connection.
225
+ 010 0: Not connecting, queue is empty.
226
+ 010 1: Item added to a queue.
227
+ 010 1: Not connecting, max connections reached.
228
+ 010 1: Releasing a connection.
229
+ 010 0: Queued item fulfilled with released connection.
230
+ 010 0: Releasing a connection.
231
+ 001 0: Connection is idle and available.
232
+ `)
233
+ })
234
+
235
+
236
+ it('tries to reconnect on recoverable error', async () => {
237
+ const logger = createPoolLogger()
238
+ const pgClientMock = new PgClientMock()
239
+ pgClientMock.on('error', () => {
240
+
241
+ })
242
+ const pool = new Pool(() => pgClientMock as unknown as PgClient, {
243
+ log: logger,
244
+ })
245
+ pgClientMock.connections.push(createRecoverableErrorPromise(), createRecoverableErrorPromise())
246
+ await pool.acquire()
247
+ await timeout()
248
+ expect(logger.messages).toMatchInlineSnapshot(`
249
+ CAI P
250
+ 000 1: Item added to a queue.
251
+ 000 1: Creating a new connection
252
+ 100 1: Connection error occurred: too many connection
253
+ 100 1: Recoverable error, retrying in a moment.
254
+ 000 1: Retrying
255
+ 000 1: Creating a new connection
256
+ 100 1: Connection error occurred: too many connection
257
+ 100 1: Recoverable error, retrying in a moment.
258
+ 000 1: Retrying
259
+ 000 1: Creating a new connection
260
+ 100 1: Connection established
261
+ 010 0: Queued item fulfilled with new connection.
262
+ 010 0: Not connecting, queue is empty.
263
+ `)
264
+ })
265
+
266
+
267
+ it('fails to reconnect on recoverable error', async () => {
268
+ const logger = createPoolLogger()
269
+ const pgClientMock = new PgClientMock()
270
+ pgClientMock.on('error', () => {
271
+
272
+ })
273
+ const pool = new Pool(() => pgClientMock as unknown as PgClient, {
274
+ log: logger,
275
+ reconnectIntervalMs: 5,
276
+ acquireTimeoutMs: 10,
277
+ })
278
+ pgClientMock.connections.push(createRecoverableErrorPromise(), createRecoverableErrorPromise())
279
+ await expect(async () => await pool.acquire()).rejects.toThrowError('Failed to acquire a connection. Last error: too many connection')
280
+ await timeout(2)
281
+ expect(logger.messages).toMatchInlineSnapshot(`
282
+ CAI P
283
+ 000 1: Item added to a queue.
284
+ 000 1: Creating a new connection
285
+ 100 1: Connection error occurred: too many connection
286
+ 100 1: Recoverable error, retrying in a moment.
287
+ 000 1: Retrying
288
+ 000 1: Creating a new connection
289
+ 100 1: Connection error occurred: too many connection
290
+ 100 1: Recoverable error, max retries reached.
291
+ 000 0: Queued item timed out
292
+ `)
293
+ })
294
+
295
+ it('fails to reconnect on unrecoverable error', async () => {
296
+ const logger = createPoolLogger()
297
+ const pgClientMock = new PgClientMock()
298
+ const pool = new Pool(() => pgClientMock as unknown as PgClient, {
299
+ log: logger,
300
+ acquireTimeoutMs: 3,
301
+ })
302
+ pgClientMock.connections.push(createErrorPromise())
303
+ const poolError = new Promise((resolve, reject) => pool.once('error', e => {
304
+ reject(e)
305
+ }))
306
+
307
+ await expect(pool.acquire.bind(pool)).rejects.toThrowError('Failed to acquire a connection')
308
+ await expect(poolError).rejects.toThrowError('my err')
309
+
310
+ await timeout(4)
311
+ expect(logger.messages).toMatchInlineSnapshot(`
312
+ CAI P
313
+ 000 1: Item added to a queue.
314
+ 000 1: Creating a new connection
315
+ 100 1: Connection error occurred: my err
316
+ 000 1: Connecting failed, emitting error
317
+ 000 0: Queued item timed out
318
+ `)
319
+ })
320
+
321
+
322
+
323
+ const createSuccessfulPromise = (timeout = 1) => () => new Promise<void>(resolve => {
324
+ setTimeout(resolve, timeout)
325
+ })
326
+
327
+ const createRecoverableErrorPromise = () => () => new Promise<void>((resolve, reject) => {
328
+ setTimeout(() => {
329
+ const err: Error & {code?: string} = new Error('too many connection')
330
+ err.code = ClientErrorCodes.TOO_MANY_CONNECTIONS
331
+ reject(err)
332
+ }, 1)
333
+ })
334
+
335
+ const createErrorPromise = () => () => new Promise<void>((resolve, reject) => {
336
+ setTimeout(() => reject(new Error('my err')), 1)
337
+ })
338
+
339
+ const PgClientMock = class extends EventEmitter {
340
+ public connections: (() => Promise<void>)[] = []
341
+
342
+ async connect() {
343
+ const connection = this.connections.shift()
344
+ return connection ? connection() : createSuccessfulPromise()
345
+ }
346
+
347
+ async end() {
348
+ return createSuccessfulPromise()
349
+ }
350
+ }