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