@contember/database 2.0.8 → 2.0.10

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 (41) hide show
  1. package/dist/development/src/builders/LimitByGroupWrapper.cjs +1 -1
  2. package/dist/development/src/builders/LimitByGroupWrapper.cjs.map +1 -1
  3. package/dist/development/src/builders/LimitByGroupWrapper.js +1 -1
  4. package/dist/development/src/builders/LimitByGroupWrapper.js.map +1 -1
  5. package/dist/development/src/builders/WindowFunction.cjs +1 -1
  6. package/dist/development/src/builders/WindowFunction.cjs.map +1 -1
  7. package/dist/development/src/builders/WindowFunction.js +1 -1
  8. package/dist/development/src/builders/WindowFunction.js.map +1 -1
  9. package/dist/development/src/client/Connection.cjs +41 -5
  10. package/dist/development/src/client/Connection.cjs.map +1 -1
  11. package/dist/development/src/client/Connection.js +41 -5
  12. package/dist/development/src/client/Connection.js.map +1 -1
  13. package/dist/production/src/builders/LimitByGroupWrapper.cjs +1 -1
  14. package/dist/production/src/builders/LimitByGroupWrapper.cjs.map +1 -1
  15. package/dist/production/src/builders/LimitByGroupWrapper.js +1 -1
  16. package/dist/production/src/builders/LimitByGroupWrapper.js.map +1 -1
  17. package/dist/production/src/builders/WindowFunction.cjs +1 -1
  18. package/dist/production/src/builders/WindowFunction.cjs.map +1 -1
  19. package/dist/production/src/builders/WindowFunction.js +1 -1
  20. package/dist/production/src/builders/WindowFunction.js.map +1 -1
  21. package/dist/production/src/client/Connection.cjs +41 -5
  22. package/dist/production/src/client/Connection.cjs.map +1 -1
  23. package/dist/production/src/client/Connection.js +41 -5
  24. package/dist/production/src/client/Connection.js.map +1 -1
  25. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts +7 -2
  26. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts.map +1 -1
  27. package/dist/tests/cases/unit/staleConnectionRetry.test.d.ts +2 -0
  28. package/dist/tests/cases/unit/staleConnectionRetry.test.d.ts.map +1 -0
  29. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  30. package/dist/types/builders/WindowFunction.d.ts +2 -1
  31. package/dist/types/builders/WindowFunction.d.ts.map +1 -1
  32. package/dist/types/client/Connection.d.ts +11 -2
  33. package/dist/types/client/Connection.d.ts.map +1 -1
  34. package/dist/types/tsconfig.tsbuildinfo +1 -1
  35. package/package.json +4 -4
  36. package/src/builders/LimitByGroupWrapper.ts +1 -1
  37. package/src/builders/WindowFunction.ts +3 -2
  38. package/src/client/Connection.ts +58 -3
  39. package/tests/cases/unit/createConnectionMockAlt.ts +18 -2
  40. package/tests/cases/unit/queryBuilder.test.ts +22 -1
  41. package/tests/cases/unit/staleConnectionRetry.test.ts +86 -0
@@ -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
- export const createConnectionMockAlt = (...queries: { sql: string; timeout?: number; result?: any }[][]): [Connection, () => void] => {
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(new class extends EventEmitter {
@@ -20,6 +30,12 @@ export const createConnectionMockAlt = (...queries: { sql: string; timeout?: num
20
30
  expect(query).toBeDefined()
21
31
  expect(sql).toEqual(query?.sql as string)
22
32
  await new Promise<void>(resolve => setTimeout(resolve, query?.timeout ?? 1))
33
+ if (query?.lost) {
34
+ this.emit('error', query.error)
35
+ }
36
+ if (query?.error) {
37
+ throw query.error
38
+ }
23
39
 
24
40
  return query?.result
25
41
  }
@@ -36,7 +52,7 @@ export const createConnectionMockAlt = (...queries: { sql: string; timeout?: num
36
52
  })()
37
53
  }, { logError: () => null })
38
54
  return [
39
- new Connection(pool),
55
+ new Connection(pool, undefined, connectionOptions),
40
56
  () => {
41
57
  allMocks.forEach(it => it.assertEmpty())
42
58
  },
@@ -341,6 +341,27 @@ test('query builder: constructs window function', async () => {
341
341
  })
342
342
  })
343
343
 
344
+ test('query builder: preserves null placement in window ordering', async () => {
345
+ await execute({
346
+ query: async wrapper => {
347
+ const qb = wrapper
348
+ .selectBuilder()
349
+ .select(expr =>
350
+ expr.window(window =>
351
+ window
352
+ .rowNumber()
353
+ .orderBy(['foo', 'first'], 'asc nulls first')
354
+ .orderBy(['foo', 'second'], 'desc nulls last'),
355
+ ),
356
+ )
357
+
358
+ await qb.getResult(wrapper)
359
+ },
360
+ sql: SQL`select row_number() over(order by "foo"."first" asc nulls first, "foo"."second" desc nulls last)`,
361
+ parameters: [],
362
+ })
363
+ })
364
+
344
365
  test('query builder: applies limit by group', async () => {
345
366
  await execute({
346
367
  query: async wrapper => {
@@ -362,7 +383,7 @@ test('query builder: applies limit by group', async () => {
362
383
  (select "foo"."bar",
363
384
  row_number() over(partition by "foo"."lorem" order by "foo"."ipsum" asc) as "rowNumber_"
364
385
  from "public"."foo" order by "foo"."ipsum" asc)
365
- select "data".* from "data" where "data"."rowNumber_" > ? and "data"."rowNumber_" <= ?`,
386
+ select "data".* from "data" where "data"."rowNumber_" > ? and "data"."rowNumber_" <= ? order by "data"."rowNumber_" asc`,
366
387
  parameters: [1, 4],
367
388
  })
368
389
  })
@@ -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
+ })