@contember/database 1.2.1 → 1.3.0-alpha.2

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 (83) hide show
  1. package/dist/src/builders/Compiler.d.ts.map +1 -1
  2. package/dist/src/builders/Compiler.js +8 -16
  3. package/dist/src/builders/Compiler.js.map +1 -1
  4. package/dist/src/builders/InsertBuilder.d.ts +2 -2
  5. package/dist/src/builders/InsertBuilder.d.ts.map +1 -1
  6. package/dist/src/builders/InsertBuilder.js +7 -4
  7. package/dist/src/builders/InsertBuilder.js.map +1 -1
  8. package/dist/src/builders/LockType.d.ts +8 -4
  9. package/dist/src/builders/LockType.d.ts.map +1 -1
  10. package/dist/src/builders/LockType.js +10 -5
  11. package/dist/src/builders/LockType.js.map +1 -1
  12. package/dist/src/builders/QueryBuilder.d.ts +4 -2
  13. package/dist/src/builders/QueryBuilder.d.ts.map +1 -1
  14. package/dist/src/builders/SelectBuilder.d.ts +6 -3
  15. package/dist/src/builders/SelectBuilder.d.ts.map +1 -1
  16. package/dist/src/builders/SelectBuilder.js +2 -2
  17. package/dist/src/builders/SelectBuilder.js.map +1 -1
  18. package/dist/src/builders/UpdateBuilder.d.ts +3 -1
  19. package/dist/src/builders/UpdateBuilder.d.ts.map +1 -1
  20. package/dist/src/builders/UpdateBuilder.js +4 -0
  21. package/dist/src/builders/UpdateBuilder.js.map +1 -1
  22. package/dist/src/builders/internal/Where.js +1 -1
  23. package/dist/src/builders/internal/Where.js.map +1 -1
  24. package/dist/src/builders/utils.d.ts.map +1 -1
  25. package/dist/src/builders/utils.js +6 -9
  26. package/dist/src/builders/utils.js.map +1 -1
  27. package/dist/src/client/AcquiredConnection.d.ts +4 -2
  28. package/dist/src/client/AcquiredConnection.d.ts.map +1 -1
  29. package/dist/src/client/AcquiredConnection.js +4 -0
  30. package/dist/src/client/AcquiredConnection.js.map +1 -1
  31. package/dist/src/client/Client.d.ts +1 -1
  32. package/dist/src/client/Client.d.ts.map +1 -1
  33. package/dist/src/client/Client.js.map +1 -1
  34. package/dist/src/client/Connection.d.ts +9 -5
  35. package/dist/src/client/Connection.d.ts.map +1 -1
  36. package/dist/src/client/Connection.js.map +1 -1
  37. package/dist/src/client/PgClient.d.ts +6 -4
  38. package/dist/src/client/PgClient.d.ts.map +1 -1
  39. package/dist/src/client/Transaction.d.ts +8 -2
  40. package/dist/src/client/Transaction.d.ts.map +1 -1
  41. package/dist/src/client/Transaction.js +2 -0
  42. package/dist/src/client/Transaction.js.map +1 -1
  43. package/dist/src/index.d.ts +1 -1
  44. package/dist/src/index.d.ts.map +1 -1
  45. package/dist/src/index.js +3 -1
  46. package/dist/src/index.js.map +1 -1
  47. package/dist/src/tsconfig.tsbuildinfo +1 -1
  48. package/dist/src/types.d.ts +2 -2
  49. package/dist/src/types.d.ts.map +1 -1
  50. package/dist/src/utils/ConstraintHelper.d.ts +1 -0
  51. package/dist/src/utils/ConstraintHelper.d.ts.map +1 -1
  52. package/dist/src/utils/ConstraintHelper.js +3 -0
  53. package/dist/src/utils/ConstraintHelper.js.map +1 -1
  54. package/dist/src/utils/index.d.ts +1 -0
  55. package/dist/src/utils/index.d.ts.map +1 -1
  56. package/dist/src/utils/index.js +1 -0
  57. package/dist/src/utils/index.js.map +1 -1
  58. package/dist/src/utils/listen.d.ts +32 -0
  59. package/dist/src/utils/listen.d.ts.map +1 -0
  60. package/dist/src/utils/listen.js +126 -0
  61. package/dist/src/utils/listen.js.map +1 -0
  62. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  63. package/package.json +3 -3
  64. package/src/builders/Compiler.ts +13 -17
  65. package/src/builders/InsertBuilder.ts +8 -5
  66. package/src/builders/LockType.ts +9 -4
  67. package/src/builders/QueryBuilder.ts +2 -1
  68. package/src/builders/SelectBuilder.ts +4 -4
  69. package/src/builders/UpdateBuilder.ts +4 -1
  70. package/src/builders/internal/Where.ts +1 -1
  71. package/src/builders/utils.ts +6 -9
  72. package/src/client/AcquiredConnection.ts +8 -2
  73. package/src/client/Client.ts +3 -3
  74. package/src/client/Connection.ts +9 -5
  75. package/src/client/PgClient.ts +8 -3
  76. package/src/client/Pool.ts +1 -1
  77. package/src/client/Transaction.ts +9 -3
  78. package/src/index.ts +2 -0
  79. package/src/tsconfig.json +1 -3
  80. package/src/types.ts +2 -2
  81. package/src/utils/ConstraintHelper.ts +4 -0
  82. package/src/utils/index.ts +1 -0
  83. package/src/utils/listen.ts +140 -0
