@contember/database 1.1.1 → 1.2.0-alpha.10

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 (123) hide show
  1. package/dist/src/builders/DeleteBuilder.d.ts +1 -1
  2. package/dist/src/builders/DeleteBuilder.d.ts.map +1 -1
  3. package/dist/src/builders/DeleteBuilder.js.map +1 -1
  4. package/dist/src/builders/InsertBuilder.d.ts +1 -1
  5. package/dist/src/builders/InsertBuilder.d.ts.map +1 -1
  6. package/dist/src/builders/InsertBuilder.js.map +1 -1
  7. package/dist/src/builders/UpdateBuilder.d.ts +1 -1
  8. package/dist/src/builders/UpdateBuilder.d.ts.map +1 -1
  9. package/dist/src/builders/UpdateBuilder.js.map +1 -1
  10. package/dist/src/client/AcquiredConnection.d.ts +17 -0
  11. package/dist/src/client/AcquiredConnection.d.ts.map +1 -0
  12. package/dist/src/client/AcquiredConnection.js +78 -0
  13. package/dist/src/client/AcquiredConnection.js.map +1 -0
  14. package/dist/src/client/Client.d.ts +3 -1
  15. package/dist/src/client/Client.d.ts.map +1 -1
  16. package/dist/src/client/Client.js +9 -5
  17. package/dist/src/client/Client.js.map +1 -1
  18. package/dist/src/client/Connection.d.ts +26 -30
  19. package/dist/src/client/Connection.d.ts.map +1 -1
  20. package/dist/src/client/Connection.js +31 -38
  21. package/dist/src/client/Connection.js.map +1 -1
  22. package/dist/src/client/PgClient.d.ts +9 -0
  23. package/dist/src/client/PgClient.d.ts.map +1 -0
  24. package/dist/src/client/PgClient.js +3 -0
  25. package/dist/src/client/PgClient.js.map +1 -0
  26. package/dist/src/client/Pool.d.ts +126 -0
  27. package/dist/src/client/Pool.d.ts.map +1 -0
  28. package/dist/src/client/Pool.js +380 -0
  29. package/dist/src/client/Pool.js.map +1 -0
  30. package/dist/src/client/Transaction.d.ts +20 -11
  31. package/dist/src/client/Transaction.d.ts.map +1 -1
  32. package/dist/src/client/Transaction.js +80 -55
  33. package/dist/src/client/Transaction.js.map +1 -1
  34. package/dist/src/client/errors.d.ts +1 -1
  35. package/dist/src/client/errors.d.ts.map +1 -1
  36. package/dist/src/client/errors.js +7 -5
  37. package/dist/src/client/errors.js.map +1 -1
  38. package/dist/src/client/index.d.ts +1 -1
  39. package/dist/src/client/index.d.ts.map +1 -1
  40. package/dist/src/client/index.js +1 -1
  41. package/dist/src/client/index.js.map +1 -1
  42. package/dist/src/index.d.ts +1 -1
  43. package/dist/src/index.d.ts.map +1 -1
  44. package/dist/src/index.js +3 -1
  45. package/dist/src/index.js.map +1 -1
  46. package/dist/src/tsconfig.tsbuildinfo +1 -1
  47. package/dist/src/types.d.ts +4 -1
  48. package/dist/src/types.d.ts.map +1 -1
  49. package/dist/src/utils/Mutex.d.ts +11 -0
  50. package/dist/src/utils/Mutex.d.ts.map +1 -0
  51. package/dist/src/utils/Mutex.js +49 -0
  52. package/dist/src/utils/Mutex.js.map +1 -0
  53. package/dist/src/utils/asyncIterableTransaction.d.ts +7 -0
  54. package/dist/src/utils/asyncIterableTransaction.d.ts.map +1 -0
  55. package/dist/src/utils/asyncIterableTransaction.js +32 -0
  56. package/dist/src/utils/asyncIterableTransaction.js.map +1 -0
  57. package/dist/src/utils/createDatabaseIfNotExists.d.ts +2 -2
  58. package/dist/src/utils/createDatabaseIfNotExists.d.ts.map +1 -1
  59. package/dist/src/utils/createDatabaseIfNotExists.js +2 -2
  60. package/dist/src/utils/createDatabaseIfNotExists.js.map +1 -1
  61. package/dist/src/utils/index.d.ts +3 -0
  62. package/dist/src/utils/index.d.ts.map +1 -1
  63. package/dist/src/utils/index.js +3 -0
  64. package/dist/src/utils/index.js.map +1 -1
  65. package/dist/src/utils/pgClientFactory.d.ts +6 -0
  66. package/dist/src/utils/pgClientFactory.d.ts.map +1 -0
  67. package/dist/src/utils/pgClientFactory.js +12 -0
  68. package/dist/src/utils/pgClientFactory.js.map +1 -0
  69. package/dist/src/utils/sql.d.ts +1 -1
  70. package/dist/src/utils/sql.d.ts.map +1 -1
  71. package/dist/src/utils/withDatabaseAdvisoryLock.d.ts +1 -1
  72. package/dist/src/utils/withDatabaseAdvisoryLock.d.ts.map +1 -1
  73. package/dist/src/utils/withDatabaseAdvisoryLock.js +1 -1
  74. package/dist/src/utils/withDatabaseAdvisoryLock.js.map +1 -1
  75. package/dist/tests/cases/unit/connection.test.d.ts +2 -0
  76. package/dist/tests/cases/unit/connection.test.d.ts.map +1 -0
  77. package/dist/tests/cases/unit/connection.test.js +128 -0
  78. package/dist/tests/cases/unit/connection.test.js.map +1 -0
  79. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts +6 -0
  80. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts.map +1 -0
  81. package/dist/tests/cases/unit/createConnectionMockAlt.js +47 -0
  82. package/dist/tests/cases/unit/createConnectionMockAlt.js.map +1 -0
  83. package/dist/tests/cases/unit/eventManager.test.js +91 -17
  84. package/dist/tests/cases/unit/eventManager.test.js.map +1 -1
  85. package/dist/tests/cases/unit/pool.test.d.ts +2 -0
  86. package/dist/tests/cases/unit/pool.test.d.ts.map +1 -0
  87. package/dist/tests/cases/unit/pool.test.js +323 -0
  88. package/dist/tests/cases/unit/pool.test.js.map +1 -0
  89. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  90. package/package.json +4 -4
  91. package/src/builders/DeleteBuilder.ts +1 -1
  92. package/src/builders/InsertBuilder.ts +1 -1
  93. package/src/builders/UpdateBuilder.ts +1 -1
  94. package/src/client/AcquiredConnection.ts +104 -0
  95. package/src/client/Client.ts +34 -18
  96. package/src/client/Connection.ts +57 -63
  97. package/src/client/PgClient.ts +13 -0
  98. package/src/client/Pool.ts +465 -0
  99. package/src/client/Transaction.ts +101 -69
  100. package/src/client/errors.ts +10 -6
  101. package/src/client/index.ts +1 -1
  102. package/src/index.ts +2 -0
  103. package/src/types.ts +4 -1
  104. package/src/utils/Mutex.ts +49 -0
  105. package/src/utils/asyncIterableTransaction.ts +33 -0
  106. package/src/utils/createDatabaseIfNotExists.ts +4 -4
  107. package/src/utils/index.ts +3 -0
  108. package/src/utils/pgClientFactory.ts +11 -0
  109. package/src/utils/withDatabaseAdvisoryLock.ts +4 -4
  110. package/tests/cases/unit/connection.test.ts +154 -0
  111. package/tests/cases/unit/createConnectionMockAlt.ts +44 -0
  112. package/tests/cases/unit/eventManager.test.ts +101 -19
  113. package/tests/cases/unit/pool.test.ts +349 -0
  114. package/dist/src/client/SingleConnection.d.ts +0 -20
  115. package/dist/src/client/SingleConnection.d.ts.map +0 -1
  116. package/dist/src/client/SingleConnection.js +0 -67
  117. package/dist/src/client/SingleConnection.js.map +0 -1
  118. package/dist/src/client/execution.d.ts +0 -8
  119. package/dist/src/client/execution.d.ts.map +0 -1
  120. package/dist/src/client/execution.js +0 -74
  121. package/dist/src/client/execution.js.map +0 -1
  122. package/src/client/SingleConnection.ts +0 -82
  123. package/src/client/execution.ts +0 -93
