@contember/database 2.2.0-alpha.2 → 2.2.0-alpha.21

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 (189) hide show
  1. package/CLAUDE.md +23 -1
  2. package/dist/development/index.cjs +6 -0
  3. package/dist/development/index.cjs.map +1 -1
  4. package/dist/development/index.js +7 -1
  5. package/dist/development/index.js.map +1 -1
  6. package/dist/development/src/builders/LimitByGroupWrapper.cjs +1 -1
  7. package/dist/development/src/builders/LimitByGroupWrapper.cjs.map +1 -1
  8. package/dist/development/src/builders/LimitByGroupWrapper.js +1 -1
  9. package/dist/development/src/builders/LimitByGroupWrapper.js.map +1 -1
  10. package/dist/development/src/builders/WindowFunction.cjs +1 -1
  11. package/dist/development/src/builders/WindowFunction.cjs.map +1 -1
  12. package/dist/development/src/builders/WindowFunction.js +1 -1
  13. package/dist/development/src/builders/WindowFunction.js.map +1 -1
  14. package/dist/development/src/client/AcquiredConnection.cjs +110 -32
  15. package/dist/development/src/client/AcquiredConnection.cjs.map +1 -1
  16. package/dist/development/src/client/AcquiredConnection.js +112 -34
  17. package/dist/development/src/client/AcquiredConnection.js.map +1 -1
  18. package/dist/development/src/client/Client.cjs +9 -1
  19. package/dist/development/src/client/Client.cjs.map +1 -1
  20. package/dist/development/src/client/Client.js +9 -1
  21. package/dist/development/src/client/Client.js.map +1 -1
  22. package/dist/development/src/client/Connection.cjs +48 -5
  23. package/dist/development/src/client/Connection.cjs.map +1 -1
  24. package/dist/development/src/client/Connection.js +48 -5
  25. package/dist/development/src/client/Connection.js.map +1 -1
  26. package/dist/development/src/client/EventManager.cjs +6 -2
  27. package/dist/development/src/client/EventManager.cjs.map +1 -1
  28. package/dist/development/src/client/EventManager.js +6 -2
  29. package/dist/development/src/client/EventManager.js.map +1 -1
  30. package/dist/development/src/client/RequestMemoryBudget.cjs +237 -0
  31. package/dist/development/src/client/RequestMemoryBudget.cjs.map +1 -0
  32. package/dist/development/src/client/RequestMemoryBudget.js +237 -0
  33. package/dist/development/src/client/RequestMemoryBudget.js.map +1 -0
  34. package/dist/development/src/client/Transaction.cjs +20 -8
  35. package/dist/development/src/client/Transaction.cjs.map +1 -1
  36. package/dist/development/src/client/Transaction.js +21 -9
  37. package/dist/development/src/client/Transaction.js.map +1 -1
  38. package/dist/development/src/client/cancelRunningStatement.cjs +32 -0
  39. package/dist/development/src/client/cancelRunningStatement.cjs.map +1 -0
  40. package/dist/development/src/client/cancelRunningStatement.js +32 -0
  41. package/dist/development/src/client/cancelRunningStatement.js.map +1 -0
  42. package/dist/development/src/client/errors.cjs +12 -1
  43. package/dist/development/src/client/errors.cjs.map +1 -1
  44. package/dist/development/src/client/errors.js +12 -1
  45. package/dist/development/src/client/errors.js.map +1 -1
  46. package/dist/development/src/utils/pgClientFactory.cjs +4 -1
  47. package/dist/development/src/utils/pgClientFactory.cjs.map +1 -1
  48. package/dist/development/src/utils/pgClientFactory.js +4 -1
  49. package/dist/development/src/utils/pgClientFactory.js.map +1 -1
  50. package/dist/production/index.cjs +6 -0
  51. package/dist/production/index.cjs.map +1 -1
  52. package/dist/production/index.js +7 -1
  53. package/dist/production/index.js.map +1 -1
  54. package/dist/production/src/builders/LimitByGroupWrapper.cjs +1 -1
  55. package/dist/production/src/builders/LimitByGroupWrapper.cjs.map +1 -1
  56. package/dist/production/src/builders/LimitByGroupWrapper.js +1 -1
  57. package/dist/production/src/builders/LimitByGroupWrapper.js.map +1 -1
  58. package/dist/production/src/builders/WindowFunction.cjs +1 -1
  59. package/dist/production/src/builders/WindowFunction.cjs.map +1 -1
  60. package/dist/production/src/builders/WindowFunction.js +1 -1
  61. package/dist/production/src/builders/WindowFunction.js.map +1 -1
  62. package/dist/production/src/client/AcquiredConnection.cjs +110 -32
  63. package/dist/production/src/client/AcquiredConnection.cjs.map +1 -1
  64. package/dist/production/src/client/AcquiredConnection.js +112 -34
  65. package/dist/production/src/client/AcquiredConnection.js.map +1 -1
  66. package/dist/production/src/client/Client.cjs +9 -1
  67. package/dist/production/src/client/Client.cjs.map +1 -1
  68. package/dist/production/src/client/Client.js +9 -1
  69. package/dist/production/src/client/Client.js.map +1 -1
  70. package/dist/production/src/client/Connection.cjs +48 -5
  71. package/dist/production/src/client/Connection.cjs.map +1 -1
  72. package/dist/production/src/client/Connection.js +48 -5
  73. package/dist/production/src/client/Connection.js.map +1 -1
  74. package/dist/production/src/client/EventManager.cjs +6 -2
  75. package/dist/production/src/client/EventManager.cjs.map +1 -1
  76. package/dist/production/src/client/EventManager.js +6 -2
  77. package/dist/production/src/client/EventManager.js.map +1 -1
  78. package/dist/production/src/client/RequestMemoryBudget.cjs +237 -0
  79. package/dist/production/src/client/RequestMemoryBudget.cjs.map +1 -0
  80. package/dist/production/src/client/RequestMemoryBudget.js +237 -0
  81. package/dist/production/src/client/RequestMemoryBudget.js.map +1 -0
  82. package/dist/production/src/client/Transaction.cjs +20 -8
  83. package/dist/production/src/client/Transaction.cjs.map +1 -1
  84. package/dist/production/src/client/Transaction.js +21 -9
  85. package/dist/production/src/client/Transaction.js.map +1 -1
  86. package/dist/production/src/client/cancelRunningStatement.cjs +32 -0
  87. package/dist/production/src/client/cancelRunningStatement.cjs.map +1 -0
  88. package/dist/production/src/client/cancelRunningStatement.js +32 -0
  89. package/dist/production/src/client/cancelRunningStatement.js.map +1 -0
  90. package/dist/production/src/client/errors.cjs +12 -1
  91. package/dist/production/src/client/errors.cjs.map +1 -1
  92. package/dist/production/src/client/errors.js +12 -1
  93. package/dist/production/src/client/errors.js.map +1 -1
  94. package/dist/production/src/utils/pgClientFactory.cjs +4 -1
  95. package/dist/production/src/utils/pgClientFactory.cjs.map +1 -1
  96. package/dist/production/src/utils/pgClientFactory.js +4 -1
  97. package/dist/production/src/utils/pgClientFactory.js.map +1 -1
  98. package/dist/tests/cases/integration/requestMemoryBudget.test.d.ts +2 -0
  99. package/dist/tests/cases/integration/requestMemoryBudget.test.d.ts.map +1 -0
  100. package/dist/tests/cases/unit/acquiredConnection.test.d.ts +2 -0
  101. package/dist/tests/cases/unit/acquiredConnection.test.d.ts.map +1 -0
  102. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts +12 -3
  103. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts.map +1 -1
  104. package/dist/tests/cases/unit/requestMemoryBudget.test.d.ts +2 -0
  105. package/dist/tests/cases/unit/requestMemoryBudget.test.d.ts.map +1 -0
  106. package/dist/tests/cases/unit/staleConnectionRetry.test.d.ts +2 -0
  107. package/dist/tests/cases/unit/staleConnectionRetry.test.d.ts.map +1 -0
  108. package/dist/tests/src/tags.d.ts.map +1 -1
  109. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  110. package/dist/types/Literal.d.ts.map +1 -1
  111. package/dist/types/builders/CaseStatement.d.ts.map +1 -1
  112. package/dist/types/builders/ColumnExpressionFactory.d.ts.map +1 -1
  113. package/dist/types/builders/Compiler.d.ts.map +1 -1
  114. package/dist/types/builders/ConditionBuilder.d.ts.map +1 -1
  115. package/dist/types/builders/DeleteBuilder.d.ts.map +1 -1
  116. package/dist/types/builders/InsertBuilder.d.ts.map +1 -1
  117. package/dist/types/builders/LimitByGroupWrapper.d.ts.map +1 -1
  118. package/dist/types/builders/SelectBuilder.d.ts.map +1 -1
  119. package/dist/types/builders/UpdateBuilder.d.ts.map +1 -1
  120. package/dist/types/builders/WindowFunction.d.ts +2 -1
  121. package/dist/types/builders/WindowFunction.d.ts.map +1 -1
  122. package/dist/types/builders/internal/Returning.d.ts.map +1 -1
  123. package/dist/types/builders/internal/Where.d.ts.map +1 -1
  124. package/dist/types/builders/internal/With.d.ts.map +1 -1
  125. package/dist/types/client/AcquiredConnection.d.ts +6 -1
  126. package/dist/types/client/AcquiredConnection.d.ts.map +1 -1
  127. package/dist/types/client/Client.d.ts +8 -0
  128. package/dist/types/client/Client.d.ts.map +1 -1
  129. package/dist/types/client/Connection.d.ts +11 -2
  130. package/dist/types/client/Connection.d.ts.map +1 -1
  131. package/dist/types/client/EventManager.d.ts +5 -1
  132. package/dist/types/client/EventManager.d.ts.map +1 -1
  133. package/dist/types/client/PgClient.d.ts +13 -2
  134. package/dist/types/client/PgClient.d.ts.map +1 -1
  135. package/dist/types/client/Pool.d.ts.map +1 -1
  136. package/dist/types/client/RequestMemoryBudget.d.ts +41 -0
  137. package/dist/types/client/RequestMemoryBudget.d.ts.map +1 -0
  138. package/dist/types/client/ScopeLimitedConnection.d.ts.map +1 -1
  139. package/dist/types/client/Transaction.d.ts +3 -3
  140. package/dist/types/client/Transaction.d.ts.map +1 -1
  141. package/dist/types/client/cancelRunningStatement.d.ts +7 -0
  142. package/dist/types/client/cancelRunningStatement.d.ts.map +1 -0
  143. package/dist/types/client/errors.d.ts +5 -0
  144. package/dist/types/client/errors.d.ts.map +1 -1
  145. package/dist/types/index.d.ts +1 -0
  146. package/dist/types/index.d.ts.map +1 -1
  147. package/dist/types/metadata/DatabaseMetadata.d.ts.map +1 -1
  148. package/dist/types/metadata/DatabaseMetadataResolver.d.ts.map +1 -1
  149. package/dist/types/metadata/ForeignKeyConstraintMetadata.d.ts.map +1 -1
  150. package/dist/types/metadata/IndexMetadata.d.ts.map +1 -1
  151. package/dist/types/metadata/UniqueConstraintMetadata.d.ts.map +1 -1
  152. package/dist/types/metadata/stringArrayEquals.d.ts.map +1 -1
  153. package/dist/types/queryable/DatabaseQuery.d.ts.map +1 -1
  154. package/dist/types/queryable/DatabaseQueryable.d.ts.map +1 -1
  155. package/dist/types/tsconfig.tsbuildinfo +1 -1
  156. package/dist/types/types.d.ts +15 -0
  157. package/dist/types/types.d.ts.map +1 -1
  158. package/dist/types/utils/ConstraintHelper.d.ts.map +1 -1
  159. package/dist/types/utils/Mutex.d.ts.map +1 -1
  160. package/dist/types/utils/Semaphore.d.ts.map +1 -1
  161. package/dist/types/utils/createDatabaseIfNotExists.d.ts.map +1 -1
  162. package/dist/types/utils/listen.d.ts.map +1 -1
  163. package/dist/types/utils/pgClientFactory.d.ts +1 -2
  164. package/dist/types/utils/pgClientFactory.d.ts.map +1 -1
  165. package/dist/types/utils/retryTransaction.d.ts.map +1 -1
  166. package/dist/types/utils/sql.d.ts.map +1 -1
  167. package/dist/types/utils/withDatabaseAdvisoryLock.d.ts.map +1 -1
  168. package/package.json +4 -3
  169. package/src/builders/LimitByGroupWrapper.ts +1 -1
  170. package/src/builders/WindowFunction.ts +3 -2
  171. package/src/client/AcquiredConnection.ts +131 -33
  172. package/src/client/Client.ts +11 -1
  173. package/src/client/Connection.ts +66 -3
  174. package/src/client/EventManager.ts +11 -1
  175. package/src/client/PgClient.ts +18 -2
  176. package/src/client/RequestMemoryBudget.ts +260 -0
  177. package/src/client/Transaction.ts +21 -8
  178. package/src/client/cancelRunningStatement.ts +36 -0
  179. package/src/client/errors.ts +15 -3
  180. package/src/index.ts +1 -0
  181. package/src/types.ts +15 -0
  182. package/src/utils/pgClientFactory.ts +5 -4
  183. package/tests/cases/integration/requestMemoryBudget.test.ts +296 -0
  184. package/tests/cases/unit/acquiredConnection.test.ts +209 -0
  185. package/tests/cases/unit/connection.test.ts +77 -1
  186. package/tests/cases/unit/createConnectionMockAlt.ts +35 -4
  187. package/tests/cases/unit/queryBuilder.test.ts +22 -1
  188. package/tests/cases/unit/requestMemoryBudget.test.ts +287 -0
  189. package/tests/cases/unit/staleConnectionRetry.test.ts +86 -0
