@contember/database 1.2.0-alpha.1 → 1.2.0-alpha.4

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 (98) hide show
  1. package/dist/src/client/AcquiredConnection.d.ts +18 -0
  2. package/dist/src/client/AcquiredConnection.d.ts.map +1 -0
  3. package/dist/src/client/AcquiredConnection.js +85 -0
  4. package/dist/src/client/AcquiredConnection.js.map +1 -0
  5. package/dist/src/client/Client.d.ts +2 -0
  6. package/dist/src/client/Client.d.ts.map +1 -1
  7. package/dist/src/client/Client.js +7 -0
  8. package/dist/src/client/Client.js.map +1 -1
  9. package/dist/src/client/Connection.d.ts +15 -8
  10. package/dist/src/client/Connection.d.ts.map +1 -1
  11. package/dist/src/client/Connection.js +19 -26
  12. package/dist/src/client/Connection.js.map +1 -1
  13. package/dist/src/client/PgClient.d.ts +9 -0
  14. package/dist/src/client/PgClient.d.ts.map +1 -0
  15. package/dist/src/client/PgClient.js +3 -0
  16. package/dist/src/client/PgClient.js.map +1 -0
  17. package/dist/src/client/Pool.d.ts +3 -1
  18. package/dist/src/client/Pool.d.ts.map +1 -1
  19. package/dist/src/client/Pool.js +15 -3
  20. package/dist/src/client/Pool.js.map +1 -1
  21. package/dist/src/client/Transaction.d.ts +20 -11
  22. package/dist/src/client/Transaction.d.ts.map +1 -1
  23. package/dist/src/client/Transaction.js +81 -56
  24. package/dist/src/client/Transaction.js.map +1 -1
  25. package/dist/src/client/index.d.ts +0 -1
  26. package/dist/src/client/index.d.ts.map +1 -1
  27. package/dist/src/client/index.js +0 -1
  28. package/dist/src/client/index.js.map +1 -1
  29. package/dist/src/index.d.ts +1 -1
  30. package/dist/src/index.d.ts.map +1 -1
  31. package/dist/src/index.js +2 -1
  32. package/dist/src/index.js.map +1 -1
  33. package/dist/src/tsconfig.tsbuildinfo +1 -1
  34. package/dist/src/utils/Mutex.d.ts +11 -0
  35. package/dist/src/utils/Mutex.d.ts.map +1 -0
  36. package/dist/src/utils/Mutex.js +49 -0
  37. package/dist/src/utils/Mutex.js.map +1 -0
  38. package/dist/src/utils/asyncIterableTransaction.d.ts +7 -0
  39. package/dist/src/utils/asyncIterableTransaction.d.ts.map +1 -0
  40. package/dist/src/utils/asyncIterableTransaction.js +32 -0
  41. package/dist/src/utils/asyncIterableTransaction.js.map +1 -0
  42. package/dist/src/utils/createDatabaseIfNotExists.js +2 -2
  43. package/dist/src/utils/createDatabaseIfNotExists.js.map +1 -1
  44. package/dist/src/utils/index.d.ts +2 -0
  45. package/dist/src/utils/index.d.ts.map +1 -1
  46. package/dist/src/utils/index.js +2 -0
  47. package/dist/src/utils/index.js.map +1 -1
  48. package/dist/src/utils/pgClientFactory.d.ts +3 -2
  49. package/dist/src/utils/pgClientFactory.d.ts.map +1 -1
  50. package/dist/src/utils/pgClientFactory.js.map +1 -1
  51. package/dist/src/utils/sql.d.ts +1 -1
  52. package/dist/src/utils/sql.d.ts.map +1 -1
  53. package/dist/src/utils/withDatabaseAdvisoryLock.d.ts +1 -1
  54. package/dist/src/utils/withDatabaseAdvisoryLock.d.ts.map +1 -1
  55. package/dist/src/utils/withDatabaseAdvisoryLock.js +1 -1
  56. package/dist/src/utils/withDatabaseAdvisoryLock.js.map +1 -1
  57. package/dist/tests/cases/unit/connection.test.d.ts +2 -0
  58. package/dist/tests/cases/unit/connection.test.d.ts.map +1 -0
  59. package/dist/tests/cases/unit/connection.test.js +128 -0
  60. package/dist/tests/cases/unit/connection.test.js.map +1 -0
  61. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts +6 -0
  62. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts.map +1 -0
  63. package/dist/tests/cases/unit/createConnectionMockAlt.js +47 -0
  64. package/dist/tests/cases/unit/createConnectionMockAlt.js.map +1 -0
  65. package/dist/tests/cases/unit/eventManager.test.js +91 -17
  66. package/dist/tests/cases/unit/eventManager.test.js.map +1 -1
  67. package/dist/tests/cases/unit/pool.test.js +9 -9
  68. package/dist/tests/cases/unit/pool.test.js.map +1 -1
  69. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  70. package/package.json +4 -4
  71. package/src/client/AcquiredConnection.ts +112 -0
  72. package/src/client/Client.ts +31 -9
  73. package/src/client/Connection.ts +42 -36
  74. package/src/client/PgClient.ts +13 -0
  75. package/src/client/Pool.ts +14 -4
  76. package/src/client/Transaction.ts +103 -69
  77. package/src/client/index.ts +0 -1
  78. package/src/index.ts +1 -0
  79. package/src/utils/Mutex.ts +49 -0
  80. package/src/utils/asyncIterableTransaction.ts +33 -0
  81. package/src/utils/createDatabaseIfNotExists.ts +3 -3
  82. package/src/utils/index.ts +2 -0
  83. package/src/utils/pgClientFactory.ts +3 -2
  84. package/src/utils/withDatabaseAdvisoryLock.ts +4 -4
  85. package/tests/cases/unit/connection.test.ts +154 -0
  86. package/tests/cases/unit/createConnectionMockAlt.ts +44 -0
  87. package/tests/cases/unit/eventManager.test.ts +101 -19
  88. package/tests/cases/unit/pool.test.ts +10 -11
  89. package/dist/src/client/SingleConnection.d.ts +0 -21
  90. package/dist/src/client/SingleConnection.d.ts.map +0 -1
  91. package/dist/src/client/SingleConnection.js +0 -73
  92. package/dist/src/client/SingleConnection.js.map +0 -1
  93. package/dist/src/client/execution.d.ts +0 -7
  94. package/dist/src/client/execution.d.ts.map +0 -1
  95. package/dist/src/client/execution.js +0 -65
  96. package/dist/src/client/execution.js.map +0 -1
  97. package/src/client/SingleConnection.ts +0 -89
  98. package/src/client/execution.ts +0 -84