@@ -0,0 +1,465 @@
1
+ import { ImplementationException } from '../exceptions'
2
+ import { ClientErrorCodes } from './errorCodes'
3
+ import EventEmitter from 'events'
4
+ import { ClientError, DatabaseError } from './errors'
5
+ import { PgClientFactory } from '../utils'
6
+ import { PgClient } from './PgClient'
7
+
8
+ export type PoolLogger = (message: string, status: PoolStatus) => void
9
+
10
+ export type PoolConfig = Partial<PoolConfigInternal>
11
+
12
+ interface PoolConfigInternal {
13
+ /** maximum number of connections in a pool */
14
+ maxConnections: number
15
+ /** maximum number of connections concurrently establishing*/
16
+ maxConnecting: number
17
+ /** maximum number of idle connections. when reached, will be disposed immediately */
18
+ maxIdle: number
19
+ /** interval between retries of recoverable errors */
20
+ reconnectIntervalMs: number
21
+ /** timeout to dispose idle connections */
22
+ idleTimeoutMs: number
23
+ /** timeout of pending item waiting for a connection. also used for retries of recoverable errors */
24
+ acquireTimeoutMs: number
25
+ /** how many times can a single connection be acquired */
26
+ maxUses?: number
27
+ /** max age of connection. when reached, connection will be disposed after returning to a pool */
28
+ maxAgeMs?: number
29
+ /** internal logging, mainly for debugging and testing */
30
+ log?: PoolLogger
31
+ }
32
+
33
+ export type PoolStats = { [K in keyof typeof poolStatsDescription]: number }
34
+
35
+ export interface PoolStatus {
36
+ /** maximum number of connections in a pool */
37
+ max: number
38
+ /** number of items waiting for a connections */
39
+ pending: number
40
+ /** number of active (acquired) connections */
41
+ active: number
42
+ /** number of available idle connections */
43
+ idle: number
44
+ /** number of currently establishing connections */
45
+ connecting: number
46
+ stats: PoolStats
47
+ }
48
+
49
+ export const poolStatsDescription = {
50
+ connection_established_count: 'Total number of established connections.',
51
+ connection_recoverable_error_count: 'Number of connections that failed on recoverable error (e.g. 53300) and retry was tried.',
52
+ connection_error_count: 'Number of non-recoverable errors or recoverable errors reaching max attempts.',
53
+ connection_disposed_idle_timeout_count: 'Number of idle connection, that was disposed after configured timeout.',
54
+ connection_disposed_idle_max_count: 'Number of idle connections, that was immediately disposed, because maximum number of idle connection was reached.',
55
+ connection_disposed_old_count: 'Number of connections, that was too old after it was released.',
56
+ connection_disposed_manual_count: 'Number of manually disposed connection (e.g. due to exception on given connection).',
57
+ connection_released_count: 'Number of connection returned to the pool.',
58
+ connection_reused_immediately_count: 'Number of connections, that was reused by pending item immediately after it was returned to the pool.',
59
+ connection_reused_later_count: 'Number of idle connections, that was reused later.',
60
+
61
+ connection_established_idle_count: 'Number of newly established connections, which was not used (e.g. some connection was returned earlier).',
62
+
63
+ item_queued_count: 'Number of queued items requesting a connection.',
64
+ item_timeout_count: 'Number of items waiting for connection, which timed out.',
65
+ item_rejected_count: 'Number of items rejected with an error.',
66
+
67
+ item_resolved_new_ms_count: 'Number of queued items resolved with newly established connection.',
68
+ item_resolved_new_ms_sum: 'Waiting time of queued items, which was resolved with a new connection.',
69
+ item_resolved_released_ms_count: 'Number of queued items resolved with released connection.',
70
+ item_resolved_released_ms_sum: 'Waiting time of queued items, which was resolved with a released connection.',
71
+ }
72
+
73
+ class PoolConnection {
74
+ public disposed = false
75
+ public uses = 0
76
+ public createdAt = Date.now()
77
+ public timerId: NodeJS.Timeout | undefined
78
+
79
+ constructor(
80
+ public readonly client: PgClient,
81
+ ) {
82
+ }
83
+ }
84
+
85
+ class PendingItem {
86
+ public readonly createdAt = Date.now()
87
+
88
+ constructor(
89
+ public resolve: (connection: PoolConnection) => void,
90
+ public reject: (error: Error) => void,
91
+ ) {
92
+ }
93
+ }
94
+
95
+ interface Pool {
96
+ on(event: 'error', listener: (err: Error) => void): this
97
+
98
+ on(event: 'recoverableError', listener: (err: Error) => void): this
99
+ }
100
+
101
+ class Pool extends EventEmitter {
102
+
103
+ /**
104
+ * pool was closed by calling end().
105
+ * All connection was disposed and it is not possible to acquire new one
106
+ */
107
+ private ended = false
108
+
109
+ /**
110
+ * current count of connection attempts
111
+ * also includes timeout between recoverable retries
112
+ */
113
+ private connectingCount = 0
114
+
115
+ /**
116
+ * available idle connections
117
+ */
118
+ private idle: PoolConnection[] = []
119
+
120
+ /**
121
+ * currently acquired connections
122
+ */
123
+ private active = new Set<PoolConnection>()
124
+
125
+ /**
126
+ * items waiting for released or newly established connection
127
+ */
128
+ private queue: PendingItem[] = []
129
+
130
+ private poolConfig: PoolConfigInternal
131
+
132
+ private poolStats: PoolStats = {
133
+ connection_established_count: 0,
134
+ connection_recoverable_error_count: 0,
135
+ connection_error_count: 0,
136
+ connection_disposed_idle_timeout_count: 0,
137
+ connection_disposed_idle_max_count: 0,
138
+ connection_disposed_old_count: 0,
139
+ connection_disposed_manual_count: 0,
140
+ connection_released_count: 0,
141
+ connection_reused_immediately_count: 0,
142
+ connection_reused_later_count: 0,
143
+ connection_established_idle_count: 0,
144
+ item_queued_count: 0,
145
+ item_timeout_count: 0,
146
+ item_rejected_count: 0,
147
+ item_resolved_new_ms_count: 0,
148
+ item_resolved_new_ms_sum: 0,
149
+ item_resolved_released_ms_count: 0,
150
+ item_resolved_released_ms_sum: 0,
151
+ }
152
+
153
+ private lastRecoverableError: {
154
+ error: any
155
+ time: number
156
+ } | undefined
157
+
158
+ constructor(
159
+ private clientFactory: PgClientFactory,
160
+ poolConfig: PoolConfig,
161
+ ) {
162
+ super()
163
+ this.poolConfig = {
164
+ maxConnections: 10,
165
+ maxConnecting: Math.ceil((poolConfig.maxConnections ?? 10) / 2),
166
+ maxIdle: Math.ceil((poolConfig.maxConnections ?? 10) / 2),
167
+ idleTimeoutMs: 10_000,
168
+ acquireTimeoutMs: 10_000,
169
+ reconnectIntervalMs: 100,
170
+ ...poolConfig,
171
+ }
172
+ }
173
+
174
+ public acquire(): Promise<PoolConnection> {
175
+ if (this.ended) {
176
+ throw new PoolClosedError()
177
+ }
178
+ const poolConnection = this.idle.pop()
179
+ if (poolConnection !== undefined) {
180
+ if (poolConnection.timerId) {
181
+ clearTimeout(poolConnection.timerId)
182
+ }
183
+ poolConnection.uses++
184
+ this.active.add(poolConnection)
185
+ this.poolStats.connection_reused_later_count++
186
+ this.log('Item fulfilled with an idle connection.')
187
+
188
+ return Promise.resolve(poolConnection)
189
+ }
190
+ const pendingItem = this.createPendingItem()
191
+ this.maybeCreateNew()
192
+ return pendingItem
193
+ }
194
+
195
+
196
+ public release(poolConnection: PoolConnection): void {
197
+ if (this.ended) {
198
+ return
199
+ }
200
+ this.log('Releasing a connection.')
201
+ if (!this.active.delete(poolConnection)) {
202
+ throw new ImplementationException('Connection does not belong to this pool.')
203
+ }
204
+ if (
205
+ (this.poolConfig.maxUses && poolConnection.uses >= this.poolConfig.maxUses)
206
+ || (this.poolConfig.maxAgeMs && poolConnection.createdAt + this.poolConfig.maxAgeMs < Date.now())) {
207
+ setImmediate(async () => {
208
+ await this.disposeConnection(poolConnection)
209
+ this.poolStats.connection_disposed_old_count++
210
+ this.log('Connection has reached max age or usage and was disposed.')
211
+ })
212
+ this.maybeCreateNew()
213
+ return
214
+ }
215
+ this.handleAvailableConnection(poolConnection)
216
+ }
217
+
218
+
219
+ public dispose(poolConnection: PoolConnection): void {
220
+ if (this.ended) {
221
+ return
222
+ }
223
+ this.poolStats.connection_disposed_manual_count++
224
+ this.log('Releasing and disposing a connection.')
225
+ if (!this.active.delete(poolConnection)) {
226
+ throw new ImplementationException('Connection does not belong to this pool.')
227
+ }
228
+ setImmediate(async () => {
229
+ await this.disposeConnection(poolConnection)
230
+ this.log('Connection errored and was disposed.')
231
+ })
232
+ this.maybeCreateNew()
233
+ }
234
+
235
+
236
+ public async end(): Promise<void> {
237
+ this.ended = true
238
+ this.queue.forEach(it => it.reject(new PoolClosedError()))
239
+ this.queue = []
240
+ const allConnections = [...this.idle, ...Array.from(this.active)]
241
+ await Promise.allSettled(allConnections.map(it => this.disposeConnection(it)))
242
+ this.idle = []
243
+ this.active.clear()
244
+ }
245
+
246
+
247
+ public async closeIdle(): Promise<void> {
248
+ this.log('Disposing all idle connection on request.')
249
+ const idle = this.idle
250
+ this.idle = []
251
+ await Promise.allSettled(idle.map(it => this.disposeConnection(it)))
252
+ }
253
+
254
+
255
+ public getPoolStatus(): PoolStatus {
256
+ return {
257
+ max: this.poolConfig.maxConnections,
258
+ active: this.active.size,
259
+ idle: this.idle.length,
260
+ pending: this.queue.length,
261
+ connecting: this.connectingCount,
262
+ stats: this.poolStats,
263
+ }
264
+ }
265
+
266
+
267
+ private async maybeCreateNew(attempt = 1): Promise<void> {
268
+ if (this.ended) {
269
+ return
270
+ }
271
+ if (this.queue.length === 0) {
272
+ this.log('Not connecting, queue is empty.')
273
+ return
274
+ }
275
+ const connectingCount = this.connectingCount
276
+ if (connectingCount >= this.queue.length) {
277
+ this.log('Not connecting, already establishing connection for all queued items.')
278
+ return
279
+ }
280
+ const idleCount = this.idle.length
281
+ if ((this.active.size + idleCount + connectingCount) >= this.poolConfig.maxConnections) {
282
+ this.log('Not connecting, max connections reached.')
283
+ return
284
+ }
285
+ if (connectingCount >= this.poolConfig.maxConnecting) {
286
+ this.log('Not connecting, maximum concurrent connection attempts in progress.')
287
+ return
288
+ }
289
+ this.log('Creating a new connection')
290
+ const client = this.clientFactory()
291
+ this.connectingCount++
292
+ const poolConnection = new PoolConnection(client)
293
+ client.on('error', e => {
294
+ this.log('Client error on idle connection has occurred: ' + e.message)
295
+ this.emit('error', e)
296
+ })
297
+ try {
298
+ await client.connect()
299
+ this.poolStats.connection_established_count++
300
+ this.log('Connection established')
301
+ this.connectingCount--
302
+ if (this.ended) {
303
+ await this.disposeConnection(poolConnection)
304
+ return
305
+ }
306
+ } catch (e: any) {
307
+ this.log('Connection error occurred: ' + e.message)
308
+ try {
309
+ await client.end()
310
+ } catch {
311
+ }
312
+ if (e.code === ClientErrorCodes.TOO_MANY_CONNECTIONS || e.code === ClientErrorCodes.CANNOT_CONNECT_NOW) {
313
+ this.lastRecoverableError = { error: e, time: Date.now() }
314
+ if (this.poolConfig.reconnectIntervalMs * attempt >= this.poolConfig.acquireTimeoutMs) {
315
+ this.poolStats.connection_error_count++
316
+ this.log('Recoverable error, max retries reached.')
317
+ this.emit('error', e)
318
+ this.connectingCount--
319
+ } else {
320
+ this.poolStats.connection_recoverable_error_count++
321
+ this.log('Recoverable error, retrying in a moment.')
322
+ this.emit('recoverableError', e)
323
+ setTimeout(() => {
324
+ this.connectingCount--
325
+ this.log('Retrying')
326
+ this.maybeCreateNew(attempt + 1)
327
+ }, this.poolConfig.reconnectIntervalMs)
328
+ }
329
+ } else {
330
+ this.poolStats.connection_error_count++
331
+ this.connectingCount--
332
+ if (this.active.size === 0 && this.queue.length > 0) {
333
+ const pendingItem = this.queue.shift()
334
+ if (!pendingItem) throw new Error()
335
+ this.log('Connecting failed, rejecting pending item')
336
+ pendingItem.reject(new ClientError(e))
337
+ this.poolStats.item_rejected_count++
338
+ } else {
339
+ this.log('Connecting failed, emitting error')
340
+ this.emit('error', e)
341
+ }
342
+ }
343
+ return
344
+ }
345
+ this.handleAvailableConnection(poolConnection)
346
+ this.maybeCreateNew()
347
+ }
348
+
349
+ private createPendingItem(): Promise<PoolConnection> {
350
+ return new Promise((resolve, reject) => {
351
+ const timeout = setTimeout(() => {
352
+ const acquireTimeoutError = new AcquireTimeoutError(
353
+ this.lastRecoverableError && this.lastRecoverableError.time > item.createdAt
354
+ ? this.lastRecoverableError.error
355
+ : undefined,
356
+ )
357
+ item.reject(acquireTimeoutError)
358
+ const index = this.queue.indexOf(item)
359
+ if (index > -1) {
360
+ this.queue.splice(index, 1)
361
+ }
362
+ this.poolStats.item_timeout_count++
363
+ this.log('Queued item timed out')
364
+ }, this.poolConfig.acquireTimeoutMs)
365
+
366
+ const item = new PendingItem(it => {
367
+ const duration = Date.now() - item.createdAt
368
+ const isNew = it.uses === 0
369
+ this.log(`Queued item fulfilled with ${!isNew ? 'released' : 'new'} connection.`)
370
+
371
+ if (isNew) {
372
+ this.poolStats.item_resolved_new_ms_count++
373
+ this.poolStats.item_resolved_new_ms_sum += duration
374
+ } else {
375
+ this.poolStats.item_resolved_released_ms_count++
376
+ this.poolStats.item_resolved_released_ms_sum += duration
377
+ }
378
+ clearTimeout(timeout)
379
+ resolve(it)
380
+ }, it => {
381
+ clearTimeout(timeout)
382
+ reject(it)
383
+ })
384
+
385
+ this.poolStats.item_queued_count++
386
+ this.queue.push(item)
387
+ this.log(`Item added to a queue.`)
388
+ })
389
+ }
390
+
391
+
392
+ private handleAvailableConnection(poolConnection: PoolConnection) {
393
+ const item = this.queue.shift()
394
+ const isNew = poolConnection.uses === 0
395
+ if (!isNew) {
396
+ this.poolStats.connection_released_count++
397
+ }
398
+ if (item) {
399
+ this.active.add(poolConnection)
400
+ item.resolve(poolConnection)
401
+ if (!isNew) {
402
+ this.poolStats.connection_reused_immediately_count++
403
+ }
404
+ poolConnection.uses++
405
+ return
406
+ }
407
+ if (isNew) {
408
+ this.poolStats.connection_established_idle_count++
409
+ }
410
+ if (this.idle.length >= this.poolConfig.maxIdle) {
411
+ setImmediate(async () => {
412
+ await this.disposeConnection(poolConnection)
413
+ this.poolStats.connection_disposed_idle_max_count++
414
+ this.log('Too many idle connections, connection disposed.')
415
+ })
416
+ } else {
417
+ poolConnection.timerId = setTimeout(async () => {
418
+ const index = this.idle.indexOf(poolConnection)
419
+ if (index > -1) {
420
+ this.idle.splice(index, 1)
421
+ await this.disposeConnection(poolConnection)
422
+ this.poolStats.connection_disposed_idle_timeout_count++
423
+ this.log('Idle connection disposed after timeout.')
424
+ }
425
+ }, this.poolConfig.idleTimeoutMs)
426
+ this.idle.push(poolConnection)
427
+ this.log('Connection is idle and available.')
428
+ }
429
+ }
430
+
431
+ private async disposeConnection(connection: PoolConnection) {
432
+ try {
433
+ if (connection.disposed) {
434
+ throw new PoolError('Connection is already disposed')
435
+ }
436
+ connection.disposed = true
437
+ await connection.client.end()
438
+ } catch (e: any) {
439
+ this.on('error', e)
440
+ }
441
+ }
442
+
443
+ private log(message: string) {
444
+ if (!this.poolConfig.log) return
445
+ const poolStatus = this.getPoolStatus()
446
+ this.poolConfig.log(message, poolStatus)
447
+ }
448
+ }
449
+
450
+ export { Pool }
451
+
452
+ export class PoolError extends DatabaseError {
453
+ }
454
+
455
+ export class AcquireTimeoutError extends PoolError {
456
+ constructor(previous: any) {
457
+ super('Failed to acquire a connection' + (previous && 'message' in previous ? `. Last error: ${previous.message}` : ''), previous)
458
+ }
459
+ }
460
+
461
+ export class PoolClosedError extends PoolError {
462
+ constructor() {
463
+ super('Pool is already closed')
464
+ }
465
+ }
@@ -1,118 +1,103 @@
1
1
  import { Connection } from './Connection'
