@contember/database 2.1.0-rc.3 → 2.1.0-rc.5
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/development/src/builders/LimitByGroupWrapper.cjs +1 -1
- package/dist/development/src/builders/LimitByGroupWrapper.cjs.map +1 -1
- package/dist/development/src/builders/LimitByGroupWrapper.js +1 -1
- package/dist/development/src/builders/LimitByGroupWrapper.js.map +1 -1
- package/dist/development/src/builders/WindowFunction.cjs +1 -1
- package/dist/development/src/builders/WindowFunction.cjs.map +1 -1
- package/dist/development/src/builders/WindowFunction.js +1 -1
- package/dist/development/src/builders/WindowFunction.js.map +1 -1
- package/dist/development/src/client/Connection.cjs +41 -5
- package/dist/development/src/client/Connection.cjs.map +1 -1
- package/dist/development/src/client/Connection.js +41 -5
- package/dist/development/src/client/Connection.js.map +1 -1
- package/dist/production/src/builders/LimitByGroupWrapper.cjs +1 -1
- package/dist/production/src/builders/LimitByGroupWrapper.cjs.map +1 -1
- package/dist/production/src/builders/LimitByGroupWrapper.js +1 -1
- package/dist/production/src/builders/LimitByGroupWrapper.js.map +1 -1
- package/dist/production/src/builders/WindowFunction.cjs +1 -1
- package/dist/production/src/builders/WindowFunction.cjs.map +1 -1
- package/dist/production/src/builders/WindowFunction.js +1 -1
- package/dist/production/src/builders/WindowFunction.js.map +1 -1
- package/dist/production/src/client/Connection.cjs +41 -5
- package/dist/production/src/client/Connection.cjs.map +1 -1
- package/dist/production/src/client/Connection.js +41 -5
- package/dist/production/src/client/Connection.js.map +1 -1
- package/dist/tests/cases/unit/createConnectionMockAlt.d.ts +7 -2
- package/dist/tests/cases/unit/createConnectionMockAlt.d.ts.map +1 -1
- package/dist/tests/cases/unit/staleConnectionRetry.test.d.ts +2 -0
- package/dist/tests/cases/unit/staleConnectionRetry.test.d.ts.map +1 -0
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/types/builders/WindowFunction.d.ts +2 -1
- package/dist/types/builders/WindowFunction.d.ts.map +1 -1
- package/dist/types/client/Connection.d.ts +11 -2
- package/dist/types/client/Connection.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +3 -3
- package/src/builders/LimitByGroupWrapper.ts +1 -1
- package/src/builders/WindowFunction.ts +3 -2
- package/src/client/Connection.ts +58 -3
- package/tests/cases/unit/createConnectionMockAlt.ts +18 -2
- package/tests/cases/unit/queryBuilder.test.ts +22 -1
- package/tests/cases/unit/staleConnectionRetry.test.ts +86 -0
package/src/client/Connection.ts
CHANGED
|
@@ -5,19 +5,23 @@ import { createPgClientFactory } from '../utils'
|
|
|
5
5
|
import { DatabaseConfig } from '../types'
|
|
6
6
|
import { AcquiredConnection } from './AcquiredConnection'
|
|
7
7
|
import { Notification } from 'pg'
|
|
8
|
+
import { DatabaseError } from './errors'
|
|
9
|
+
import { ClientErrorCodes } from './errorCodes'
|
|
8
10
|
|
|
9
11
|
class Connection implements Connection.ConnectionLike, Connection.ClientFactory, Connection.PoolStatusProvider {
|
|
10
12
|
constructor(
|
|
11
13
|
private readonly pool: Pool,
|
|
12
14
|
public readonly eventManager: EventManager = new EventManager(null),
|
|
15
|
+
private readonly options: Connection.Options = {},
|
|
13
16
|
) {
|
|
14
17
|
}
|
|
15
18
|
|
|
16
19
|
public static create(
|
|
17
20
|
{ pool = {}, ...config }: DatabaseConfig & { pool?: Omit<PoolConfig, 'logError'> },
|
|
18
21
|
logError: (error: Error) => void,
|
|
22
|
+
options: Connection.Options = {},
|
|
19
23
|
): Connection {
|
|
20
|
-
return new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }))
|
|
24
|
+
return new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }), new EventManager(null), options)
|
|
21
25
|
}
|
|
22
26
|
|
|
23
27
|
public static createSingle(
|
|
@@ -35,17 +39,49 @@ class Connection implements Connection.ConnectionLike, Connection.ClientFactory,
|
|
|
35
39
|
callback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,
|
|
36
40
|
options: { eventManager?: EventManager } = {},
|
|
37
41
|
): Promise<Result> {
|
|
38
|
-
const acquired = await this.pool.acquire()
|
|
39
42
|
const eventManager = new EventManager(options.eventManager ?? this.eventManager)
|
|
43
|
+
// Each retry disposes the stale connection it got, so the loop ends once the idle connections are used up.
|
|
44
|
+
while (true) {
|
|
45
|
+
const attempt = await this.scopeOnce(callback, eventManager)
|
|
46
|
+
if (!attempt.stale) {
|
|
47
|
+
return attempt.result
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
private async scopeOnce<Result>(
|
|
53
|
+
callback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,
|
|
54
|
+
eventManager: EventManager,
|
|
55
|
+
): Promise<{ stale: false; result: Result } | { stale: true }> {
|
|
56
|
+
const acquired = await this.pool.acquire()
|
|
57
|
+
const reused = acquired.uses > 1
|
|
58
|
+
// pg emits `error` only for a connection lost unexpectedly, not for its own end().
|
|
59
|
+
let lost = false
|
|
60
|
+
let answered = false
|
|
61
|
+
const onError = () => {
|
|
62
|
+
lost = true
|
|
63
|
+
}
|
|
64
|
+
const onAnswer = () => {
|
|
65
|
+
answered = true
|
|
66
|
+
}
|
|
67
|
+
acquired.client.on('error', onError)
|
|
68
|
+
eventManager.on(EventManager.Event.queryEnd, onAnswer)
|
|
40
69
|
try {
|
|
41
70
|
const connection = new AcquiredConnection(acquired.client, eventManager)
|
|
42
71
|
const result = await callback(connection)
|
|
43
72
|
this.pool.release(acquired)
|
|
44
73
|
|
|
45
|
-
return result
|
|
74
|
+
return { stale: false, result }
|
|
46
75
|
} catch (e) {
|
|
47
76
|
this.pool.dispose(acquired)
|
|
77
|
+
// The server closed a pooled connection before answering anything, e.g. a pooler or replica restart.
|
|
78
|
+
if (this.options.retryStaleConnection && reused && !answered && (lost || isConnectionLoss(e))) {
|
|
79
|
+
return { stale: true }
|
|
80
|
+
}
|
|
48
81
|
throw e
|
|
82
|
+
} finally {
|
|
83
|
+
acquired.client.off('error', onError)
|
|
84
|
+
eventManager.removeListener(EventManager.Event.queryEnd, onAnswer)
|
|
49
85
|
}
|
|
50
86
|
}
|
|
51
87
|
|
|
@@ -81,7 +117,26 @@ class Connection implements Connection.ConnectionLike, Connection.ClientFactory,
|
|
|
81
117
|
}
|
|
82
118
|
}
|
|
83
119
|
|
|
120
|
+
const connectionLossCodes = new Set<string>([
|
|
121
|
+
ClientErrorCodes.CONNECTION_EXCEPTION,
|
|
122
|
+
ClientErrorCodes.CONNECTION_DOES_NOT_EXIST,
|
|
123
|
+
ClientErrorCodes.CONNECTION_FAILURE,
|
|
124
|
+
ClientErrorCodes.ADMIN_SHUTDOWN,
|
|
125
|
+
ClientErrorCodes.CRASH_SHUTDOWN,
|
|
126
|
+
])
|
|
127
|
+
|
|
128
|
+
const isConnectionLoss = (error: unknown): boolean =>
|
|
129
|
+
error instanceof DatabaseError && error.code !== undefined && connectionLossCodes.has(error.code)
|
|
130
|
+
|
|
84
131
|
namespace Connection {
|
|
132
|
+
export interface Options {
|
|
133
|
+
/**
|
|
134
|
+
* Runs a scope again on another connection when a connection taken from the pool turns out to be closed by
|
|
135
|
+
* the server before it answered anything. Only for connections whose scopes may run twice, such as a read replica.
|
|
136
|
+
*/
|
|
137
|
+
retryStaleConnection?: boolean
|
|
138
|
+
}
|
|
139
|
+
|
|
85
140
|
export interface Queryable {
|
|
86
141
|
readonly eventManager: EventManager
|
|
87
142
|
|
|
@@ -3,7 +3,17 @@ import { PgClient } from '../../../src/client/PgClient'
|
|
|
3
3
|
import EventEmitter from 'node:events'
|
|
4
4
|
import { expect } from 'bun:test'
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
// `error` rejects the query; with `lost`, the client first emits `error` as pg does when the server closes the connection.
|
|
7
|
+
type MockQuery = { sql: string; timeout?: number; result?: any; error?: Error; lost?: boolean }
|
|
8
|
+
|
|
9
|
+
export const createConnectionMockAlt = (...queries: MockQuery[][]): [Connection, () => void] => {
|
|
10
|
+
return createConnectionMockAltWithOptions({}, ...queries)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export const createConnectionMockAltWithOptions = (
|
|
14
|
+
connectionOptions: Connection.Options,
|
|
15
|
+
...queries: MockQuery[][]
|
|
16
|
+
): [Connection, () => void] => {
|
|
7
17
|
const connectionMocks: (PgClient & { assertEmpty: () => void })[] = []
|
|
8
18
|
for (const queriesSet of queries) {
|
|
9
19
|
connectionMocks.push(
|
|
@@ -21,6 +31,12 @@ export const createConnectionMockAlt = (...queries: { sql: string; timeout?: num
|
|
|
21
31
|
expect(query).toBeDefined()
|
|
22
32
|
expect(sql).toEqual(query?.sql as string)
|
|
23
33
|
await new Promise<void>(resolve => setTimeout(resolve, query?.timeout ?? 1))
|
|
34
|
+
if (query?.lost) {
|
|
35
|
+
this.emit('error', query.error)
|
|
36
|
+
}
|
|
37
|
+
if (query?.error) {
|
|
38
|
+
throw query.error
|
|
39
|
+
}
|
|
24
40
|
|
|
25
41
|
return query?.result
|
|
26
42
|
}
|
|
@@ -38,7 +54,7 @@ export const createConnectionMockAlt = (...queries: { sql: string; timeout?: num
|
|
|
38
54
|
})()
|
|
39
55
|
}, { logError: () => null })
|
|
40
56
|
return [
|
|
41
|
-
new Connection(pool),
|
|
57
|
+
new Connection(pool, undefined, connectionOptions),
|
|
42
58
|
() => {
|
|
43
59
|
allMocks.forEach(it => it.assertEmpty())
|
|
44
60
|
},
|
|
@@ -335,6 +335,27 @@ test('query builder: constructs window function', async () => {
|
|
|
335
335
|
})
|
|
336
336
|
})
|
|
337
337
|
|
|
338
|
+
test('query builder: preserves null placement in window ordering', async () => {
|
|
339
|
+
await execute({
|
|
340
|
+
query: async wrapper => {
|
|
341
|
+
const qb = wrapper
|
|
342
|
+
.selectBuilder()
|
|
343
|
+
.select(expr =>
|
|
344
|
+
expr.window(window =>
|
|
345
|
+
window
|
|
346
|
+
.rowNumber()
|
|
347
|
+
.orderBy(['foo', 'first'], 'asc nulls first')
|
|
348
|
+
.orderBy(['foo', 'second'], 'desc nulls last')
|
|
349
|
+
)
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
await qb.getResult(wrapper)
|
|
353
|
+
},
|
|
354
|
+
sql: SQL`select row_number() over(order by "foo"."first" asc nulls first, "foo"."second" desc nulls last)`,
|
|
355
|
+
parameters: [],
|
|
356
|
+
})
|
|
357
|
+
})
|
|
358
|
+
|
|
338
359
|
test('query builder: applies limit by group', async () => {
|
|
339
360
|
await execute({
|
|
340
361
|
query: async wrapper => {
|
|
@@ -356,7 +377,7 @@ test('query builder: applies limit by group', async () => {
|
|
|
356
377
|
(select "foo"."bar",
|
|
357
378
|
row_number() over(partition by "foo"."lorem" order by "foo"."ipsum" asc) as "rowNumber_"
|
|
358
379
|
from "public"."foo" order by "foo"."ipsum" asc)
|
|
359
|
-
select "data".* from "data" where "data"."rowNumber_" > ? and "data"."rowNumber_" <=
|
|
380
|
+
select "data".* from "data" where "data"."rowNumber_" > ? and "data"."rowNumber_" <= ? order by "data"."rowNumber_" asc`,
|
|
360
381
|
parameters: [1, 4],
|
|
361
382
|
})
|
|
362
383
|
})
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { expect, it } from 'bun:test'
|
|
2
|
+
import { createConnectionMockAltWithOptions } from './createConnectionMockAlt'
|
|
3
|
+
import { Connection } from '../../../src'
|
|
4
|
+
|
|
5
|
+
const terminated = () => new Error('Connection terminated unexpectedly')
|
|
6
|
+
const adminShutdown = () => Object.assign(new Error('terminating connection due to administrator command'), { code: '57P01' })
|
|
7
|
+
const retrying = { retryStaleConnection: true }
|
|
8
|
+
|
|
9
|
+
const warmUp = async (connection: Connection) => {
|
|
10
|
+
await connection.query('SELECT 1')
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
it('runs the scope again when a pooled connection was lost before answering', async () => {
|
|
14
|
+
const [connection, end] = createConnectionMockAltWithOptions(
|
|
15
|
+
retrying,
|
|
16
|
+
[{ sql: 'SELECT 1' }, { sql: 'BEGIN', error: terminated(), lost: true }],
|
|
17
|
+
[{ sql: 'BEGIN' }, { sql: 'SELECT 2', result: { rows: [{ ok: true }] } }, { sql: 'COMMIT', result: { command: 'COMMIT' } }],
|
|
18
|
+
)
|
|
19
|
+
await warmUp(connection)
|
|
20
|
+
const rows = await connection.transaction(async trx => (await trx.query('SELECT 2')).rows)
|
|
21
|
+
expect(rows).toStrictEqual([{ ok: true }])
|
|
22
|
+
end()
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
it('runs the scope again when the server shut a pooled connection down', async () => {
|
|
26
|
+
const [connection, end] = createConnectionMockAltWithOptions(
|
|
27
|
+
retrying,
|
|
28
|
+
[{ sql: 'SELECT 1' }, { sql: 'SELECT 2', error: adminShutdown() }],
|
|
29
|
+
[{ sql: 'SELECT 2', result: { rows: [] } }],
|
|
30
|
+
)
|
|
31
|
+
await warmUp(connection)
|
|
32
|
+
await connection.query('SELECT 2')
|
|
33
|
+
end()
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it('keeps going through stale idle connections until a working one', async () => {
|
|
37
|
+
const [connection, end] = createConnectionMockAltWithOptions(
|
|
38
|
+
retrying,
|
|
39
|
+
[{ sql: 'SELECT 1', timeout: 5 }, { sql: 'SELECT 2', error: terminated(), lost: true }],
|
|
40
|
+
[{ sql: 'SELECT 1', timeout: 5 }, { sql: 'SELECT 2', error: adminShutdown() }],
|
|
41
|
+
[{ sql: 'SELECT 2', result: { rows: [] } }],
|
|
42
|
+
)
|
|
43
|
+
await Promise.all([warmUp(connection), warmUp(connection)])
|
|
44
|
+
await connection.query('SELECT 2')
|
|
45
|
+
end()
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('does not retry without the option', async () => {
|
|
49
|
+
const [connection, end] = createConnectionMockAltWithOptions(
|
|
50
|
+
{},
|
|
51
|
+
[{ sql: 'SELECT 1' }, { sql: 'SELECT 2', error: terminated(), lost: true }],
|
|
52
|
+
)
|
|
53
|
+
await warmUp(connection)
|
|
54
|
+
await expect(connection.query('SELECT 2')).rejects.toThrow('Connection terminated unexpectedly')
|
|
55
|
+
end()
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('does not retry a new connection', async () => {
|
|
59
|
+
const [connection, end] = createConnectionMockAltWithOptions(
|
|
60
|
+
retrying,
|
|
61
|
+
[{ sql: 'SELECT 1', error: terminated(), lost: true }],
|
|
62
|
+
)
|
|
63
|
+
await expect(connection.query('SELECT 1')).rejects.toThrow('Connection terminated unexpectedly')
|
|
64
|
+
end()
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it('does not retry once the connection answered a query', async () => {
|
|
68
|
+
const [connection, end] = createConnectionMockAltWithOptions(
|
|
69
|
+
retrying,
|
|
70
|
+
[{ sql: 'SELECT 1' }, { sql: 'BEGIN' }, { sql: 'SELECT 2', error: terminated(), lost: true }, { sql: 'ROLLBACK' }],
|
|
71
|
+
)
|
|
72
|
+
await warmUp(connection)
|
|
73
|
+
await expect(connection.transaction(trx => trx.query('SELECT 2'))).rejects.toThrow('Connection terminated unexpectedly')
|
|
74
|
+
end()
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
it('does not retry a query error on a live connection', async () => {
|
|
78
|
+
const syntaxError = Object.assign(new Error('syntax error'), { code: '42601' })
|
|
79
|
+
const [connection, end] = createConnectionMockAltWithOptions(
|
|
80
|
+
retrying,
|
|
81
|
+
[{ sql: 'SELECT 1' }, { sql: 'SELECT 2', error: syntaxError }],
|
|
82
|
+
)
|
|
83
|
+
await warmUp(connection)
|
|
84
|
+
await expect(connection.query('SELECT 2')).rejects.toThrow('syntax error')
|
|
85
|
+
end()
|
|
86
|
+
})
|