@@ -0,0 +1,260 @@
1
+ import { Buffer } from 'node:buffer'
2
+
3
+ export interface RequestMemoryBudgetOptions {
4
+ warnBytes: number
5
+ maxBytes: number
6
+ }
7
+
8
+ const rowCompletionOverheadBytes = 256
9
+ const maximumRecursiveEstimateDepth = 64
10
+ const isBun = process.versions.bun !== undefined
11
+
12
+ export const validateRequestMemoryBudgetOptions = ({ warnBytes, maxBytes }: RequestMemoryBudgetOptions): string | undefined => {
13
+ if (!Number.isSafeInteger(warnBytes) || warnBytes <= 0) {
14
+ return 'warnBytes must be a positive safe integer'
15
+ }
16
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
17
+ return 'maxBytes must be a positive safe integer'
18
+ }
19
+ if (warnBytes > maxBytes) {
20
+ return 'warnBytes must not exceed maxBytes'
21
+ }
22
+ return undefined
23
+ }
24
+
25
+ export class RequestMemoryBudgetExceededError extends Error {
26
+ constructor() {
27
+ super('Request memory budget exceeded')
28
+ this.name = 'RequestMemoryBudgetExceededError'
29
+ }
30
+ }
31
+
32
+ export class RequestMemoryBudget {
33
+ private databaseBytes = 0
34
+ private hydrationBytes = 0
35
+ private peakBytes = 0
36
+ private databaseRows = 0
37
+ private largestDatabaseRowBytes = 0
38
+ private readonly databaseStrings = new StringMemoryEstimate()
39
+ private failure: RequestMemoryBudgetExceededError | undefined
40
+ // A plain set rather than an AbortSignal: every in-flight query of the request listens, and Node 20 warns above ten signal listeners.
41
+ private readonly exceededListeners = new Set<(failure: RequestMemoryBudgetExceededError) => void>()
42
+
43
+ constructor(private readonly options: RequestMemoryBudgetOptions) {
44
+ const optionsError = validateRequestMemoryBudgetOptions(options)
45
+ if (optionsError) {
46
+ throw new Error(`Invalid request memory budget: ${optionsError}`)
47
+ }
48
+ }
49
+
50
+ get exceeded(): boolean {
51
+ return this.failure !== undefined
52
+ }
53
+
54
+ check(): void {
55
+ if (this.failure) {
56
+ throw this.failure
57
+ }
58
+ }
59
+
60
+ /** Calls the listener once the budget is exceeded, immediately when it already is. Returns the unsubscribe. */
61
+ onExceeded(listener: (failure: RequestMemoryBudgetExceededError) => void): () => void {
62
+ if (this.failure) {
63
+ listener(this.failure)
64
+ return () => {}
65
+ }
66
+ this.exceededListeners.add(listener)
67
+ return () => this.exceededListeners.delete(listener)
68
+ }
69
+
70
+ addDatabaseRow(row: Record<string, unknown>): void {
71
+ this.check()
72
+ this.databaseRows++
73
+ let rowBytes = 40
74
+ for (const key in row) {
75
+ if (Object.prototype.hasOwnProperty.call(row, key)) {
76
+ rowBytes += 16 + estimateValueBytes(row[key], this.databaseStrings)
77
+ }
78
+ }
79
+ this.databaseBytes += rowBytes
80
+ this.largestDatabaseRowBytes = Math.max(this.largestDatabaseRowBytes, rowBytes)
81
+ this.update()
82
+ }
83
+
84
+ addHydrationBytes(bytes: number): void {
85
+ this.check()
86
+ this.hydrationBytes += bytes
87
+ this.update()
88
+ }
89
+
90
+ snapshot() {
91
+ return {
92
+ estimatedRetainedBytes: this.databaseBytes + this.hydrationBytes,
93
+ reservedCompletionBytes: this.getCompletionBytes(),
94
+ estimatedPeakBytes: this.peakBytes,
95
+ databaseRows: this.databaseRows,
96
+ databaseBytes: this.databaseBytes,
97
+ hydrationBytes: this.hydrationBytes,
98
+ warnBytes: this.options.warnBytes,
99
+ maxBytes: this.options.maxBytes,
100
+ warningThresholdExceeded: this.peakBytes > this.options.warnBytes,
101
+ maxBytesExceeded: this.peakBytes > this.options.maxBytes,
102
+ }
103
+ }
104
+
105
+ private getCompletionBytes(): number {
106
+ // GraphQL shares scalar strings with DB results; completion allocates structures and serialized text.
107
+ const projectedCompletionBytes = (this.databaseBytes - this.databaseStrings.retainedBytes) * 2
108
+ + this.databaseStrings.serializedBytes + this.hydrationBytes
109
+ // Decoding a row and serializing the response happen in different phases.
110
+ // JSC includes pg's growing buffers in its heap account; V8 reports them as external memory.
111
+ const decodingBytes = this.largestDatabaseRowBytes * (isBun ? 3 : 1)
112
+ return Math.max(projectedCompletionBytes, decodingBytes)
113
+ + this.databaseRows * rowCompletionOverheadBytes
114
+ }
115
+
116
+ private update(): void {
117
+ const estimatedBytes = this.databaseBytes + this.hydrationBytes + this.getCompletionBytes()
118
+ this.peakBytes = Math.max(this.peakBytes, estimatedBytes)
119
+ if (estimatedBytes > this.options.maxBytes) {
120
+ const failure = new RequestMemoryBudgetExceededError()
121
+ this.failure = failure
122
+ const listeners = [...this.exceededListeners]
123
+ this.exceededListeners.clear()
124
+ listeners.forEach(listener => listener(failure))
125
+ throw failure
126
+ }
127
+ }
128
+ }
129
+
130
+ function estimateValueBytes(value: unknown, strings: StringMemoryEstimate): number {
131
+ return estimateScalarBytes(value, strings) ?? estimateStructuredValueBytes(value, strings, 0)
132
+ }
133
+
134
+ function estimateStructuredValueBytes(value: unknown, strings: StringMemoryEstimate, depth: number): number {
135
+ if (depth >= maximumRecursiveEstimateDepth) {
136
+ return estimateDeepValueBytes(value, strings)
137
+ }
138
+ if (Array.isArray(value)) {
139
+ let bytes = 32 + value.length * 8
140
+ for (let i = 0; i < value.length; i++) {
141
+ const item: unknown = value[i]
142
+ const scalarBytes = estimateScalarBytes(item, strings)
143
+ bytes += scalarBytes ?? estimateStructuredValueBytes(item, strings, depth + 1)
144
+ }
145
+ return bytes
146
+ }
147
+ let bytes = 32
148
+ if (value !== null && typeof value === 'object') {
149
+ for (const key in value) {
150
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
151
+ const item: unknown = Reflect.get(value, key)
152
+ const scalarBytes = estimateScalarBytes(item, strings)
153
+ strings.addPropertyName(key)
154
+ bytes += 16 + (scalarBytes ?? estimateStructuredValueBytes(item, strings, depth + 1))
155
+ }
156
+ }
157
+ }
158
+ return bytes
159
+ }
160
+
161
+ function estimateDeepValueBytes(value: unknown, strings: StringMemoryEstimate): number {
162
+ const scalarBytes = estimateScalarBytes(value, strings)
163
+ if (scalarBytes !== undefined) {
164
+ return scalarBytes
165
+ }
166
+ let bytes = 0
167
+ const pending: Iterator<unknown>[] = [[value].values()]
168
+ while (pending.length > 0) {
169
+ const next = pending[pending.length - 1].next()
170
+ if (next.done) {
171
+ pending.pop()
172
+ continue
173
+ }
174
+ const current: unknown = next.value
175
+ const scalarBytes = estimateScalarBytes(current, strings)
176
+ if (scalarBytes !== undefined) {
177
+ bytes += scalarBytes
178
+ } else if (Array.isArray(current)) {
179
+ bytes += 32 + current.length * 8
180
+ pending.push(current.values())
181
+ } else if (current !== null && typeof current === 'object') {
182
+ bytes += 32
183
+ let hasNestedValues = false
184
+ for (const key in current) {
185
+ if (!Object.prototype.hasOwnProperty.call(current, key)) {
186
+ continue
187
+ }
188
+ strings.addPropertyName(key)
189
+ bytes += 16
190
+ const scalarBytes = estimateScalarBytes(Reflect.get(current, key), strings)
191
+ if (scalarBytes === undefined) {
192
+ hasNestedValues = true
193
+ } else {
194
+ bytes += scalarBytes
195
+ }
196
+ }
197
+ if (hasNestedValues) {
198
+ pending.push(nestedValues(current))
199
+ }
200
+ }
201
+ }
202
+ return bytes
203
+
204
+ function* nestedValues(object: object): Generator<unknown> {
205
+ for (const key in object) {
206
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
207
+ const value: unknown = Reflect.get(object, key)
208
+ if (value !== null && typeof value === 'object' && !(value instanceof Date) && !ArrayBuffer.isView(value)) {
209
+ yield value
210
+ }
211
+ }
212
+ }
213
+ }
214
+ }
215
+
216
+ function estimateScalarBytes(value: unknown, strings: StringMemoryEstimate): number | undefined {
217
+ if (typeof value === 'string') {
218
+ return 24 + strings.add(value)
219
+ }
220
+ if (value === null || typeof value !== 'object') {
221
+ return 8
222
+ }
223
+ if (value instanceof Date) {
224
+ return 40
225
+ }
226
+ if (ArrayBuffer.isView(value)) {
227
+ return 64 + value.byteLength
228
+ }
229
+ return undefined
230
+ }
231
+
232
+ class StringMemoryEstimate {
233
+ private codeUnits = 0
234
+ private storageBytes = 0
235
+ private nonAscii = false
236
+
237
+ get retainedBytes(): number {
238
+ return this.storageBytes
239
+ }
240
+
241
+ get serializedBytes(): number {
242
+ // One non-ASCII string can promote the entire serialized JSON string to two-byte storage.
243
+ return this.codeUnits * (this.nonAscii ? 2 : 1)
244
+ }
245
+
246
+ add(value: string): number {
247
+ // A native length comparison avoids a JavaScript character loop and RegExp.input, which can retain a request string.
248
+ const ascii = Buffer.byteLength(value) === value.length
249
+ this.nonAscii ||= !ascii
250
+ this.codeUnits += value.length
251
+ const bytes = ascii ? value.length : value.length * 2
252
+ this.storageBytes += bytes
253
+ return bytes
254
+ }
255
+
256
+ // Runtimes share property names between objects of one shape; only their serialized copies are new.
257
+ addPropertyName(key: string): void {
258
+ this.codeUnits += key.length
259
+ }
260
+ }
@@ -2,7 +2,7 @@ import { Connection } from './Connection.js'
2
2
  import { EventManager } from './EventManager.js'