2
2
  import { EventManager } from './EventManager'
3
- import { ClientBase } from 'pg'
4
3
  import { wrapIdentifier } from '../utils'
5
- import { executeQuery } from './execution'
6
4
 
7
5
  export class Transaction implements Connection.TransactionLike {
8
- private _isClosed = false
9
-
10
- private queryContext: Connection.QueryContext = {}
11
-
12
- private savepointCounter = 1
13
-
14
6
  public get isClosed(): boolean {
15
- return this._isClosed
7
+ return this.state.isClosed
16
8
  }
17
9
 
18
10
  constructor(
19
- private readonly pgClient: ClientBase,
20
- public readonly eventManager: EventManager,
21
- private readonly config: Connection.QueryConfig,
22
- ) {}
11
+ private readonly connection: Connection.ConnectionLike,
12
+ private readonly savepointManager = new SavepointState(),
13
+ private readonly state = new TransactionLikeState(),
14
+ ) {
15
+ }
16
+
17
+ get eventManager() {
18
+ return this.connection.eventManager
19
+ }
20
+
21
+ async scope<Result>(
22
+ callback: (connection: Connection.TransactionLike) => Promise<Result> | Result,
23
+ { eventManager = this.eventManager }: { eventManager?: EventManager } = {},
24
+ ): Promise<Result> {
25
+ return await this.connection.scope(async connection => {
26
+ return await callback(new Transaction(connection, this.savepointManager, this.state))
27
+ }, { eventManager })
28
+ }
23
29
 