@@ -31,7 +31,7 @@ class UpdateBuilder<Result extends UpdateBuilder.UpdateResult> implements With.A
31
31
  return this.withOption('table', name)
32
32
  }
33
33
 
34
- public values(columns: QueryBuilder.Values): UpdateBuilder<Result> {
34
+ public values<Values extends QueryBuilder.Values>(columns: { [K in keyof Values]?: Values[K] | QueryBuilder.ColumnExpression }): UpdateBuilder<Result> {
35
35
  return this.withOption('values', resolveValues(columns))
36
36
  }
37
37
 
@@ -75,6 +75,9 @@ class UpdateBuilder<Result extends UpdateBuilder.UpdateResult> implements With.A
75
75
  }
76
76
 
77
77
  public async execute(db: Client): Promise<Result> {
78
+ if (this.options.values?.length === 0) {
79
+ return this.options.returning.parseResponse<Result>({ rows: [], rowCount: 0 })
80
+ }
78
81
  const namespaceContext = new Compiler.Context(db.schema, new Set())
79
82
  const query = this.createQuery(namespaceContext)
80
83
  const result: Connection.Result = await db.query(query.sql, query.parameters)
@@ -37,7 +37,7 @@ namespace Where {
37
37
  )
38
38
 
39
39
  return new Literal(' where ').appendAll(
40
- this.values.map(it => (it instanceof Literal ? it : valueWhereToLiteral(it))),
40
+ this.values.map(it => (it instanceof Literal ? it : valueWhereToLiteral(it))).filter(it => it.sql !== ''),
41
41
  ' and ',
42
42
  )
43
43
  }
@@ -1,5 +1,4 @@
1
1
  import { Literal } from '../Literal'
2
- import { Value } from '../types'
3
2
  import { QueryBuilder } from './QueryBuilder'
4
3
  import { ColumnExpressionFactory } from './ColumnExpressionFactory'
5
4
  import { toFqnWrap } from './formatUtils'
@@ -8,16 +7,14 @@ export { toFqnWrap }
8
7
 
