@contember/database 1.2.0-alpha.3 → 1.2.0-alpha.6
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.
- package/dist/src/client/AcquiredConnection.d.ts +17 -0
- package/dist/src/client/AcquiredConnection.d.ts.map +1 -0
- package/dist/src/client/AcquiredConnection.js +78 -0
- package/dist/src/client/AcquiredConnection.js.map +1 -0
- package/dist/src/client/Client.d.ts +3 -1
- package/dist/src/client/Client.d.ts.map +1 -1
- package/dist/src/client/Client.js +9 -5
- package/dist/src/client/Client.js.map +1 -1
- package/dist/src/client/Connection.d.ts +18 -16
- package/dist/src/client/Connection.d.ts.map +1 -1
- package/dist/src/client/Connection.js +22 -30
- package/dist/src/client/Connection.js.map +1 -1
- package/dist/src/client/PgClient.d.ts +9 -0
- package/dist/src/client/PgClient.d.ts.map +1 -0
- package/dist/src/client/PgClient.js +3 -0
- package/dist/src/client/PgClient.js.map +1 -0
- package/dist/src/client/Pool.d.ts +2 -1
- package/dist/src/client/Pool.d.ts.map +1 -1
- package/dist/src/client/Pool.js +14 -2
- package/dist/src/client/Pool.js.map +1 -1
- package/dist/src/client/Transaction.d.ts +20 -11
- package/dist/src/client/Transaction.d.ts.map +1 -1
- package/dist/src/client/Transaction.js +80 -55
- package/dist/src/client/Transaction.js.map +1 -1
- package/dist/src/client/index.d.ts +0 -1
- package/dist/src/client/index.d.ts.map +1 -1
- package/dist/src/client/index.js +0 -1
- package/dist/src/client/index.js.map +1 -1
- package/dist/src/tsconfig.tsbuildinfo +1 -1
- package/dist/src/utils/Mutex.d.ts +11 -0
- package/dist/src/utils/Mutex.d.ts.map +1 -0
- package/dist/src/utils/Mutex.js +49 -0
- package/dist/src/utils/Mutex.js.map +1 -0
- package/dist/src/utils/asyncIterableTransaction.d.ts.map +1 -1
- package/dist/src/utils/asyncIterableTransaction.js +21 -9
- package/dist/src/utils/asyncIterableTransaction.js.map +1 -1
- package/dist/src/utils/createDatabaseIfNotExists.js +2 -2
- package/dist/src/utils/createDatabaseIfNotExists.js.map +1 -1
- package/dist/src/utils/index.d.ts +1 -0
- package/dist/src/utils/index.d.ts.map +1 -1
- package/dist/src/utils/index.js +1 -0
- package/dist/src/utils/index.js.map +1 -1
- package/dist/src/utils/pgClientFactory.d.ts +3 -2
- package/dist/src/utils/pgClientFactory.d.ts.map +1 -1
- package/dist/src/utils/pgClientFactory.js.map +1 -1
- package/dist/src/utils/withDatabaseAdvisoryLock.d.ts +1 -1
- package/dist/src/utils/withDatabaseAdvisoryLock.d.ts.map +1 -1
- package/dist/src/utils/withDatabaseAdvisoryLock.js +1 -1
- package/dist/src/utils/withDatabaseAdvisoryLock.js.map +1 -1
- package/dist/tests/cases/unit/connection.test.d.ts +2 -0
- package/dist/tests/cases/unit/connection.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/connection.test.js +128 -0
- package/dist/tests/cases/unit/connection.test.js.map +1 -0
- package/dist/tests/cases/unit/createConnectionMockAlt.d.ts +6 -0
- package/dist/tests/cases/unit/createConnectionMockAlt.d.ts.map +1 -0
- package/dist/tests/cases/unit/createConnectionMockAlt.js +47 -0
- package/dist/tests/cases/unit/createConnectionMockAlt.js.map +1 -0
- package/dist/tests/cases/unit/eventManager.test.js +91 -17
- package/dist/tests/cases/unit/eventManager.test.js.map +1 -1
- package/dist/tests/cases/unit/pool.test.js +6 -10
- package/dist/tests/cases/unit/pool.test.js.map +1 -1
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/package.json +3 -3
- package/src/client/AcquiredConnection.ts +104 -0
- package/src/client/Client.ts +34 -18
- package/src/client/Connection.ts +42 -46
- package/src/client/PgClient.ts +13 -0
- package/src/client/Pool.ts +13 -3
- package/src/client/Transaction.ts +101 -69
- package/src/client/index.ts +0 -1
- package/src/utils/Mutex.ts +49 -0
- package/src/utils/asyncIterableTransaction.ts +21 -9
- package/src/utils/createDatabaseIfNotExists.ts +3 -3
- package/src/utils/index.ts +1 -0
- package/src/utils/pgClientFactory.ts +3 -2
- package/src/utils/withDatabaseAdvisoryLock.ts +4 -4
- package/tests/cases/unit/connection.test.ts +154 -0
- package/tests/cases/unit/createConnectionMockAlt.ts +44 -0
- package/tests/cases/unit/eventManager.test.ts +101 -19
- package/tests/cases/unit/pool.test.ts +6 -12
- package/dist/src/client/SingleConnection.d.ts +0 -21
- package/dist/src/client/SingleConnection.d.ts.map +0 -1
- package/dist/src/client/SingleConnection.js +0 -73
- package/dist/src/client/SingleConnection.js.map +0 -1
- package/dist/src/client/execution.d.ts +0 -7
- package/dist/src/client/execution.d.ts.map +0 -1
- package/dist/src/client/execution.js +0 -65
- package/dist/src/client/execution.js.map +0 -1
- package/src/client/SingleConnection.ts +0 -89
- package/src/client/execution.ts +0 -84
|
@@ -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
|
+
}
|
package/src/client/Pool.ts
CHANGED
|
@@ -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,
|
|
@@ -327,8 +329,16 @@ class Pool extends EventEmitter {
|
|
|
327
329
|
} else {
|
|
328
330
|
this.poolStats.connection_error_count++
|
|
329
331
|
this.connectingCount--
|
|
330
|
-
this.
|
|
331
|
-
|
|
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,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.
|
|
7
|
+
return this.state.isClosed
|
|
16
8
|
}
|
|
17
9
|
|
|
18
10
|
constructor(
|
|
19
|
-
private readonly
|
|
20
|
-
|
|
21
|
-
private readonly
|
|
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
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
|
60
|
-
|
|
61
|
-
|
|
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.
|
|
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
|
-
|
|
105
|
-
private readonly
|
|
106
|
-
|
|
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
|
|
96
|
+
options: { eventManager?: EventManager } = {},
|
|
112
97
|
): Promise<Result> {
|
|
113
|
-
return await this.
|
|
114
|
-
|
|
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.
|
|
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
|
+
}
|
package/src/client/index.ts
CHANGED
|
@@ -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
|
+
}
|
|
@@ -7,15 +7,27 @@ interface AsyncIterableX<T, TReturn = any, TNext = undefined> {
|
|
|
7
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
8
|
// eslint-disable-next-line promise/param-names
|
|
9
9
|
return yield* await new Promise(async resolveOuter => {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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
|
+
})
|
|
18
27
|
})
|
|
19
|
-
|
|
28
|
+
|
|
29
|
+
} catch (e) {
|
|
30
|
+
// suppress the error caused by rejectInner(), it was already propagated out of asyncIterableTransaction()
|
|
31
|
+
}
|
|
20
32
|
})
|
|
21
33
|
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { DatabaseConfig } from '../types'
|
|
2
|
-
import { ClientError, ClientErrorCodes,
|
|
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 =
|
|
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 =
|
|
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
|
}
|
package/src/utils/index.ts
CHANGED
|
@@ -2,6 +2,7 @@ export * from './assertNever'
|
|
|
2
2
|
export * from './asyncIterableTransaction'
|
|
3
3
|
export * from './ConstraintHelper'
|
|
4
4
|
export * from './createDatabaseIfNotExists'
|
|
5
|
+
export * from './Mutex'
|
|
5
6
|
export * from './sql'
|
|
6
7
|
export * from './retryTransaction'
|
|
7
8
|
export * from './withDatabaseAdvisoryLock'
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { Client as
|
|
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
|
|
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 <
|
|
4
|
-
connection:
|
|
3
|
+
export const withDatabaseAdvisoryLock = async <Result>(
|
|
4
|
+
connection: Connection.ConnectionLike,
|
|
5
5
|
lock: number,
|
|
6
|
-
callback: (
|
|
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(
|
|
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) {
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { expect, it } from 'vitest'
|
|
2
|
+
import { MutexDeadlockError } from '../../../src/utils'
|
|
3
|
+
import { createConnectionMockAlt } from './createConnectionMockAlt'
|
|
4
|
+
|
|
5
|
+
it('support nested scope', async () => {
|
|
6
|
+
const [connection, end] = createConnectionMockAlt(
|
|
7
|
+
[{ sql: 'SELECT 1' }],
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
await connection.scope(async c1 => await c1.scope(async c2 => {
|
|
11
|
+
await c2.query('SELECT 1')
|
|
12
|
+
return 'foo'
|
|
13
|
+
}))
|
|
14
|
+
end()
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
it('another scope acquires new connection', async () => {
|
|
18
|
+
const [connection, end] = createConnectionMockAlt(
|
|
19
|
+
[{ sql: 'SELECT 1', timeout: 5 }, { sql: 'SELECT 2', timeout: 5 }],
|
|
20
|
+
[{ sql: 'SELECT 3', timeout: 5 }],
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
await Promise.all([
|
|
24
|
+
connection.scope(async c1 => {
|
|
25
|
+
await c1.query('SELECT 1')
|
|
26
|
+
await c1.query('SELECT 2')
|
|
27
|
+
}),
|
|
28
|
+
connection.scope(async c1 => c1.query('SELECT 3')),
|
|
29
|
+
])
|
|
30
|
+
end()
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
it('another nested scope waits for connection', async () => {
|
|
35
|
+
const [connection, end] = createConnectionMockAlt(
|
|
36
|
+
[{ sql: 'SELECT 1', timeout: 5 }, { sql: 'SELECT 2', timeout: 5 }, { sql: 'SELECT 3', timeout: 5 }],
|
|
37
|
+
)
|
|
38
|
+
await connection.scope(async c1 => {
|
|
39
|
+
await Promise.all([
|
|
40
|
+
c1.scope(async c2 => {
|
|
41
|
+
await c2.query('SELECT 1')
|
|
42
|
+
await c2.query('SELECT 2')
|
|
43
|
+
}),
|
|
44
|
+
c1.scope(async c2 => c2.query('SELECT 3')),
|
|
45
|
+
])
|
|
46
|
+
})
|
|
47
|
+
end()
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
it('another nested scope waits for connection in a transaction', async () => {
|
|
52
|
+
const [connection, end] = createConnectionMockAlt(
|
|
53
|
+
[
|
|
54
|
+
{ sql: 'BEGIN', timeout: 5 },
|
|
55
|
+
{ sql: 'SELECT 1', timeout: 5 },
|
|
56
|
+
{ sql: 'SELECT 2', timeout: 5 },
|
|
57
|
+
{ sql: 'SELECT 3', timeout: 5 },
|
|
58
|
+
{ sql: 'COMMIT', timeout: 5 },
|
|
59
|
+
],
|
|
60
|
+
)
|
|
61
|
+
await connection.transaction(async c1 => {
|
|
62
|
+
await Promise.all([
|
|
63
|
+
c1.scope(async c2 => {
|
|
64
|
+
await c2.query('SELECT 1')
|
|
65
|
+
await c2.query('SELECT 2')
|
|
66
|
+
}),
|
|
67
|
+
c1.scope(async c2 => c2.query('SELECT 3')),
|
|
68
|
+
])
|
|
69
|
+
})
|
|
70
|
+
end()
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
it('unscoped queries can pe out of order', async () => {
|
|
75
|
+
const [connection, end] = createConnectionMockAlt(
|
|
76
|
+
[
|
|
77
|
+
{ sql: 'SELECT 1', timeout: 5 },
|
|
78
|
+
{ sql: 'SELECT 3' },
|
|
79
|
+
{ sql: 'SELECT 2' },
|
|
80
|
+
],
|
|
81
|
+
)
|
|
82
|
+
await connection.scope(async c1 => {
|
|
83
|
+
await Promise.all([
|
|
84
|
+
(async () => {
|
|
85
|
+
await c1.query('SELECT 1')
|
|
86
|
+
await c1.query('SELECT 2')
|
|
87
|
+
|
|
88
|
+
})(),
|
|
89
|
+
c1.query('SELECT 3'),
|
|
90
|
+
])
|
|
91
|
+
})
|
|
92
|
+
end()
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
it('support nested transaction / savepoints', async () => {
|
|
97
|
+
const [connection, end] = createConnectionMockAlt([
|
|
98
|
+
{ sql: 'BEGIN' },
|
|
99
|
+
{ sql: 'SELECT 1' },
|
|
100
|
+
{ sql: 'SAVEPOINT "savepoint_1"' },
|
|
101
|
+
{ sql: 'SELECT 2' },
|
|
102
|
+
{ sql: 'SAVEPOINT "savepoint_2"' },
|
|
103
|
+
{ sql: 'SELECT 3' },
|
|
104
|
+
{ sql: 'RELEASE SAVEPOINT "savepoint_2"' },
|
|
105
|
+
{ sql: 'RELEASE SAVEPOINT "savepoint_1"' },
|
|
106
|
+
{ sql: 'SELECT 4' },
|
|
107
|
+
{ sql: 'SAVEPOINT "savepoint_3"' },
|
|
108
|
+
{ sql: 'SELECT 5', timeout: 5 },
|
|
109
|
+
{ sql: 'SELECT 6' },
|
|
110
|
+
{ sql: 'SELECT 7' },
|
|
111
|
+
{ sql: 'SELECT 8' },
|
|
112
|
+
{ sql: 'RELEASE SAVEPOINT "savepoint_3"' },
|
|
113
|
+
{ sql: 'SELECT 9' },
|
|
114
|
+
{ sql: 'COMMIT' },
|
|
115
|
+
],
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
await connection.transaction(async trx => {
|
|
119
|
+
await Promise.all([
|
|
120
|
+
trx.query('SELECT 1'),
|
|
121
|
+
trx.transaction(async trx => {
|
|
122
|
+
await trx.query('SELECT 2')
|
|
123
|
+
await trx.transaction(async trx => {
|
|
124
|
+
await trx.query('SELECT 3')
|
|
125
|
+
})
|
|
126
|
+
}),
|
|
127
|
+
trx.query('SELECT 4'),
|
|
128
|
+
trx.transaction(async trx => {
|
|
129
|
+
await Promise.all([
|
|
130
|
+
trx.scope(async trx => {
|
|
131
|
+
return await Promise.all([
|
|
132
|
+
trx.query('SELECT 5'),
|
|
133
|
+
trx.query('SELECT 6'),
|
|
134
|
+
trx.query('SELECT 7'),
|
|
135
|
+
])
|
|
136
|
+
}),
|
|
137
|
+
trx.query('SELECT 8'),
|
|
138
|
+
])
|
|
139
|
+
}),
|
|
140
|
+
trx.scope(async trx => {
|
|
141
|
+
trx.query('SELECT 9')
|
|
142
|
+
}),
|
|
143
|
+
])
|
|
144
|
+
})
|
|
145
|
+
end()
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
it('detects deadlock', async () => {
|
|
149
|
+
const [connection, end] = createConnectionMockAlt([])
|
|
150
|
+
|
|
151
|
+
await expect(async () => await connection.scope(async c1 => c1.scope(async () => await c1.query('SELECT 1')))).rejects.toThrow(MutexDeadlockError)
|
|
152
|
+
end()
|
|
153
|
+
})
|
|
154
|
+
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { Connection, Pool } from '../../../src'
|
|
2
|
+
import { PgClient } from '../../../src/client/PgClient'
|
|
3
|
+
import EventEmitter from 'events'
|
|
4
|
+
import { expect } from 'vitest'
|
|
5
|
+
|
|
6
|
+
export const createConnectionMockAlt = (...queries: { sql: string; timeout?: number }[][]): [Connection, () => void] => {
|
|
7
|
+
const connectionMocks: (PgClient & { assertEmpty: () => void })[] = []
|
|
8
|
+
for (const queriesSet of queries) {
|
|
9
|
+
connectionMocks.push(new class extends EventEmitter {
|
|
10
|
+
connect() {
|
|
11
|
+
return Promise.resolve()
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
end() {
|
|
15
|
+
return Promise.resolve()
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async query(sql: string) {
|
|
19
|
+
const query = queriesSet.shift()
|
|
20
|
+
expect(query).toBeDefined()
|
|
21
|
+
expect(sql).toEqual(query?.sql)
|
|
22
|
+
await new Promise<void>(resolve => setTimeout(resolve, query?.timeout ?? 1))
|
|
23
|
+
|
|
24
|
+
return sql as any
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
assertEmpty() {
|
|
28
|
+
expect(queriesSet).deep.eq([])
|
|
29
|
+
}
|
|
30
|
+
})
|
|
31
|
+
}
|
|
32
|
+
const allMocks = [...connectionMocks]
|
|
33
|
+
const pool = new Pool(() => {
|
|
34
|
+
return connectionMocks.shift() ?? (() => {
|
|
35
|
+
throw new Error('No connection')
|
|
36
|
+
})()
|
|
37
|
+
}, {})
|
|
38
|
+
return [
|
|
39
|
+
new Connection(pool),
|
|
40
|
+
() => {
|
|
41
|
+
allMocks.forEach(it => it.assertEmpty())
|
|
42
|
+
},
|
|
43
|
+
]
|
|
44
|
+
}
|