@contember/database 1.2.0-alpha.1 → 1.2.0-alpha.12
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/builders/DeleteBuilder.d.ts +1 -1
- package/dist/src/builders/DeleteBuilder.d.ts.map +1 -1
- package/dist/src/builders/DeleteBuilder.js.map +1 -1
- package/dist/src/builders/InsertBuilder.d.ts +1 -1
- package/dist/src/builders/InsertBuilder.d.ts.map +1 -1
- package/dist/src/builders/InsertBuilder.js.map +1 -1
- package/dist/src/builders/UpdateBuilder.d.ts +1 -1
- package/dist/src/builders/UpdateBuilder.d.ts.map +1 -1
- package/dist/src/builders/UpdateBuilder.js.map +1 -1
- 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 +3 -1
- package/dist/src/client/Pool.d.ts.map +1 -1
- package/dist/src/client/Pool.js +15 -3
- 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/index.d.ts +1 -1
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +2 -1
- package/dist/src/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 +7 -0
- package/dist/src/utils/asyncIterableTransaction.d.ts.map +1 -0
- package/dist/src/utils/asyncIterableTransaction.js +32 -0
- package/dist/src/utils/asyncIterableTransaction.js.map +1 -0
- package/dist/src/utils/createDatabaseIfNotExists.js +2 -2
- package/dist/src/utils/createDatabaseIfNotExists.js.map +1 -1
- package/dist/src/utils/index.d.ts +2 -0
- package/dist/src/utils/index.d.ts.map +1 -1
- package/dist/src/utils/index.js +2 -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/sql.d.ts +1 -1
- package/dist/src/utils/sql.d.ts.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 +9 -9
- package/dist/tests/cases/unit/pool.test.js.map +1 -1
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/package.json +4 -4
- package/src/builders/DeleteBuilder.ts +1 -1
- package/src/builders/InsertBuilder.ts +1 -1
- package/src/builders/UpdateBuilder.ts +1 -1
- 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 +14 -4
- package/src/client/Transaction.ts +101 -69
- package/src/client/index.ts +0 -1
- package/src/index.ts +1 -0
- package/src/utils/Mutex.ts +49 -0
- package/src/utils/asyncIterableTransaction.ts +33 -0
- package/src/utils/createDatabaseIfNotExists.ts +3 -3
- package/src/utils/index.ts +2 -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 +10 -11
- 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
package/src/client/Connection.ts
CHANGED
|
@@ -1,15 +1,13 @@
|
|
|
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(
|
|
11
10
|
private readonly pool: Pool,
|
|
12
|
-
private readonly queryConfig: Connection.QueryConfig,
|
|
13
11
|
public readonly eventManager: EventManager = new EventManager(null),
|
|
14
12
|
) {
|
|
15
13
|
this.pool.on('error', err => {
|
|
@@ -21,64 +19,63 @@ class Connection implements Connection.ConnectionLike, Connection.ClientFactory,
|
|
|
21
19
|
|
|
22
20
|
public static create(
|
|
23
21
|
{ pool = {}, ...config }: DatabaseConfig & { pool?: PoolConfig },
|
|
24
|
-
queryConfig: Connection.QueryConfig = {},
|
|
25
22
|
): Connection {
|
|
26
|
-
return new Connection(new Pool(createPgClientFactory(config), pool)
|
|
23
|
+
return new Connection(new Pool(createPgClientFactory(config), pool))
|
|
27
24
|
}
|
|
28
25
|
|
|
29
|
-
public
|
|
30
|
-
|
|
26
|
+
public static createSingle(
|
|
27
|
+
config: DatabaseConfig,
|
|
28
|
+
): Connection {
|
|
29
|
+
return new Connection(new Pool(createPgClientFactory(config), { maxConnections: 1, maxIdle: 0 }))
|
|
31
30
|
}
|
|
32
31
|
|
|
33
|
-
public
|
|
34
|
-
|
|
32
|
+
public createClient(schema: string, queryMeta: Record<string, any>): Client {
|
|
33
|
+
return new Client(this, schema, queryMeta, new EventManager(this.eventManager))
|
|
35
34
|
}
|
|
36
35
|
|
|
37
|
-
async
|
|
38
|
-
callback: (connection: Connection.
|
|
36
|
+
async scope<Result>(
|
|
37
|
+
callback: (connection: Connection.ConnectionLike) => Promise<Result> | Result,
|
|
39
38
|
options: { eventManager?: EventManager } = {},
|
|
40
39
|
): Promise<Result> {
|
|
41
40
|
const acquired = await this.pool.acquire()
|
|
42
41
|
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
42
|
try {
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
await transaction.commitUnclosed()
|
|
43
|
+
const connection = new AcquiredConnection(acquired.client, eventManager)
|
|
44
|
+
const result = await callback(connection)
|
|
52
45
|
this.pool.release(acquired)
|
|
53
46
|
|
|
54
47
|
return result
|
|
55
48
|
} catch (e) {
|
|
56
|
-
await transaction.rollbackUnclosed()
|
|
57
49
|
this.pool.dispose(acquired)
|
|
58
50
|
throw e
|
|
59
51
|
}
|
|
60
52
|
}
|
|
61
53
|
|
|
62
|
-
async
|
|
63
|
-
|
|
54
|
+
async transaction<Result>(
|
|
55
|
+
callback: (connection: Connection.TransactionLike) => Promise<Result> | Result,
|
|
56
|
+
options: { eventManager?: EventManager } = {},
|
|
57
|
+
): Promise<Result> {
|
|
58
|
+
return await this.scope(async connection => {
|
|
59
|
+
return await connection.transaction(callback)
|
|
60
|
+
}, options)
|
|
64
61
|
}
|
|
65
62
|
|
|
66
63
|
async query<Row extends Record<string, any>>(
|
|
67
64
|
sql: string,
|
|
68
65
|
parameters: any[] = [],
|
|
69
66
|
meta: Record<string, any> = {},
|
|
70
|
-
{ eventManager, ...config }: Connection.QueryConfig = {},
|
|
71
67
|
): Promise<Connection.Result<Row>> {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
68
|
+
return await this.scope(async connection => {
|
|
69
|
+
return await connection.query(sql, parameters, meta)
|
|
70
|
+
})
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async end(): Promise<void> {
|
|
74
|
+
await this.pool.end()
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
public async clearPool(): Promise<void> {
|
|
78
|
+
await this.pool.closeIdle()
|
|
82
79
|
}
|
|
83
80
|
|
|
84
81
|
getPoolStatus(): PoolStatus {
|
|
@@ -87,11 +84,6 @@ class Connection implements Connection.ConnectionLike, Connection.ClientFactory,
|
|
|
87
84
|
}
|
|
88
85
|
|
|
89
86
|
namespace Connection {
|
|
90
|
-
export interface QueryConfig {
|
|
91
|
-
timing?: boolean
|
|
92
|
-
eventManager?: EventManager
|
|
93
|
-
}
|
|
94
|
-
|
|
95
87
|
export interface Queryable {
|
|
96
88
|
readonly eventManager: EventManager
|
|
97
89
|
|
|
@@ -99,7 +91,6 @@ namespace Connection {
|
|
|
99
91
|
sql: string,
|
|
100
92
|
parameters?: readonly any[],
|
|
101
93
|
meta?: Record<string, any>,
|
|
102
|
-
config?: Connection.QueryConfig,
|
|
103
94
|
): Promise<Connection.Result<Row>>
|
|
104
95
|
}
|
|
105
96
|
|
|
@@ -115,7 +106,15 @@ namespace Connection {
|
|
|
115
106
|
& Connection.ClientFactory
|
|
116
107
|
& Connection.PoolStatusProvider
|
|
117
108
|
|
|
118
|
-
export interface
|
|
109
|
+
export interface Scopable<Sub> {
|
|
110
|
+
scope<Result>(
|
|
111
|
+
callback: (connection: Sub) => Promise<Result> | Result,
|
|
112
|
+
options?: { eventManager?: EventManager },
|
|
113
|
+
): Promise<Result>
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export interface ConnectionLike extends Transactional, Queryable, Scopable<ConnectionLike> {
|
|
117
|
+
}
|
|
119
118
|
|
|
120
119
|
export interface ClientFactory {
|
|
121
120
|
createClient(schema: string, queryMeta: Record<string, any>): Client
|
|
@@ -125,7 +124,7 @@ namespace Connection {
|
|
|
125
124
|
getPoolStatus(): PoolStatus | undefined
|
|
126
125
|
}
|
|
127
126
|
|
|
128
|
-
export interface TransactionLike extends
|
|
127
|
+
export interface TransactionLike extends Transactional, Queryable, Scopable<TransactionLike> {
|
|
129
128
|
readonly isClosed: boolean
|
|
130
129
|
|
|
131
130
|
rollback(): Promise<void>
|
|
@@ -133,10 +132,6 @@ namespace Connection {
|
|
|
133
132
|
commit(): Promise<void>
|
|
134
133
|
}
|
|
135
134
|
|
|
136
|
-
export interface QueryContext {
|
|
137
|
-
previousQueryEnd?: number
|
|
138
|
-
}
|
|
139
|
-
|
|
140
135
|
export interface Query {
|
|
141
136
|
readonly sql: string
|
|
142
137
|
readonly parameters: any[]
|
|
@@ -147,8 +142,9 @@ namespace Connection {
|
|
|
147
142
|
readonly rowCount: number
|
|
148
143
|
readonly rows: Row[]
|
|
149
144
|
readonly timing?: {
|
|
150
|
-
totalDuration: number
|
|
151
145
|
selfDuration: number
|
|
146
|
+
/** @deprecated both selfDuration and totalDuration now contains same number */
|
|
147
|
+
totalDuration: number
|
|
152
148
|
}
|
|
153
149
|
}
|
|
154
150
|
|
|
@@ -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,
|
|
@@ -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('
|
|
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.
|
|
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
package/src/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
|
+
}
|
|
@@ -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,
|
|
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
|
@@ -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
|
|
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) {
|