24
30
  async transaction<Result>(
25
31
  callback: (connection: Connection.TransactionLike) => Promise<Result> | Result,
26
32
  options?: { eventManager?: EventManager },
27
33
  ): Promise<Result> {
28
- const savepointName = `savepoint_${this.savepointCounter++}`
29
- await this.query(`SAVEPOINT ${wrapIdentifier(savepointName)}`)
30
- const savepoint = new SavePoint(
31
- savepointName,
32
- this,
33
- this.pgClient,
34
- new EventManager(options?.eventManager ?? this.eventManager),
35
- )
36
- try {
37
- const result = await callback(savepoint)
38
- if (!savepoint.isClosed) {
39
- await savepoint.commit()
40
- }
41
- return result
42
- } catch (e) {
43
- if (!savepoint.isClosed) {
44
- await savepoint.rollback()
45
- }
46
- throw e
47
- }
34
+ return await this.scope(async connection => {
35
+ return await this.savepointManager.execute(connection, callback)
36
+ }, options)
48
37
  }
49
38
 
50
39
  async query<Row extends Record<string, any>>(
51
40
  sql: string,
52
41
  parameters: any[] = [],
53
42
  meta: Record<string, any> = {},
54
- config: Connection.QueryConfig = {},
55
43
  ): Promise<Connection.Result<Row>> {
56
44
  if (this.isClosed) {
57
45
  throw new Error('Transaction is already closed')
58
46
  }
59
- return await executeQuery<Row>(
60
- this.pgClient,
61
- this.eventManager,
62
- { sql, parameters, meta, ...this.config, ...config },
63
- this.queryContext,
64
- )
47
+ return await this.connection.scope(async connection => {
48
+ return connection.query(sql, parameters, meta)
49
+ }, { eventManager: this.eventManager })
65
50
  }