3
3
  import { wrapIdentifier } from '../utils/index.js'
4
4
  import { Notification } from 'pg'
5
- import { CannotCommitError, DatabaseError } from './errors.js'
5
+ import { CannotCommitError, DatabaseError, TerminatedConnectionError } from './errors.js'
6
6
 
7
7
  export class Transaction implements Connection.TransactionLike {
8
8
  public get isClosed(): boolean {
@@ -55,7 +55,7 @@ export class Transaction implements Connection.TransactionLike {
55
55
  }
56
56
 
57
57
  async rollback(): Promise<void> {
58
- await this.close('ROLLBACK')
58
+ await this.close('ROLLBACK', new EventManager(this.eventManager, null))
59
59
  }
60
60
 
61
61
  async commit(): Promise<void> {
@@ -65,8 +65,11 @@ export class Transaction implements Connection.TransactionLike {
65
65
  }
66
66
  }
67
67
 
68
- private async close(command: string) {
69
- const result = await this.query(command)
68
+ private async close(command: string, eventManager = this.eventManager) {
69
+ if (this.isClosed) {
70
+ throw new Error('Transaction is already closed')
71
+ }
72
+ const result = await this.scope(connection => connection.query(command), { eventManager })
70
73
  this.state.close()
71
74
  return result
72
75
  }
@@ -124,15 +127,18 @@ class SavePoint implements Connection.TransactionLike {
124
127
  }
125
128
 
126
129
  async rollback(): Promise<void> {
127
- await this.close(`ROLLBACK TO SAVEPOINT ${wrapIdentifier(this.savepointName)}`)
130
+ await this.close(`ROLLBACK TO SAVEPOINT ${wrapIdentifier(this.savepointName)}`, new EventManager(this.eventManager, null))
128
131
  }
129
132
 
130
133
  async commit(): Promise<void> {
131
134
  await this.close(`RELEASE SAVEPOINT ${wrapIdentifier(this.savepointName)}`)
132
135
  }
133
136
 
134
- private async close(sql: string) {
135
- await this.query(sql)
137
+ private async close(sql: string, eventManager = this.eventManager) {
138
+ if (this.isClosed) {
139
+ throw new Error(`Savepoint ${this.savepointName} is already closed.`)
140
+ }
141
+ await this.scope(connection => connection.query(sql), { eventManager })
136
142
  this.state.close()
137
143
  }
138
144
  }
@@ -176,7 +182,14 @@ export const executeTransaction = async <Result>(
176
182
  return result
177
183
  } catch (e) {
178
184
  if (!transaction.isClosed) {
179
- await transaction.rollback()
185
+ try {
186
+ await transaction.rollback()
187
+ } catch (rollbackError) {
188
+ // PostgreSQL already rolled back the transaction of a terminated connection, whatever terminated it.
189
+ if (!(rollbackError instanceof TerminatedConnectionError)) {
190
+ throw rollbackError
191
+ }
192
+ }
180
193
  }
181
194
  throw e
182
195
  }
@@ -0,0 +1,36 @@
1
+ import { connect } from 'node:net'
2
+ import { PgClient } from './PgClient.js'
3
+
4
+ const CANCEL_REQUEST_CODE = 80877102
5
+ const CANCEL_REQUEST_TIMEOUT_MS = 5000
6
+
7
+ /**
8
+ * Asks the server to cancel the statement the client is running, with a protocol CancelRequest on a separate socket.
9
+ * Closing the client's own socket does not stop a statement that has not sent a row yet.
10
+ */
11
+ export const cancelRunningStatement = async ({ host, port, processID, secretKey }: PgClient): Promise<void> => {
12
+ if (processID === null || secretKey === null) {
13
+ return
14
+ }
15
+ const message = Buffer.alloc(16)
16
+ message.writeInt32BE(16, 0)
17
+ message.writeInt32BE(CANCEL_REQUEST_CODE, 4)
18
+ message.writeInt32BE(processID, 8)
19
+ message.writeInt32BE(secretKey, 12)
20
+
21
+ const socket = host.startsWith('/') ? connect(`${host}/.s.PGSQL.${port}`) : connect(port, host)
22
+ await new Promise<void>((resolve, reject) => {
23
+ socket.setTimeout(CANCEL_REQUEST_TIMEOUT_MS, () => {
24
+ socket.destroy(new Error(`PostgreSQL cancel request timed out after ${CANCEL_REQUEST_TIMEOUT_MS} ms`))
25
+ })
26
+ socket.once('error', reject)
27
+ socket.once('close', hadError => {
28
+ if (!hadError) {
29
+ resolve()
30
+ }
31
+ })
32
+ socket.once('connect', () => {
33
+ socket.end(message)
34
+ })
35
+ })
36
+ }
@@ -27,15 +27,19 @@ export class ClientError extends DatabaseError {
27
27
  }
28
28
  }
29
29
 
30
+ // PostgreSQL often puts the actionable part of an error (e.g. which objects block a DROP) into DETAIL and HINT.
31
+ const formatDiagnosticField = (label: string, value: unknown): string => typeof value === 'string' && value !== '' ? `\n${label}: ${value}` : ''
32
+
30
33
  export class QueryError extends DatabaseError {
31
34
  public readonly constraint?: string
32
35
  public readonly table?: string
33
36
 
34
37
  constructor(public readonly sql: string, public readonly parameters: any, public override readonly previous: Error | any) {
35
38
  super(
36
- `Database query error: ${'message' in previous && previous.message ? previous.message : JSON.stringify(previous)}
37
- SQL: ${sql}
38
- parameters: ${parameters}`,
39
+ ('message' in previous && previous.message
40
+ ? `Database query error: ${previous.message}` + formatDiagnosticField('Detail', previous.detail) + formatDiagnosticField('Hint', previous.hint)
41
+ : `Database query error: ${JSON.stringify(previous)}`)
42
+ + `\nSQL: ${sql}\nparameters: ${parameters}`,
39
43
  previous,
40
44
  )
41
45
  this.constraint = previous.constraint
@@ -49,6 +53,8 @@ export class ForeignKeyViolationError extends QueryError {}
49
53
 
50
54
  export class UniqueViolationError extends QueryError {}
51
55
 
56
+ export class CheckViolationError extends QueryError {}
57
+
52
58
  export class SerializationFailureError extends QueryError {}
53
59
 
54
60
  export class InvalidDataError extends QueryError {}
@@ -56,3 +62,9 @@ export class InvalidDataError extends QueryError {}
56
62
  export class TransactionAbortedError extends QueryError {}
57
63
 
58
64
  export class CannotCommitError extends DatabaseError {}
65
+
66
+ export class TerminatedConnectionError extends DatabaseError {
67
+ constructor() {
68
+ super('Database connection was terminated')
69
+ }
70
+ }
package/src/index.ts CHANGED
@@ -25,3 +25,4 @@ export {
25
25
  withDatabaseAdvisoryLock,
26
26
  wrapIdentifier,
27
27
  } from './utils/index.js'
28
+ export * from './client/RequestMemoryBudget.js'
package/src/types.ts CHANGED
@@ -25,4 +25,19 @@ export interface DatabaseConfig {
25
25
  readonly statementTimeoutMs?: number
26
26
  readonly lockTimeoutMs?: number
27
27
  readonly connectionTimeoutMs?: number
28
+ /**
29
+ * Enable TCP keep-alive on the connection socket (`pg`'s `keepAlive`).
30
+ * When a pooled connection is idle and the peer (a connection pooler, load
31
+ * balancer or NAT) silently drops it, the socket only surfaces as broken on
32
+ * the next use. With keep-alive the OS probes idle connections, so a dead one
33
+ * errors out and is discarded by the pool instead of being handed to a query.
34
+ * Defaults to `false` (pg default).
35
+ */
36
+ readonly keepAlive?: boolean
37
+ /**
38
+ * Idle time before the first TCP keep-alive probe, in milliseconds
39
+ * (`pg`'s `keepAliveInitialDelayMillis`). Only applies when `keepAlive` is
40
+ * enabled; the subsequent probe interval and count are controlled by the OS.
41
+ */
42
+ readonly keepAliveInitialDelayMs?: number
28
43
  }
@@ -5,14 +5,15 @@ import { PgClient } from '../client/PgClient.js'
5
5
  export type PgClientFactory = () => PgClient
6
6
  export const createPgClientFactory =
7
7
  ({ queryTimeoutMs, statementTimeoutMs, lockTimeoutMs, connectionTimeoutMs, ...config }: DatabaseConfig) => () => {
8
- // `lock_timeout` is supported by pg at runtime but missing from the installed @types/pg version,
9
- // so it is typed explicitly here.
10
- const clientConfig: pg.ClientConfig & { lock_timeout?: number } = {
8
+ const { keepAlive, keepAliveInitialDelayMs, ...connectionConfig } = config
9
+ const clientConfig: pg.ClientConfig = {
11
10
  query_timeout: queryTimeoutMs,
12
11
  statement_timeout: statementTimeoutMs,
13
12
  lock_timeout: lockTimeoutMs,
14
13
  connectionTimeoutMillis: connectionTimeoutMs,
15
- ...config,
14
+ keepAlive: keepAlive ?? false,
15
+ keepAliveInitialDelayMillis: keepAliveInitialDelayMs,
16
+ ...connectionConfig,
16
17
  }
17
18
  return new pg.Client(clientConfig)
18
19
  }