@@ -1,10 +1,9 @@
1
1
  import { EventManager } from './EventManager'
2
2
  import { Client } from './Client'
3
- import { Transaction } from './Transaction'
4
- import { executeQuery } from './execution'
5
3
  import { Pool, PoolConfig, PoolStatus } from './Pool'
6
4
  import { createPgClientFactory } from '../utils'
7
5
  import { DatabaseConfig } from '../types'
6
+ import { AcquiredConnection } from './AcquiredConnection'
8
7
 
9
8
  class Connection implements Connection.ConnectionLike, Connection.ClientFactory, Connection.PoolStatusProvider {
10
9
  constructor(
@@ -26,41 +25,42 @@ class Connection implements Connection.ConnectionLike, Connection.ClientFactory,
26
25
  return new Connection(new Pool(createPgClientFactory(config), pool), queryConfig)
27
26
  }
28
27
 
29
- public createClient(schema: string, queryMeta: Record<string, any>): Client {
30
- return new Client(this, schema, queryMeta, new EventManager(this.eventManager))
28
+ public static createSingle(
29
+ config: DatabaseConfig,
30
+ queryConfig: Connection.QueryConfig = {},
31
+ ): Connection {
32
+ return new Connection(new Pool(createPgClientFactory(config), { maxConnections: 1, maxIdle: 0 }), queryConfig)
31
33
  }
32
34
 
33
- public async clearPool(): Promise<void> {
34
- await this.pool.closeIdle()
35
+ public createClient(schema: string, queryMeta: Record<string, any>): Client {
36
+ return new Client(this, schema, queryMeta, new EventManager(this.eventManager))
35
37
  }
36
38
 
37
- async transaction<Result>(
38
- callback: (connection: Connection.TransactionLike) => Promise<Result> | Result,
39
+ async scope<Result>(
40
+ callback: (connection: Connection.ConnectionLike) => Promise<Result> | Result,
39
41
  options: { eventManager?: EventManager } = {},
40
42
  ): Promise<Result> {
41
43
  const acquired = await this.pool.acquire()
42
44
  const eventManager = new EventManager(options.eventManager ?? this.eventManager)
43
- await executeQuery(acquired.client, eventManager, {
44
- sql: 'BEGIN',
45
- ...this.queryConfig,
46
- })
47
- const transaction = new Transaction(acquired.client, eventManager, this.queryConfig)
48
45
  try {
49
- const result = await callback(transaction)
50
-
51
- await transaction.commitUnclosed()
46
+ const connection = new AcquiredConnection(acquired.client, eventManager, this.queryConfig)
47
+ const result = await callback(connection)
52
48
  this.pool.release(acquired)
53
49
 
54
50
  return result
55
51
  } catch (e) {
56
- await transaction.rollbackUnclosed()
57
52
  this.pool.dispose(acquired)
58
53
  throw e
59
54
  }
60
55
  }
61
56
 
62
- async end(): Promise<void> {
63
- await this.pool.end()
57
+ async transaction<Result>(
58
+ callback: (connection: Connection.TransactionLike) => Promise<Result> | Result,
59
+ options: { eventManager?: EventManager } = {},
60
+ ): Promise<Result> {
61
+ return await this.scope(async connection => {
62
+ return await connection.transaction(callback)
63
+ }, options)
64
64
  }
65
65
 
66
66
  async query<Row extends Record<string, any>>(
@@ -69,16 +69,17 @@ class Connection implements Connection.ConnectionLike, Connection.ClientFactory,
69
69
  meta: Record<string, any> = {},
70
70
  { eventManager, ...config }: Connection.QueryConfig = {},
71
71
  ): Promise<Connection.Result<Row>> {
72
- const client = await this.pool.acquire()
73
- const query: Connection.Query = { sql, parameters, meta, ...this.queryConfig, ...config }
74
- try {
75
- const result = await executeQuery<Row>(client.client, eventManager ?? this.eventManager, query, {})
76
- this.pool.release(client)
77
- return result
78
- } catch (e) {
79
- this.pool.dispose(client)
80
- throw e
81
- }
72
+ return await this.scope(async connection => {
73
+ return await connection.query(sql, parameters, meta, config)
74
+ }, { eventManager })
75
+ }
76
+
77
+ async end(): Promise<void> {
78
+ await this.pool.end()
79
+ }
80
+
81
+ public async clearPool(): Promise<void> {
82
+ await this.pool.closeIdle()
82
83
  }
83
84
 
84
85
  getPoolStatus(): PoolStatus {
@@ -115,7 +116,15 @@ namespace Connection {
115
116
  & Connection.ClientFactory
116
117
  & Connection.PoolStatusProvider
117
118
 
118
- export interface ConnectionLike extends Transactional, Queryable {}
119
+ export interface Scopable<Sub> {
120
+ scope<Result>(
121
+ callback: (connection: Sub) => Promise<Result> | Result,
122
+ options?: { eventManager?: EventManager },
123
+ ): Promise<Result>
124
+ }
125
+
126
+ export interface ConnectionLike extends Transactional, Queryable, Scopable<ConnectionLike> {
127
+ }
119
128
 
120
129
  export interface ClientFactory {
121
130
  createClient(schema: string, queryMeta: Record<string, any>): Client
@@ -125,7 +134,7 @@ namespace Connection {
125
134
  getPoolStatus(): PoolStatus | undefined
126
135
  }
127
136
 
128
- export interface TransactionLike extends ConnectionLike {
137
+ export interface TransactionLike extends Transactional, Queryable, Scopable<TransactionLike> {
129
138
  readonly isClosed: boolean
130
139
 
131
140
  rollback(): Promise<void>
@@ -133,10 +142,6 @@ namespace Connection {
133
142
  commit(): Promise<void>
134
143
  }
135
144
 
136
- export interface QueryContext {
137
- previousQueryEnd?: number
138
- }
139
-
140
145
  export interface Query {
141
146
  readonly sql: string
142
147
  readonly parameters: any[]
@@ -147,8 +152,9 @@ namespace Connection {
147
152
  readonly rowCount: number
148
153
  readonly rows: Row[]
149
154
  readonly timing?: {
150
- totalDuration: number
151
155
  selfDuration: number
156
+ /** @deprecated both selfDuration and totalDuration now contains same number */
157
+ totalDuration: number
152
158
  }
153
159
  }
154
160
 
@@ -0,0 +1,13 @@
1
+ import { QueryConfig, QueryResult, QueryResultRow } from 'pg'
2
+ import EventEmitter from 'events'
3
+
4
+ export interface PgClient extends EventEmitter {
5
+ connect(): Promise<void>
6
+
7
+ query<R extends QueryResultRow = any, I extends any[] = any[]>(
8
+ queryTextOrConfig: string | QueryConfig<I>,
9
+ values?: I,
10
+ ): Promise<QueryResult<R>>
11
+
12
+ end(): Promise<void>
13
+ }
@@ -1,9 +1,9 @@
1
1
  import { ImplementationException } from '../exceptions'
2
- import { Client as PgClient } from 'pg'
3
2
  import { ClientErrorCodes } from './errorCodes'
4
3
  import EventEmitter from 'events'
5
4
  import { ClientError, DatabaseError } from './errors'
6
5
  import { PgClientFactory } from '../utils'
6
+ import { PgClient } from './PgClient'
7
7
 
8
8
  export type PoolLogger = (message: string, status: PoolStatus) => void
9
9
 
@@ -62,6 +62,7 @@ export const poolStatsDescription = {
62
62
 
63
63
  item_queued_count: 'Number of queued items requesting a connection.',
64
64
  item_timeout_count: 'Number of items waiting for connection, which timed out.',
65
+ item_rejected_count: 'Number of items rejected with an error.',
65
66
 
66
67
  item_resolved_new_ms_count: 'Number of queued items resolved with newly established connection.',
67
68
  item_resolved_new_ms_sum: 'Waiting time of queued items, which was resolved with a new connection.',
@@ -142,6 +143,7 @@ class Pool extends EventEmitter {
142
143
  connection_established_idle_count: 0,
143
144
  item_queued_count: 0,
144
145
  item_timeout_count: 0,
146
+ item_rejected_count: 0,
145
147
  item_resolved_new_ms_count: 0,
146
148
  item_resolved_new_ms_sum: 0,
147
149
  item_resolved_released_ms_count: 0,
@@ -312,7 +314,7 @@ class Pool extends EventEmitter {
312
314
  if (this.poolConfig.reconnectIntervalMs * attempt >= this.poolConfig.acquireTimeoutMs) {
313
315
  this.poolStats.connection_error_count++
314
316
  this.log('Recoverable error, max retries reached.')
315
- this.emit('e', e)
317
+ this.emit('error', e)
316
318
  this.connectingCount--
317
319
  } else {
318
320
  this.poolStats.connection_recoverable_error_count++
@@ -327,8 +329,16 @@ class Pool extends EventEmitter {
327
329
  } else {
328
330
  this.poolStats.connection_error_count++
329
331
  this.connectingCount--
330
- this.log('Connecting failed, emitting error')
331
- this.emit('error', e)
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
+ }
332
342
  }
333
343
  return
334
344
  }
@@ -1,129 +1,118 @@
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 = {},
43
+ { eventManager = this.eventManager, ...config }: Connection.QueryConfig = {},
55
44
  ): Promise<Connection.Result<Row>> {
56
45
  if (this.isClosed) {
57
46
  throw new Error('Transaction is already closed')
58
47
  }
59
- return await executeQuery<Row>(
60
- this.pgClient,
61
- this.eventManager,
62
- { sql, parameters, meta, ...this.config, ...config },
63
- this.queryContext,
64
- )
48
+ return await this.connection.scope(async connection => {
49
+ return connection.query(sql, parameters, meta, config)
50
+ }, { eventManager })
65
51
  }
66
52
 
67
53
  async rollback(): Promise<void> {
68
54
  await this.close('ROLLBACK')
69
55
  }
70
56
 
71
- async rollbackUnclosed(): Promise<void> {
72
- if (this.isClosed) {
73
- return
74
- }
75
- await this.rollback()
76
- }
77
-
78
57
  async commit(): Promise<void> {
79
58
  await this.close('COMMIT')
80
59
  }
81
60
 
82
- async commitUnclosed(): Promise<void> {
83
- if (this.isClosed) {
84
- return
85
- }
86
- await this.commit()
87
- }
88
-
89
61
  private async close(command: string) {
90
62
  await this.query(command)
91
- this._isClosed = true
63
+ this.state.close()
92
64
  }
93
65
  }
94
66
 
95
67
  class SavePoint implements Connection.TransactionLike {
96
- private _isClosed = false
97
-
98
- public get isClosed(): boolean {
99
- return this._isClosed
100
- }
101
68
 
102
69
  constructor(
103
70
  public readonly savepointName: string,
104
- private readonly transactionInst: Transaction,
105
- private readonly pgClient: ClientBase,
106
- public readonly eventManager: EventManager,
107
- ) {}
71
+ public readonly savepointManager: SavepointState,
72
+ private readonly connection: Connection.ConnectionLike,
73
+ private readonly state = new TransactionLikeState(),
74
+ ) {
75
+ }
76
+
77
+ get isClosed() {
78
+ return this.state.isClosed
79
+ }
80
+
81
+ get eventManager() {
82
+ return this.connection.eventManager
83
+ }
84
+
85
+ async scope<Result>(
86
+ callback: (connection: Connection.TransactionLike) => Promise<Result> | Result,
87
+ { eventManager = this.eventManager }: { eventManager?: EventManager } = {},
88
+ ): Promise<Result> {
89
+ return this.connection.scope(async connection => {
90
+ return await callback(new SavePoint(this.savepointName, this.savepointManager, connection, this.state))
91
+ }, { eventManager })
92
+ }
93
+
108
94
 
109
95
  async transaction<Result>(
110
96
  callback: (connection: Connection.TransactionLike) => Promise<Result> | Result,
111
- options?: { eventManager?: EventManager },
97
+ options: { eventManager?: EventManager } = {},
112
98
  ): Promise<Result> {
113
- return await this.transactionInst.transaction(callback, {
114
- eventManager: options?.eventManager ?? this.eventManager,
115
- })
99
+ return await this.scope(async connection => {
100
+ return await this.savepointManager.execute(connection, callback)
101
+ }, options)
116
102
  }
117
103
 
118
104
  async query<Row extends Record<string, any>>(
119
105
  sql: string,
120
106
  parameters: any[] = [],
121
107
  meta: Record<string, any> = {},
108
+ { eventManager = this.eventManager, ...config }: Connection.QueryConfig = {},
122
109
  ): Promise<Connection.Result<Row>> {
123
110
  if (this.isClosed) {
124
111
  throw new Error(`Savepoint ${this.savepointName} is already closed.`)
125
112
  }
126
- return await this.transactionInst.query<Row>(sql, parameters, meta)
113
+ return await this.connection.scope(connection => {
114
+ return connection.query(sql, parameters, meta, config)
115
+ }, { eventManager })
127
116
  }
128
117
 
129
118
  async rollback(): Promise<void> {
@@ -136,6 +125,51 @@ class SavePoint implements Connection.TransactionLike {
136
125
 
137
126
  private async close(sql: string) {
138
127
  await this.query(sql)
128
+ this.state.close()
129
+ }
130
+ }
131
+
132
+ class TransactionLikeState {
133
+ private _isClosed = false
134
+
135
+ public get isClosed(): boolean {
136
+ return this._isClosed
137
+ }
138
+
139
+ public close(): void {
139
140
  this._isClosed = true
140
141
  }
141
142
  }
143
+
144
+ class SavepointState {
145
+ public counter = 1
146
+
147
+ public async execute<Result>(
148
+ connection: Connection.ConnectionLike,
149
+ callback: (connection: Connection.TransactionLike) => Promise<Result> | Result,
150
+ ) {
151
+ const savepointName = `savepoint_${this.counter++}`
152
+
153
+ await connection.query(`SAVEPOINT ${wrapIdentifier(savepointName)}`)
154
+ const savepoint = new SavePoint(savepointName, this, connection)
155
+ return await executeTransaction(savepoint, callback)
156
+ }
157
+ }
158
+
159
+ export const executeTransaction = async <Result>(
160
+ transaction: Connection.TransactionLike,
161
+ callback: (connection: Connection.TransactionLike) => Promise<Result> | Result,
162
+ ) => {
163
+ try {
164
+ const result = await callback(transaction)
165
+ if (!transaction.isClosed) {
166
+ await transaction.commit()
167
+ }
168
+ return result
169
+ } catch (e) {
170
+ if (!transaction.isClosed) {
171
+ await transaction.rollback()
172
+ }
173
+ throw e
174
+ }
175
+ }
@@ -5,4 +5,3 @@ export * from './Connection'
5
5
  export * from './EventManager'
6
6
  export * from './Pool'
7
7
  export * from './Transaction'
8
- export * from './SingleConnection'
package/src/index.ts CHANGED
@@ -12,6 +12,7 @@ export * from './queryable'
12
12
  export * from './Literal'
13
13
  export * from './types'
14
14
  export {
15
+ asyncIterableTransaction,
15
16
  wrapIdentifier,
16
17
  retryTransaction,
17
18
  ConstraintHelper,
@@ -0,0 +1,49 @@
1
+ import { AsyncLocalStorage } from 'async_hooks'
2
+
3
+ const mutexDeadlockTracker = new AsyncLocalStorage<Set<number>>()
4
+
5
+ let mutexIdCounter = 1
6
+
7
+ export class Mutex {
8
+ private mutexId = mutexIdCounter++
9
+
10
+ private resolvers: (() => void)[] = []
11
+
12
+ private locked = false
13
+
14
+ public async execute<T>(cb: () => T): Promise<T> {
15
+ const current = mutexDeadlockTracker.getStore()
16
+ await this.lock(current)
17
+ try {
18
+ const newState = new Set<number>(current)
19
+ newState.add(this.mutexId)
20
+ return await mutexDeadlockTracker.run(newState, async () => cb())
21
+ } finally {
22
+ this.release()
23
+ }
24
+ }
25
+
26
+ private lock(currentState?: Set<number>): Promise<void> {
27
+ if (!this.locked) {
28
+ this.locked = true
29
+ return Promise.resolve()
30
+ }
31
+ if (currentState?.has(this.mutexId)) {
32
+ throw new MutexDeadlockError()
33
+ }
34
+ return new Promise(resolve => this.resolvers.push(resolve))
35
+ }
36
+
37
+ private release(): void {
38
+ const nextResolver = this.resolvers.shift()
39
+ if (nextResolver) {
40
+ nextResolver()
41
+ } else {
42
+ this.locked = false
43
+ }
44
+ }
45
+ }
46
+
47
+ export class MutexDeadlockError extends Error {
48
+
49
+ }
@@ -0,0 +1,33 @@
1
+ import { Client, Connection } from '../client/index.js'
2
+
3
+ interface AsyncIterableX<T, TReturn = any, TNext = undefined> {
4
+ [Symbol.asyncIterator](): AsyncIterator<T, TReturn, TNext>
5
+ }
6
+
7
+ export async function* asyncIterableTransaction<T, TReturn = any, TNext = undefined>(db: Client, cb: (db2: Client<Connection.TransactionLike>) => AsyncIterableX<T, TReturn, TNext>): AsyncIterableX<T, TReturn, TNext> {
8
+ // eslint-disable-next-line promise/param-names
9
+ return yield* await new Promise(async resolveOuter => {
10
+ try {
11
+ await db.transaction((db2: Client<Connection.TransactionLike>) => {
12
+ // eslint-disable-next-line promise/param-names
13
+ return new Promise<void>((resolveInner, rejectInner) => {
14
+ resolveOuter((async function* () {
15
+ try {
16
+ const result = yield* cb(db2)
17
+ resolveInner()
18
+ return result
19
+
20
+ } finally { // required to close the transaction when the generator is externally closed, or exceptions are thrown
21
+ if (!db2.connection.isClosed) {
22
+ rejectInner()
23
+ }
24
+ }
25
+ })())
26
+ })
27
+ })
28
+
29
+ } catch (e) {
30
+ // suppress the error caused by rejectInner(), it was already propagated out of asyncIterableTransaction()
31
+ }
32
+ })
33
+ }
@@ -1,10 +1,10 @@
1
1
  import { DatabaseConfig } from '../types'
2
- import { ClientError, ClientErrorCodes, SingleConnection } from '../client'
2
+ import { ClientError, ClientErrorCodes, Connection } from '../client'
3
3
  import { wrapIdentifier } from './sql'
4
4
 
5
5
  export const createDatabaseIfNotExists = async (db: DatabaseConfig, log: (message: string) => void) => {
6
6
  try {
7
- const connection = new SingleConnection(db, {})
7
+ const connection = Connection.createSingle(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: DatabaseConfig, log: (messag
15
15
  }
16
16
 
17
17
  log(`Database ${db.database} does not exist, attempting to create it...`)
18
- const connection = new SingleConnection({ ...db, database: 'postgres' }, {})
18
+ const connection = Connection.createSingle({ ...db, database: 'postgres' }, {})
19
19
  await connection.query(`CREATE DATABASE ${wrapIdentifier(db.database)}`)
20
20
  await connection.end()
21
21
  }
@@ -1,6 +1,8 @@
1
1
  export * from './assertNever'
2
+ export * from './asyncIterableTransaction'
2
3
  export * from './ConstraintHelper'
3
4
  export * from './createDatabaseIfNotExists'
5
+ export * from './Mutex'
4
6
  export * from './sql'
5
7
  export * from './retryTransaction'
6
8
  export * from './withDatabaseAdvisoryLock'
@@ -1,8 +1,9 @@
1
- import { Client as PgClient } from 'pg'
1
+ import { Client as PgClientImpl } from 'pg'
2
2
  import { DatabaseConfig } from '../types'
3
+ import { PgClient } from '../client/PgClient'
3
4
 
4
5
  export type PgClientFactory = () => PgClient
5
- export const createPgClientFactory = ({ queryTimeoutMs, statementTimeoutMs, connectionTimeoutMs, ...config }: DatabaseConfig) => () => new PgClient({
6
+ export const createPgClientFactory = ({ queryTimeoutMs, statementTimeoutMs, connectionTimeoutMs, ...config }: DatabaseConfig) => () => new PgClientImpl({
6
7
  query_timeout: queryTimeoutMs,
7
8
  statement_timeout: statementTimeoutMs,
8
9
  connectionTimeoutMillis: connectionTimeoutMs,
@@ -1,13 +1,13 @@
1
1
  import { Connection } from '../client'
2
2
 
3
- export const withDatabaseAdvisoryLock = async <Cn extends Connection.Queryable, Result>(
4
- connection: Cn,
3
+ export const withDatabaseAdvisoryLock = async <Result>(
4
+ connection: Connection.ConnectionLike,
5
5
  lock: number,
6
- callback: (connection: Cn) => Result | Promise<Result>,
6
+ callback: () => Result | Promise<Result>,
7
7
  ): Promise<Result> => {
8
8
  await connection.query(`select pg_advisory_lock(?)`, [lock])
9
9
  try {
10
- return await callback(connection)
10
+ return await callback()
11
11
  } finally {
12
12
  const result = await connection.query<{lockReleased: boolean}>('select pg_advisory_unlock(?) as "lockReleased"', [lock])
13
13
  if (!result.rows[0].lockReleased) {