9
8
  export function resolveValues(values: QueryBuilder.Values): QueryBuilder.ResolvedValues {
10
9
  return Object.entries(values)
11
- .map(([key, value]): [string, Literal | Value | undefined] => {
12
- if (typeof value === 'function') {
13
- return [key, value(new ColumnExpressionFactory())]
14
- } else if (value instanceof Literal) {
15
- return [key, value]
10
+ .map(([key, value]) => {
11
+ const resolved = typeof value === 'function' ? value(new ColumnExpressionFactory()) : value
12
+ return {
13
+ columnName: key,
14
+ value: resolved === undefined || resolved instanceof Literal ? resolved : new Literal('?', [resolved]),
16
15
  }
17
- return [key, new Literal('?', [value])]
18
16
  })
19
- .filter((it): it is [string, Literal] => it[1] !== undefined)
20
- .reduce((result, [key, value]) => ({ ...result, [key]: value }), {})
17
+ .filter((it): it is QueryBuilder.ResolvedValue => it.value !== undefined)
21
18
  }
22
19
 
23
20
  export function columnExpressionToLiteral(
@@ -13,8 +13,9 @@ import {
13
13
  UniqueViolationError,
14
14
  } from './errors'
15
15
  import { PgClient } from './PgClient'
16
+ import { Notification } from 'pg'
16
17
 
17
- export class AcquiredConnection implements Connection.ConnectionLike {
18
+ export class AcquiredConnection implements Connection.AcquiredConnectionLike {
18
19
  private mutex = new Mutex()
19
20
 
20
21
  constructor(
@@ -24,7 +25,7 @@ export class AcquiredConnection implements Connection.ConnectionLike {
24
25
  }
25
26
 
26
27
  async scope<Result>(
27
- callback: (connection: Connection.ConnectionLike) => Promise<Result> | Result,
28
+ callback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,
28
29
  options: { eventManager?: EventManager } = {},
29
30
  ): Promise<Result> {
30
31
  return await this.mutex.execute(async () => {
@@ -96,6 +97,11 @@ export class AcquiredConnection implements Connection.ConnectionLike {
96
97
  }
97
98
  })
98
99
  }
100
+
101
+ on(event: 'end' | 'notification' | 'error', cb: (() => void) | ((notification: Notification) => void) | ((error: any) => void)) {
102
+ this.pgClient.on(event as any, cb)
103
+ return () => this.pgClient.off(event as any, cb)
104
+ }
99
105
  }
100
106
 
101
107
  function prepareSql(sql: string) {
@@ -3,7 +3,7 @@ import { DatabaseQueryable } from '../queryable'
3
3
  import { Connection } from './Connection'
4
4
  import { EventManager } from './EventManager'
5
5
  import { QueryHandler } from '@contember/queryable'
6
- import { withDatabaseAdvisoryLock } from '../utils'
6
+ import { withDatabaseAdvisoryLock, wrapIdentifier } from '../utils'
7
7
 
8
8
  class Client<ConnectionType extends Connection.ConnectionLike = Connection.ConnectionLike> implements Connection.Queryable {
9
9
  constructor(
@@ -19,11 +19,11 @@ class Client<ConnectionType extends Connection.ConnectionLike = Connection.Conne
19
19
  return new Client<ConnectionType>(this.connection, schema, this.queryMeta, eventManager)
20
20
  }
21
21
 
22
- async scope<T>(callback: (wrapper: Client<Connection.ConnectionLike>) => Promise<T> | T): Promise<T> {
22
+ async scope<T>(callback: (wrapper: Client<ConnectionType & Connection.AcquiredConnectionLike>) => Promise<T> | T): Promise<T> {
23
23
  return await this.connection.scope(
24
24
  connection => callback(
25
25
  new Client(
26
- connection,
26
+ connection as ConnectionType & Connection.AcquiredConnectionLike,
27
27
  this.schema,
28
28
  this.queryMeta,
29
29
  new EventManager(connection.eventManager),
@@ -4,6 +4,7 @@ import { Pool, PoolConfig, PoolStatus } from './Pool'
4
4
  import { createPgClientFactory } from '../utils'
5
5
  import { DatabaseConfig } from '../types'
6
6
  import { AcquiredConnection } from './AcquiredConnection'
7
+ import { Notification } from 'pg'
7
8
 
8
9
  class Connection implements Connection.ConnectionLike, Connection.ClientFactory, Connection.PoolStatusProvider {
9
10
  constructor(
@@ -31,7 +32,7 @@ class Connection implements Connection.ConnectionLike, Connection.ClientFactory,
31
32
  }
32
33
 
33
34
  async scope<Result>(
34
- callback: (connection: Connection.ConnectionLike) => Promise<Result> | Result,
35
+ callback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,
35
36
  options: { eventManager?: EventManager } = {},
36
37
  ): Promise<Result> {
37
38
  const acquired = await this.pool.acquire()
@@ -103,14 +104,17 @@ namespace Connection {
103
104
  & Connection.ClientFactory
104
105
  & Connection.PoolStatusProvider
105
106
 
106
- export interface Scopable<Sub> {
107
+ export interface ConnectionLike<T = {}> extends Transactional, Queryable {
107
108
  scope<Result>(
108
- callback: (connection: Sub) => Promise<Result> | Result,
109
+ callback: (connection: T & AcquiredConnectionLike) => Promise<Result> | Result,
109
110
  options?: { eventManager?: EventManager },
110
111
  ): Promise<Result>
111
112
  }
112
113
 
113
- export interface ConnectionLike extends Transactional, Queryable, Scopable<ConnectionLike> {
114
+ export interface AcquiredConnectionLike<T = {}> extends ConnectionLike<T> {
115
+ on(event: 'notification', listener: (message: Notification) => void): () => void
116
+ on(event: 'end', listener: () => void): () => void
117
+ on(event: 'error', listener: (error: any) => void): () => void
114
118
  }
115
119
 
116
120
  export interface ClientFactory {
@@ -121,7 +125,7 @@ namespace Connection {
121
125
  getPoolStatus(): PoolStatus | undefined
122
126
  }
123
127
 
124
- export interface TransactionLike extends Transactional, Queryable, Scopable<TransactionLike> {
128
+ export interface TransactionLike extends AcquiredConnectionLike<TransactionLike> {
125
129
  readonly isClosed: boolean
126
130
 
127
131
  rollback(): Promise<void>
@@ -1,7 +1,6 @@
1
- import { QueryConfig, QueryResult, QueryResultRow } from 'pg'
2
- import EventEmitter from 'node:events'
1
+ import { Notification, QueryConfig, QueryResult, QueryResultRow } from 'pg'
3
2
 
4
- export interface PgClient extends EventEmitter {
3
+ export interface PgClient {
5
4
  connect(): Promise<void>
6
5
 
7
6
  query<R extends QueryResultRow = any, I extends any[] = any[]>(
@@ -10,4 +9,10 @@ export interface PgClient extends EventEmitter {
10
9
  ): Promise<QueryResult<R>>
11
10
 
12
11
  end(): Promise<void>
12
+
13
+ on(event: 'notification', listener: (message: Notification) => void): this
14
+ on(event: 'error', listener: (err: Error) => void): this
15
+ on(event: 'end', listener: () => void): this
16
+
17
+ off(eventName: string | symbol, listener: (...args: any[]) => void): this
13
18
  }
@@ -1,6 +1,6 @@
1
1
  import { ImplementationException } from '../exceptions'
2
2
  import { ClientErrorCodes } from './errorCodes'
3
- import EventEmitter from 'node:events'
3
+ import { EventEmitter } from 'node:events'
4
4
  import { ClientError, DatabaseError } from './errors'
5
5
  import { PgClientFactory } from '../utils'
6
6
  import { PgClient } from './PgClient'
@@ -1,6 +1,7 @@
1
1
  import { Connection } from './Connection'
2
2
  import { EventManager } from './EventManager'
3
3
  import { wrapIdentifier } from '../utils'
4
+ import { Notification } from 'pg'
4
5
 
5
6
  export class Transaction implements Connection.TransactionLike {
6
7
  public get isClosed(): boolean {
@@ -8,7 +9,7 @@ export class Transaction implements Connection.TransactionLike {
8
9
  }
9
10
 
10
11
  constructor(
11
- private readonly connection: Connection.ConnectionLike,
12
+ private readonly connection: Connection.AcquiredConnectionLike,
12
13
  private readonly savepointManager = new SavepointState(),
13
14
  private readonly state = new TransactionLikeState(),
14
15
  ) {
@@ -61,6 +62,9 @@ export class Transaction implements Connection.TransactionLike {
61
62
  await this.query(command)
62
63
  this.state.close()
63
64
  }
65
+
66
+ on = this.connection.on.bind(this.connection)
67
+
64
68
  }
65
69
 
66
70
  class SavePoint implements Connection.TransactionLike {
@@ -68,7 +72,7 @@ class SavePoint implements Connection.TransactionLike {
68
72
  constructor(
69
73
  public readonly savepointName: string,
70
74
  public readonly savepointManager: SavepointState,
71
- private readonly connection: Connection.ConnectionLike,
75
+ private readonly connection: Connection.AcquiredConnectionLike,
72
76
  private readonly state = new TransactionLikeState(),
73
77
  ) {
74
78
  }
@@ -125,6 +129,8 @@ class SavePoint implements Connection.TransactionLike {
125
129
  await this.query(sql)
126
130
  this.state.close()
127
131
  }
132
+
133
+ on = this.connection.on.bind(this.connection)
128
134
  }
129
135
 
130
136
  class TransactionLikeState {
@@ -143,7 +149,7 @@ class SavepointState {
143
149
  public counter = 1
144
150
 
145
151
  public async execute<Result>(
146
- connection: Connection.ConnectionLike,
152
+ connection: Connection.AcquiredConnectionLike,
147
153
  callback: (connection: Connection.TransactionLike) => Promise<Result> | Result,
148
154
  ) {
149
155
  const savepointName = `savepoint_${this.counter++}`
package/src/index.ts CHANGED
@@ -19,4 +19,6 @@ export {
19
19
  withDatabaseAdvisoryLock,
20
20
  createDatabaseIfNotExists,
21
21
  createPgClientFactory,
22
+ Listener,
23
+ AcquiringListener,
22
24
  } from './utils'
package/src/tsconfig.json CHANGED
@@ -4,8 +4,6 @@
4
4
  "outDir": "../dist/src"
5
5
  },
6
6
  "references": [
7
- {
8
- "path": "../../queryable/src"
9
- }
7
+ { "path": "../../queryable/src" }
10
8
  ]
11
9
  }
package/src/types.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export type JSONPrimitive = string | number | boolean | null | undefined
2
2
  export type JSONValue = JSONPrimitive | JSONObject | JSONArray
3
- export type JSONObject = { [member: string]: JSONValue }
4
- export type JSONArray = JSONValue[]
3
+ export type JSONObject = { readonly [K in string]?: JSONValue }
4
+ export type JSONArray = readonly JSONValue[]
5
5
 
6
6
  export type Value =
7
7
  | JSONValue
@@ -7,6 +7,10 @@ export class ConstraintHelper {
7
7
 
8
8
  constructor(private readonly client: Client) {}
9
9
 
10
+ public areFkConstraintsDeferred(): boolean {
11
+ return this.fkConstraintsLevel > 0
12
+ }
13
+
10
14
  public async setFkConstraintsDeferred(): Promise<void> {
11
15
  this.fkConstraintsLevel++
12
16
  if (this.fkConstraintsLevel > 1) {
@@ -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 './listen'
5
6
  export * from './Mutex'
6
7
  export * from './sql'
7
8
  export * from './retryTransaction'
@@ -0,0 +1,140 @@
1
+ import { Client, Connection } from '../client'
2
+ import { wrapIdentifier } from './sql'
3
+ import { clearInterval } from 'node:timers'
4
+
5
+ type ListenArgs<P> = {
6
+ client: Client<Connection.AcquiredConnectionLike>
7
+ channel: string
8
+ abortSignal?: AbortSignal
9
+ healthCheckMs?: number
10
+ onMessage: (payload: P) => void
11
+ onError: (err: any) => void
12
+ onClose?: () => void
13
+ }
14
+
15
+
16
+ export class Listener<P> {
17
+ constructor(
18
+ private readonly client: Client<Connection.AcquiredConnectionLike>,
19
+ private readonly channel: string,
20
+ private readonly onMessage: (message: P) => void,
21
+ private readonly options: { healthCheckMs?: number } = {},
22
+ ) {
23
+ }
24
+
25
+ async run({ onClose, onError }: {
26
+ onError: (e: any) => void
27
+ onClose?: () => void
28
+ },
29
+ ): Promise<{ end: () => Promise<void> }> {
30
+ let aborted = false
31
+ let onAbortInner = async () => {}
32
+ const onAbort = async () => {
33
+ aborted = true
34
+ await onAbortInner()
35
+ }
36
+ let cleanups: (() => void)[] = []
37
+ const cleanup = () => {
38
+ let localCleanup = cleanups
39
+ cleanups = []
40
+ localCleanup.forEach(it => it())
41
+ }
42
+ try {
43
+ cleanups.push(this.client.connection.on('notification', ({ channel, payload }) => {
44
+ if (channel !== this.channel || aborted) {
45
+ return
46
+ }
47
+ this.onMessage(payload as P)
48
+ }))
49
+ await this.client.query(`LISTEN ${wrapIdentifier(this.channel)}`)
50
+
51
+ ;(async () => {
52
+ const stopListening = async () => {
53
+ try {
54
+ await this.client.query(`UNLISTEN ${wrapIdentifier(this.channel)}`)
55
+ } catch {
56
+ }
57
+ }
58
+
59
+ try {
60
+ if (aborted) {
61
+ await stopListening()
62
+ return
63
+ }
64
+ await new Promise<void>((resolve, reject) => {
65
+ onAbortInner = async () => {
66
+ await stopListening()
67
+ resolve()
68
+ }
69
+ cleanups.push(this.client.connection.on('end', reject))
70
+ cleanups.push(this.client.connection.on('error', reject))
71
+
72
+ const healthCheckHandle = setInterval(async () => {
73
+ try {
74
+ await this.client.query('SELECT 1')
75
+ } catch (e) {
76
+ reject(e)
77
+ }
78
+ }, this.options.healthCheckMs ?? 30_000)
79
+ cleanups.push(() => clearInterval(healthCheckHandle))
80
+ })
81
+ onClose?.()
82
+ } catch (e) {
83
+ onError(e)
84
+ } finally {
85
+ cleanup()
86
+ }
87
+ })()
88
+
89
+ return {
90
+ end: async () => {
91
+ await onAbort()
92
+ },
93
+ }
94
+ } catch (e) {
95
+ cleanup()
96
+ throw e
97
+ }
98
+ }
99
+ }
100
+
101
+
102
+ export class AcquiringListener<P> {
103
+ constructor(
104
+ private readonly client: Client,
105
+ private readonly channel: string,
106
+ private readonly onMessage: (message: P) => void,
107
+ private readonly options: { healthCheckMs?: number } = {},
108
+ ) {
109
+ }
110
+
111
+ async run({ onClose, onError }: { onError: (e: any) => void;onClose?: () => void },
112
+ ): Promise<{ end: () => Promise<void> }> {
113
+ return new Promise(async (resolveRunning, rejectRunning) => {
114
+ try {
115
+ await this.client.scope(async db => {
116
+ const listener = new Listener<P>(db, this.channel, this.onMessage, this.options)
117
+ await new Promise<void>(async (resolveScope, rejectScope) => {
118
+ try {
119
+ const running = await listener.run({
120
+ onClose: resolveScope,
121
+ onError: rejectScope,
122
+ })
123
+ resolveRunning({
124
+ end: async () => {
125
+ await running.end()
126
+ },
127
+ })
128
+ } catch (e) {
129
+ rejectScope(e)
130
+ }
131
+ })
132
+ })
133
+ onClose?.()
134
+ } catch (e) {
135
+ rejectRunning(e)
136
+ onError(e)
137
+ }
138
+ })
139
+ }
140
+ }