66
51
 
67
52
  async rollback(): Promise<void> {
68
53
  await this.close('ROLLBACK')
69
54
  }
70
55
 
71
- async rollbackUnclosed(): Promise<void> {
72
- if (this.isClosed) {
73
- return
74
- }
75
- await this.rollback()
76
- }
77
-
78
56
  async commit(): Promise<void> {
79
57
  await this.close('COMMIT')
80
58
  }
81
59
 
82
- async commitUnclosed(): Promise<void> {
83
- if (this.isClosed) {
84
- return
85
- }
86
- await this.commit()
87
- }
88
-
89
60
  private async close(command: string) {
90
61
  await this.query(command)
91
- this._isClosed = true
62
+ this.state.close()
92
63
  }
93
64
  }
94
65
 
95
66
  class SavePoint implements Connection.TransactionLike {
96
- private _isClosed = false
97
-
98
- public get isClosed(): boolean {
99
- return this._isClosed
100
- }
101
67
 
102
68
  constructor(
103
69
  public readonly savepointName: string,
104
- private readonly transactionInst: Transaction,
105
- private readonly pgClient: ClientBase,
106
- public readonly eventManager: EventManager,
107
- ) {}
70
+ public readonly savepointManager: SavepointState,
71
+ private readonly connection: Connection.ConnectionLike,
72
+ private readonly state = new TransactionLikeState(),
73
+ ) {
74
+ }
75
+
76
+ get isClosed() {
77
+ return this.state.isClosed
78
+ }
79
+
80
+ get eventManager() {
81
+ return this.connection.eventManager
82
+ }
83
+
84
+ async scope<Result>(
85
+ callback: (connection: Connection.TransactionLike) => Promise<Result> | Result,
86
+ { eventManager = this.eventManager }: { eventManager?: EventManager } = {},
87
+ ): Promise<Result> {
88
+ return this.connection.scope(async connection => {
89
+ return await callback(new SavePoint(this.savepointName, this.savepointManager, connection, this.state))
90
+ }, { eventManager })
91
+ }
92
+
108
93
 
109
94
  async transaction<Result>(
110
95
  callback: (connection: Connection.TransactionLike) => Promise<Result> | Result,
111
- options?: { eventManager?: EventManager },
96
+ options: { eventManager?: EventManager } = {},
112
97
  ): Promise<Result> {
113
- return await this.transactionInst.transaction(callback, {
114
- eventManager: options?.eventManager ?? this.eventManager,
115
- })
98
+ return await this.scope(async connection => {
99
+ return await this.savepointManager.execute(connection, callback)
100
+ }, options)
116
101
  }
117
102
 
118
103
  async query<Row extends Record<string, any>>(
@@ -123,7 +108,9 @@ class SavePoint implements Connection.TransactionLike {
123
108
  if (this.isClosed) {
124
109
  throw new Error(`Savepoint ${this.savepointName} is already closed.`)
125
110
  }
126
- return await this.transactionInst.query<Row>(sql, parameters, meta)
111
+ return await this.connection.scope(connection => {
112
+ return connection.query(sql, parameters, meta)
113
+ }, { eventManager: this.eventManager })
127
114
  }
128
115
 
129
116
  async rollback(): Promise<void> {
@@ -136,6 +123,51 @@ class SavePoint implements Connection.TransactionLike {
136
123
 
137
124
  private async close(sql: string) {
138
125
  await this.query(sql)
126
+ this.state.close()
127
+ }
128
+ }
129
+
130
+ class TransactionLikeState {
131
+ private _isClosed = false
132
+
133
+ public get isClosed(): boolean {
134
+ return this._isClosed
135
+ }
136
+
137
+ public close(): void {
139
138
  this._isClosed = true
140
139
  }
141
140
  }
141
+
142
+ class SavepointState {
143
+ public counter = 1
144
+
145
+ public async execute<Result>(
146
+ connection: Connection.ConnectionLike,
147
+ callback: (connection: Connection.TransactionLike) => Promise<Result> | Result,
148
+ ) {
149
+ const savepointName = `savepoint_${this.counter++}`
150
+
151
+ await connection.query(`SAVEPOINT ${wrapIdentifier(savepointName)}`)
152
+ const savepoint = new SavePoint(savepointName, this, connection)
153
+ return await executeTransaction(savepoint, callback)
154
+ }
155
+ }
156
+
157
+ export const executeTransaction = async <Result>(
158
+ transaction: Connection.TransactionLike,
159
+ callback: (connection: Connection.TransactionLike) => Promise<Result> | Result,
160
+ ) => {
161
+ try {
162
+ const result = await callback(transaction)
163
+ if (!transaction.isClosed) {
164
+ await transaction.commit()
165
+ }
166
+ return result
167
+ } catch (e) {
168
+ if (!transaction.isClosed) {
169
+ await transaction.rollback()
170
+ }
171
+ throw e
172
+ }
173
+ }