@vibeorm/adapter-pg 2.0.0-alpha.8 → 2.0.0
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/README.md +2 -2
- package/dist/errors.d.ts.map +1 -1
- package/dist/index.d.ts +19 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +331 -36
- package/dist/index.js.map +9 -7
- package/dist/savepoint-gate.d.ts +86 -0
- package/dist/savepoint-gate.d.ts.map +1 -0
- package/dist/statement-cache.d.ts +35 -9
- package/dist/statement-cache.d.ts.map +1 -1
- package/dist/transaction-budget.d.ts +144 -0
- package/dist/transaction-budget.d.ts.map +1 -0
- package/dist/transaction-sql.d.ts.map +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -5,10 +5,10 @@
|
|
|
5
5
|
This adapter runs VibeORM on [node-postgres](https://node-postgres.com/) (`pg`) against a PostgreSQL server. It works on both Bun and Node, and `pg` is a peer dependency you install yourself.
|
|
6
6
|
|
|
7
7
|
```bash
|
|
8
|
-
bun add @vibeorm/adapter-pg
|
|
8
|
+
bun add @vibeorm/adapter-pg pg
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
> **
|
|
11
|
+
> **Stable.** `2.0.0`, published under the `latest` dist-tag. The v1 line stays installable as `vibeorm@1`.
|
|
12
12
|
|
|
13
13
|
## Usage
|
|
14
14
|
|
package/dist/errors.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,SAAS,EAAE,KAAK,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAIhE;;;GAGG;AACH,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,SAAS,EAAE,KAAK,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAIhE;;;GAGG;AACH,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CA2B1E,CAAC;AAEH,4EAA4E;AAC5E,eAAO,MAAM,mBAAmB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAE/D,CAAC;AAYH;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE;IAAE,KAAK,EAAE,OAAO,CAAA;CAAE,GAAG,MAAM,GAAG,SAAS,CAK9E;AAID;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE;IAAE,KAAK,EAAE,OAAO,CAAA;CAAE,GAAG,SAAS,CA0BtE;AAED,wEAAwE;AACxE,wBAAsB,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAMnE"}
|
package/dist/index.d.ts
CHANGED
|
@@ -11,6 +11,16 @@ export type PgQueryConfig = {
|
|
|
11
11
|
readonly text: string;
|
|
12
12
|
readonly values?: unknown[];
|
|
13
13
|
readonly name?: string;
|
|
14
|
+
/**
|
|
15
|
+
* QUERY-LOCAL result parsers ({@link EXACT_TYPES}). node-postgres reads this
|
|
16
|
+
* off the query config, so nothing outside VibeORM's own statements is
|
|
17
|
+
* affected — a caller's pool keeps the driver's documented behaviour.
|
|
18
|
+
*/
|
|
19
|
+
readonly types?: PgTypeParsers;
|
|
20
|
+
};
|
|
21
|
+
/** The `pg-types` surface a query config may carry. */
|
|
22
|
+
export type PgTypeParsers = {
|
|
23
|
+
getTypeParser(oid: number, format?: "text" | "binary"): (value: string) => unknown;
|
|
14
24
|
};
|
|
15
25
|
/** The parts of a `pg` result this adapter reads. */
|
|
16
26
|
export type PgQueryResultLike = {
|
|
@@ -20,7 +30,13 @@ export type PgQueryResultLike = {
|
|
|
20
30
|
/** The parts of a `pg` PoolClient this adapter uses. */
|
|
21
31
|
export type PgPoolClientLike = {
|
|
22
32
|
query(config: PgQueryConfig): Promise<PgQueryResultLike>;
|
|
23
|
-
|
|
33
|
+
/**
|
|
34
|
+
* Hand the client back. A TRUTHY argument tells node-postgres to DESTROY it
|
|
35
|
+
* instead of pooling it — used when a rollback failed and the session state
|
|
36
|
+
* can no longer be asserted (EPIC 6). Optional so existing test doubles that
|
|
37
|
+
* declare `release(): void` still satisfy this type.
|
|
38
|
+
*/
|
|
39
|
+
release(destroy?: boolean): void;
|
|
24
40
|
/**
|
|
25
41
|
* EventEmitter surface. A real `pg.PoolClient` has it; test doubles need not,
|
|
26
42
|
* so both members are optional and the adapter feature-detects them.
|
|
@@ -93,4 +109,6 @@ export { createStatementNameCache } from "./statement-cache.ts";
|
|
|
93
109
|
export type { StatementNameCache } from "./statement-cache.ts";
|
|
94
110
|
export { ISOLATION_LEVEL_SQL, beginStatement, classifyRawTransactionControl, refuseNestedTransactionOptions, statementTimeoutStatement, } from "./transaction-sql.ts";
|
|
95
111
|
export type { RawTransactionControl } from "./transaction-sql.ts";
|
|
112
|
+
export { DEFAULT_DEADLINE_CLOCK, engineStatementBudgetMs, isTransactionDeadlineError, startTransactionBudget, transactionClosedError, transactionDeadlineError, transactionOutcomeUnknownError, validateTransactionDeadline, } from "./transaction-budget.ts";
|
|
113
|
+
export type { BudgetStage, DeadlineClock, TransactionBudget, TransactionOutcome } from "./transaction-budget.ts";
|
|
96
114
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"m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AE,MAAM,iBAAiB,CAAC;AACxD,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,YAAY,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EACL,mBAAmB,EACnB,cAAc,EACd,6BAA6B,EAC7B,8BAA8B,EAC9B,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAElE,OAAO,EACL,sBAAsB,EACtB,uBAAuB,EACvB,0BAA0B,EAC1B,sBAAsB,EACtB,sBAAsB,EACtB,wBAAwB,EACxB,8BAA8B,EAC9B,2BAA2B,GAC5B,MAAM,yBAAyB,CAAC;AACjC,YAAY,EAAE,WAAW,EAAE,aAAa,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -10,6 +10,7 @@ var PG_SQLSTATE_ERROR_CODES = Object.freeze({
|
|
|
10
10
|
"23502": "VIBE_VALIDATION",
|
|
11
11
|
"23514": "VIBE_VALIDATION",
|
|
12
12
|
"22P02": "VIBE_VALIDATION",
|
|
13
|
+
"42501": "VIBE_PERMISSION_DENIED",
|
|
13
14
|
"40001": "VIBE_TRANSACTION",
|
|
14
15
|
"40P01": "VIBE_TRANSACTION",
|
|
15
16
|
"57014": "VIBE_TRANSACTION"
|
|
@@ -93,6 +94,9 @@ function serializeParamsRaw(params) {
|
|
|
93
94
|
});
|
|
94
95
|
}
|
|
95
96
|
|
|
97
|
+
// packages/adapter-pg/src/savepoint-gate.ts
|
|
98
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
99
|
+
|
|
96
100
|
// packages/adapter-pg/src/savepoints.ts
|
|
97
101
|
function createSavepointCounter() {
|
|
98
102
|
return { n: 0 };
|
|
@@ -101,26 +105,123 @@ function nextSavepointName(params) {
|
|
|
101
105
|
return `vibeorm_sp_${params.counter.n++}`;
|
|
102
106
|
}
|
|
103
107
|
|
|
108
|
+
// packages/adapter-pg/src/savepoint-gate.ts
|
|
109
|
+
var CURRENT = new AsyncLocalStorage;
|
|
110
|
+
function createSavepointScope() {
|
|
111
|
+
return { depth: 0, state: { counter: createSavepointCounter(), open: null } };
|
|
112
|
+
}
|
|
113
|
+
function runRootScope(params) {
|
|
114
|
+
return CURRENT.run(params.scope, params.body);
|
|
115
|
+
}
|
|
116
|
+
function scopeTurn(params) {
|
|
117
|
+
const open = params.scope.state.open;
|
|
118
|
+
if (mayProceed({ scope: params.scope, open }))
|
|
119
|
+
return;
|
|
120
|
+
return waitForTurn({ scope: params.scope });
|
|
121
|
+
}
|
|
122
|
+
async function runNestedSavepoint(params) {
|
|
123
|
+
const { scope, execute, body } = params;
|
|
124
|
+
const node = await acquire({ scope });
|
|
125
|
+
try {
|
|
126
|
+
if (execute !== undefined)
|
|
127
|
+
await execute(`SAVEPOINT ${node.name}`);
|
|
128
|
+
let result;
|
|
129
|
+
try {
|
|
130
|
+
result = await CURRENT.run(node.scope, () => body(node.scope));
|
|
131
|
+
} catch (error) {
|
|
132
|
+
await drainDescendants({ node });
|
|
133
|
+
if (execute !== undefined) {
|
|
134
|
+
try {
|
|
135
|
+
await execute(`ROLLBACK TO SAVEPOINT ${node.name}`);
|
|
136
|
+
} catch {}
|
|
137
|
+
}
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
await drainDescendants({ node });
|
|
141
|
+
if (execute !== undefined)
|
|
142
|
+
await execute(`RELEASE SAVEPOINT ${node.name}`);
|
|
143
|
+
return result;
|
|
144
|
+
} finally {
|
|
145
|
+
closeNode({ node });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
function mayProceed(params) {
|
|
149
|
+
const { scope, open } = params;
|
|
150
|
+
if (open === null)
|
|
151
|
+
return true;
|
|
152
|
+
if (open.scope === scope)
|
|
153
|
+
return true;
|
|
154
|
+
if (open.scope.depth < scope.depth)
|
|
155
|
+
return true;
|
|
156
|
+
return CURRENT.getStore() === open.scope;
|
|
157
|
+
}
|
|
158
|
+
async function waitForTurn(params) {
|
|
159
|
+
for (;; ) {
|
|
160
|
+
const open = params.scope.state.open;
|
|
161
|
+
if (open === null || mayProceed({ scope: params.scope, open }))
|
|
162
|
+
return;
|
|
163
|
+
await open.settled;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
async function acquire(params) {
|
|
167
|
+
const { scope } = params;
|
|
168
|
+
for (;; ) {
|
|
169
|
+
const open = scope.state.open;
|
|
170
|
+
if (mayProceed({ scope, open }))
|
|
171
|
+
return pushNode({ scope, parent: open });
|
|
172
|
+
await open.settled;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
function pushNode(params) {
|
|
176
|
+
const { scope, parent } = params;
|
|
177
|
+
const state = scope.state;
|
|
178
|
+
let settle = () => {
|
|
179
|
+
return;
|
|
180
|
+
};
|
|
181
|
+
const settled = new Promise((resolve) => {
|
|
182
|
+
settle = () => resolve();
|
|
183
|
+
});
|
|
184
|
+
const node = {
|
|
185
|
+
scope: { depth: (parent === null ? 0 : parent.scope.depth) + 1, state },
|
|
186
|
+
name: nextSavepointName({ counter: state.counter }),
|
|
187
|
+
parent,
|
|
188
|
+
settled,
|
|
189
|
+
settle
|
|
190
|
+
};
|
|
191
|
+
state.open = node;
|
|
192
|
+
return node;
|
|
193
|
+
}
|
|
194
|
+
function closeNode(params) {
|
|
195
|
+
const { node } = params;
|
|
196
|
+
const state = node.scope.state;
|
|
197
|
+
if (state.open === node)
|
|
198
|
+
state.open = node.parent;
|
|
199
|
+
node.settle();
|
|
200
|
+
}
|
|
201
|
+
async function drainDescendants(params) {
|
|
202
|
+
const state = params.node.scope.state;
|
|
203
|
+
for (;; ) {
|
|
204
|
+
const open = state.open;
|
|
205
|
+
if (open === null || open === params.node || open.scope.depth <= params.node.scope.depth)
|
|
206
|
+
return;
|
|
207
|
+
await open.settled;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
104
211
|
// packages/adapter-pg/src/statement-cache.ts
|
|
105
212
|
function createStatementNameCache(params) {
|
|
106
|
-
const
|
|
213
|
+
const max = Math.max(0, params.max);
|
|
107
214
|
const names = new Map;
|
|
108
215
|
let counter = 0;
|
|
109
216
|
return {
|
|
110
217
|
getName(nameParams) {
|
|
111
218
|
const { text } = nameParams;
|
|
112
219
|
const existing = names.get(text);
|
|
113
|
-
if (existing !== undefined)
|
|
114
|
-
names.delete(text);
|
|
115
|
-
names.set(text, existing);
|
|
220
|
+
if (existing !== undefined)
|
|
116
221
|
return existing;
|
|
117
|
-
|
|
222
|
+
if (names.size >= max)
|
|
223
|
+
return;
|
|
118
224
|
const name = `vibeorm_${counter++}`;
|
|
119
|
-
if (names.size >= max) {
|
|
120
|
-
const oldest = names.keys().next().value;
|
|
121
|
-
if (oldest !== undefined)
|
|
122
|
-
names.delete(oldest);
|
|
123
|
-
}
|
|
124
225
|
names.set(text, name);
|
|
125
226
|
return name;
|
|
126
227
|
},
|
|
@@ -130,8 +231,127 @@ function createStatementNameCache(params) {
|
|
|
130
231
|
};
|
|
131
232
|
}
|
|
132
233
|
|
|
133
|
-
// packages/adapter-pg/src/transaction-
|
|
234
|
+
// packages/adapter-pg/src/transaction-budget.ts
|
|
134
235
|
import { VibeError as VibeError2 } from "@vibeorm/schema";
|
|
236
|
+
var DEFAULT_DEADLINE_CLOCK = () => Date.now();
|
|
237
|
+
function validateTransactionDeadline(params) {
|
|
238
|
+
const { options, support, provider } = params;
|
|
239
|
+
const deadline = options?.deadline;
|
|
240
|
+
if (deadline === undefined)
|
|
241
|
+
return;
|
|
242
|
+
if (support === "unsupported") {
|
|
243
|
+
throw new VibeError2({
|
|
244
|
+
code: "VIBE_UNSUPPORTED_CAPABILITY",
|
|
245
|
+
message: `${provider} cannot enforce a transaction deadline \u2014 remove the \`deadline\` option`,
|
|
246
|
+
meta: { provider, feature: "transactionDeadline", supported: support }
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
if (!Number.isInteger(deadline.totalMs) || deadline.totalMs <= 0) {
|
|
250
|
+
throw new VibeError2({
|
|
251
|
+
code: "VIBE_VALIDATION",
|
|
252
|
+
message: `transaction deadline \`totalMs\` must be a positive integer of milliseconds, received ${String(deadline.totalMs)}`,
|
|
253
|
+
meta: { provider, feature: "transactionDeadline", totalMs: deadline.totalMs }
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
const requested = deadline.enforcement ?? "between-statements";
|
|
257
|
+
if (requested === "cancel-running-statements" && support !== "cancel-running-statements") {
|
|
258
|
+
throw new VibeError2({
|
|
259
|
+
code: "VIBE_UNSUPPORTED_CAPABILITY",
|
|
260
|
+
message: `${provider} cannot cancel a statement that is already running, so the requested ` + "`cancel-running-statements` deadline guarantee is refused rather than silently downgraded \u2014 " + 'ask for "between-statements" if a budget checked between statements is enough',
|
|
261
|
+
meta: { provider, feature: "transactionDeadline", requested, supported: support }
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
function startTransactionBudget(params) {
|
|
266
|
+
const { options, provider } = params;
|
|
267
|
+
const clock = params.clock ?? DEFAULT_DEADLINE_CLOCK;
|
|
268
|
+
const deadline = options?.deadline;
|
|
269
|
+
const totalMs = deadline === undefined ? null : deadline.totalMs;
|
|
270
|
+
const enforcement = deadline === undefined ? null : deadline.enforcement ?? "between-statements";
|
|
271
|
+
const expiresAt = totalMs === null ? null : clock() + totalMs;
|
|
272
|
+
let outcome = null;
|
|
273
|
+
const budget = {
|
|
274
|
+
enforcement,
|
|
275
|
+
totalMs,
|
|
276
|
+
statementTimeoutMs: options?.timeout ?? null,
|
|
277
|
+
remainingMs() {
|
|
278
|
+
return expiresAt === null ? null : Math.max(0, expiresAt - clock());
|
|
279
|
+
},
|
|
280
|
+
expired() {
|
|
281
|
+
return expiresAt !== null && clock() >= expiresAt;
|
|
282
|
+
},
|
|
283
|
+
assertUsable(assertParams) {
|
|
284
|
+
if (outcome !== null) {
|
|
285
|
+
throw transactionClosedError({ provider, outcome, stage: assertParams.stage });
|
|
286
|
+
}
|
|
287
|
+
if (expiresAt !== null && clock() >= expiresAt) {
|
|
288
|
+
throw transactionDeadlineError({
|
|
289
|
+
provider,
|
|
290
|
+
stage: assertParams.stage,
|
|
291
|
+
totalMs,
|
|
292
|
+
overdueMs: clock() - expiresAt
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
},
|
|
296
|
+
close(closeParams) {
|
|
297
|
+
if (outcome === null)
|
|
298
|
+
outcome = closeParams.outcome;
|
|
299
|
+
},
|
|
300
|
+
get outcome() {
|
|
301
|
+
return outcome;
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
return budget;
|
|
305
|
+
}
|
|
306
|
+
function engineStatementBudgetMs(params) {
|
|
307
|
+
const { budget } = params;
|
|
308
|
+
if (budget.enforcement !== "cancel-running-statements")
|
|
309
|
+
return null;
|
|
310
|
+
const remaining = budget.remainingMs();
|
|
311
|
+
if (remaining === null)
|
|
312
|
+
return null;
|
|
313
|
+
const totalBound = Math.max(1, Math.ceil(remaining));
|
|
314
|
+
return budget.statementTimeoutMs !== null && budget.statementTimeoutMs > 0 ? Math.min(totalBound, budget.statementTimeoutMs) : totalBound;
|
|
315
|
+
}
|
|
316
|
+
function transactionDeadlineError(params) {
|
|
317
|
+
const { provider, stage, totalMs, overdueMs } = params;
|
|
318
|
+
const what = stage === "commit" ? "the transaction was rolled back instead of committed" : "the statement was never sent and the transaction is being rolled back";
|
|
319
|
+
return new VibeError2({
|
|
320
|
+
code: "VIBE_TRANSACTION",
|
|
321
|
+
message: `transaction deadline of ${totalMs} ms expired ${Math.max(0, Math.round(overdueMs))} ms ago \u2014 ${what}. ` + "Nothing is retried automatically: work the callback did outside the database may already have happened.",
|
|
322
|
+
meta: { provider, reason: "transaction-deadline", stage, totalMs, overdueMs: Math.max(0, Math.round(overdueMs)) }
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
function transactionClosedError(params) {
|
|
326
|
+
const { provider, outcome, stage } = params;
|
|
327
|
+
return new VibeError2({
|
|
328
|
+
code: "VIBE_TRANSACTION",
|
|
329
|
+
message: `this transaction has already finished (${outcome}), so its client can no longer be used \u2014 ` + "a handle kept past the end of `$transaction` would run outside the transaction, on a connection " + "that now belongs to someone else",
|
|
330
|
+
meta: { provider, reason: "transaction-closed", outcome, stage }
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
function transactionOutcomeUnknownError(params) {
|
|
334
|
+
const { provider, totalMs, cause } = params;
|
|
335
|
+
return new VibeError2({
|
|
336
|
+
code: "VIBE_TRANSACTION",
|
|
337
|
+
message: `transaction deadline of ${totalMs} ms expired and the rollback that should have cleaned up failed \u2014 ` + "the commit state of this transaction is UNKNOWN. It is not retried automatically; inspect the data " + "before deciding.",
|
|
338
|
+
meta: {
|
|
339
|
+
provider,
|
|
340
|
+
reason: "transaction-outcome-unknown",
|
|
341
|
+
outcome: "unknown",
|
|
342
|
+
totalMs,
|
|
343
|
+
rollbackFailed: true
|
|
344
|
+
},
|
|
345
|
+
cause
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
function isTransactionDeadlineError(error) {
|
|
349
|
+
const reason = error?.meta?.reason;
|
|
350
|
+
return reason === "transaction-deadline";
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// packages/adapter-pg/src/transaction-sql.ts
|
|
354
|
+
import { VibeError as VibeError3 } from "@vibeorm/schema";
|
|
135
355
|
var ISOLATION_LEVEL_SQL = Object.freeze({
|
|
136
356
|
ReadCommitted: "READ COMMITTED",
|
|
137
357
|
RepeatableRead: "REPEATABLE READ",
|
|
@@ -144,7 +364,7 @@ function beginStatement(params) {
|
|
|
144
364
|
function statementTimeoutStatement(params) {
|
|
145
365
|
const { timeout } = params;
|
|
146
366
|
if (!Number.isInteger(timeout) || timeout < 0) {
|
|
147
|
-
throw new
|
|
367
|
+
throw new VibeError3({
|
|
148
368
|
code: "VIBE_VALIDATION",
|
|
149
369
|
message: `transaction timeout must be a non-negative integer of milliseconds, received ${String(timeout)}`,
|
|
150
370
|
meta: { timeout }
|
|
@@ -170,6 +390,8 @@ function refuseNestedTransactionOptions(params) {
|
|
|
170
390
|
passed.push("isolationLevel");
|
|
171
391
|
if (options.timeout !== undefined)
|
|
172
392
|
passed.push("timeout");
|
|
393
|
+
if (options.deadline !== undefined)
|
|
394
|
+
passed.push("deadline");
|
|
173
395
|
if (passed.length === 0)
|
|
174
396
|
return;
|
|
175
397
|
const meta = { provider, nested: true };
|
|
@@ -177,14 +399,17 @@ function refuseNestedTransactionOptions(params) {
|
|
|
177
399
|
meta.isolationLevel = options.isolationLevel;
|
|
178
400
|
if (options.timeout !== undefined)
|
|
179
401
|
meta.timeout = options.timeout;
|
|
180
|
-
|
|
402
|
+
if (options.deadline !== undefined)
|
|
403
|
+
meta.deadline = options.deadline;
|
|
404
|
+
throw new VibeError3({
|
|
181
405
|
code: "VIBE_VALIDATION",
|
|
182
|
-
message: `nested transactions run as savepoints and cannot honor ${passed.join(" or ")} \u2014 a savepoint cannot change the isolation level of the transaction it joins,
|
|
406
|
+
message: `nested transactions run as savepoints and cannot honor ${passed.join(" or ")} \u2014 a savepoint cannot change the isolation level of the transaction it joins, a nested timeout is not enforceable, and a nested deadline would need its own session setting on a connection it does not own (it inherits the top-level one instead); pass options on the top-level $transaction`,
|
|
183
407
|
meta
|
|
184
408
|
});
|
|
185
409
|
}
|
|
186
410
|
|
|
187
411
|
// packages/adapter-pg/src/index.ts
|
|
412
|
+
var POOL_STATEMENT_NAMES = new WeakMap;
|
|
188
413
|
function guardBackgroundErrors(params) {
|
|
189
414
|
const { client } = params;
|
|
190
415
|
if (typeof client.on !== "function")
|
|
@@ -200,9 +425,25 @@ function guardBackgroundErrors(params) {
|
|
|
200
425
|
var DIALECT = "postgres";
|
|
201
426
|
var PROVIDER = "postgresql";
|
|
202
427
|
var WIRE = Object.freeze({ dateTime: "native", json: "parsed", numbers: "native" });
|
|
428
|
+
var BUDGETS = Object.freeze({
|
|
429
|
+
acquireTimeout: true,
|
|
430
|
+
statementTimeout: "all-statements",
|
|
431
|
+
transactionDeadline: "cancel-running-statements"
|
|
432
|
+
});
|
|
433
|
+
var NUMERIC_ARRAY_OID = 1231;
|
|
434
|
+
var TEXT_ARRAY_OID = 1009;
|
|
435
|
+
var EXACT_TYPES = {
|
|
436
|
+
getTypeParser(oid, format) {
|
|
437
|
+
if (oid === NUMERIC_ARRAY_OID && (format === undefined || format === "text")) {
|
|
438
|
+
return driverTypeParser(TEXT_ARRAY_OID, "text");
|
|
439
|
+
}
|
|
440
|
+
return driverTypeParser(oid, format);
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
var driverTypeParser = pg.types.getTypeParser;
|
|
203
444
|
function pgAdapter(options) {
|
|
204
445
|
const usePrepared = options?.preparedStatements ?? false;
|
|
205
|
-
const
|
|
446
|
+
const stmtCacheMax = options?.stmtCacheMax ?? 1000;
|
|
206
447
|
let pool = null;
|
|
207
448
|
let ownsPool = false;
|
|
208
449
|
let rawSession = null;
|
|
@@ -231,9 +472,20 @@ function pgAdapter(options) {
|
|
|
231
472
|
ownsPool = true;
|
|
232
473
|
return pool;
|
|
233
474
|
}
|
|
475
|
+
function statementNamesFor(params) {
|
|
476
|
+
const existing = POOL_STATEMENT_NAMES.get(params.pool);
|
|
477
|
+
if (existing !== undefined)
|
|
478
|
+
return existing;
|
|
479
|
+
const created = createStatementNameCache({ max: stmtCacheMax });
|
|
480
|
+
POOL_STATEMENT_NAMES.set(params.pool, created);
|
|
481
|
+
return created;
|
|
482
|
+
}
|
|
234
483
|
function buildQueryConfig(params) {
|
|
235
484
|
const values = serializeParams({ values: params.values });
|
|
236
|
-
|
|
485
|
+
if (!usePrepared)
|
|
486
|
+
return { text: params.text, values, types: EXACT_TYPES };
|
|
487
|
+
const name = statementNamesFor({ pool: getPool() }).getName({ text: params.text });
|
|
488
|
+
return name === undefined ? { text: params.text, values, types: EXACT_TYPES } : { name, text: params.text, values, types: EXACT_TYPES };
|
|
237
489
|
}
|
|
238
490
|
async function runExecute(params) {
|
|
239
491
|
const config = buildQueryConfig({ text: params.text, values: params.values });
|
|
@@ -242,35 +494,46 @@ function pgAdapter(options) {
|
|
|
242
494
|
}
|
|
243
495
|
async function runExecuteUnsafe(params) {
|
|
244
496
|
const values = params.values === undefined ? undefined : serializeParamsRaw({ values: params.values });
|
|
245
|
-
const result = await runMapped(() => params.queryable.query({ text: params.text, values }));
|
|
497
|
+
const result = await runMapped(() => params.queryable.query({ text: params.text, values, types: EXACT_TYPES }));
|
|
246
498
|
return { rows: result.rows, affectedRows: result.rowCount ?? 0 };
|
|
247
499
|
}
|
|
248
500
|
function createClientAdapter(params) {
|
|
249
|
-
const { client,
|
|
501
|
+
const { client, scope, budget } = params;
|
|
502
|
+
async function applyEngineBudget() {
|
|
503
|
+
const ms = engineStatementBudgetMs({ budget });
|
|
504
|
+
if (ms === null)
|
|
505
|
+
return;
|
|
506
|
+
await runMapped(() => client.query({ text: statementTimeoutStatement({ timeout: ms }) }));
|
|
507
|
+
}
|
|
250
508
|
return {
|
|
251
509
|
dialect: DIALECT,
|
|
252
510
|
provider: PROVIDER,
|
|
253
511
|
wire: WIRE,
|
|
512
|
+
budgets: BUDGETS,
|
|
254
513
|
async execute(execParams) {
|
|
514
|
+
const turn = scopeTurn({ scope });
|
|
515
|
+
if (turn !== undefined)
|
|
516
|
+
await turn;
|
|
517
|
+
budget.assertUsable({ stage: "statement" });
|
|
518
|
+
await applyEngineBudget();
|
|
255
519
|
return runExecute({ queryable: client, ...execParams });
|
|
256
520
|
},
|
|
257
521
|
async executeUnsafe(execParams) {
|
|
522
|
+
const turn = scopeTurn({ scope });
|
|
523
|
+
if (turn !== undefined)
|
|
524
|
+
await turn;
|
|
525
|
+
budget.assertUsable({ stage: "statement" });
|
|
526
|
+
await applyEngineBudget();
|
|
258
527
|
return runExecuteUnsafe({ queryable: client, ...execParams });
|
|
259
528
|
},
|
|
260
529
|
async transaction(fn, nestedOptions) {
|
|
261
530
|
refuseNestedTransactionOptions({ options: nestedOptions, provider: PROVIDER });
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
} catch (error) {
|
|
269
|
-
try {
|
|
270
|
-
await client.query({ text: `ROLLBACK TO SAVEPOINT ${savepoint}` });
|
|
271
|
-
} catch {}
|
|
272
|
-
throw error;
|
|
273
|
-
}
|
|
531
|
+
budget.assertUsable({ stage: "nested" });
|
|
532
|
+
return runNestedSavepoint({
|
|
533
|
+
scope,
|
|
534
|
+
execute: (statement) => runMapped(() => client.query({ text: statement })),
|
|
535
|
+
body: (child) => fn(createClientAdapter({ client, scope: child, budget }))
|
|
536
|
+
});
|
|
274
537
|
},
|
|
275
538
|
async connect() {},
|
|
276
539
|
async disconnect() {},
|
|
@@ -283,6 +546,7 @@ function pgAdapter(options) {
|
|
|
283
546
|
dialect: DIALECT,
|
|
284
547
|
provider: PROVIDER,
|
|
285
548
|
wire: WIRE,
|
|
549
|
+
budgets: BUDGETS,
|
|
286
550
|
async execute(params) {
|
|
287
551
|
return runExecute({ queryable: getPool(), ...params });
|
|
288
552
|
},
|
|
@@ -320,26 +584,49 @@ function pgAdapter(options) {
|
|
|
320
584
|
return runExecuteUnsafe({ queryable: getPool(), ...params });
|
|
321
585
|
},
|
|
322
586
|
async transaction(fn, transactionOptions) {
|
|
587
|
+
validateTransactionDeadline({
|
|
588
|
+
options: transactionOptions,
|
|
589
|
+
support: BUDGETS.transactionDeadline,
|
|
590
|
+
provider: PROVIDER
|
|
591
|
+
});
|
|
323
592
|
const client = await runMapped(() => getPool().connect());
|
|
324
593
|
const unguard = guardBackgroundErrors({ client });
|
|
325
|
-
const
|
|
594
|
+
const scope = createSavepointScope();
|
|
595
|
+
const budget = startTransactionBudget({ options: transactionOptions, provider: PROVIDER });
|
|
596
|
+
let discard = false;
|
|
326
597
|
try {
|
|
327
598
|
await runMapped(() => client.query({ text: beginStatement({ isolationLevel: transactionOptions?.isolationLevel }) }));
|
|
328
599
|
if (transactionOptions?.timeout !== undefined) {
|
|
329
600
|
const text = statementTimeoutStatement({ timeout: transactionOptions.timeout });
|
|
330
601
|
await runMapped(() => client.query({ text }));
|
|
331
602
|
}
|
|
332
|
-
const result = await
|
|
603
|
+
const result = await runRootScope({
|
|
604
|
+
scope,
|
|
605
|
+
body: () => fn(createClientAdapter({ client, scope, budget }))
|
|
606
|
+
});
|
|
607
|
+
budget.assertUsable({ stage: "commit" });
|
|
333
608
|
await runMapped(() => client.query({ text: "COMMIT" }));
|
|
609
|
+
budget.close({ outcome: "committed" });
|
|
334
610
|
return result;
|
|
335
611
|
} catch (error) {
|
|
336
612
|
try {
|
|
337
613
|
await client.query({ text: "ROLLBACK" });
|
|
338
|
-
|
|
614
|
+
budget.close({ outcome: "rolled-back" });
|
|
615
|
+
} catch {
|
|
616
|
+
discard = true;
|
|
617
|
+
budget.close({ outcome: "unknown" });
|
|
618
|
+
if (budget.totalMs !== null && isTransactionDeadlineError(error)) {
|
|
619
|
+
throw transactionOutcomeUnknownError({
|
|
620
|
+
provider: PROVIDER,
|
|
621
|
+
totalMs: budget.totalMs,
|
|
622
|
+
cause: error
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
}
|
|
339
626
|
throw error;
|
|
340
627
|
} finally {
|
|
341
628
|
unguard();
|
|
342
|
-
client.release();
|
|
629
|
+
client.release(discard);
|
|
343
630
|
}
|
|
344
631
|
},
|
|
345
632
|
async connect() {
|
|
@@ -370,7 +657,12 @@ function pgAdapter(options) {
|
|
|
370
657
|
};
|
|
371
658
|
}
|
|
372
659
|
export {
|
|
660
|
+
validateTransactionDeadline,
|
|
661
|
+
transactionOutcomeUnknownError,
|
|
662
|
+
transactionDeadlineError,
|
|
663
|
+
transactionClosedError,
|
|
373
664
|
statementTimeoutStatement,
|
|
665
|
+
startTransactionBudget,
|
|
374
666
|
serializeParamsRaw,
|
|
375
667
|
serializeParams,
|
|
376
668
|
refuseNestedTransactionOptions,
|
|
@@ -378,6 +670,8 @@ export {
|
|
|
378
670
|
pgAdapter,
|
|
379
671
|
nextSavepointName,
|
|
380
672
|
mapPgDriverError,
|
|
673
|
+
isTransactionDeadlineError,
|
|
674
|
+
engineStatementBudgetMs,
|
|
381
675
|
createStatementNameCache,
|
|
382
676
|
createSavepointCounter,
|
|
383
677
|
classifyRawTransactionControl,
|
|
@@ -385,7 +679,8 @@ export {
|
|
|
385
679
|
PgArrayParam,
|
|
386
680
|
PG_SQLSTATE_REASONS,
|
|
387
681
|
PG_SQLSTATE_ERROR_CODES,
|
|
388
|
-
ISOLATION_LEVEL_SQL
|
|
682
|
+
ISOLATION_LEVEL_SQL,
|
|
683
|
+
DEFAULT_DEADLINE_CLOCK
|
|
389
684
|
};
|
|
390
685
|
|
|
391
|
-
//# debugId=
|
|
686
|
+
//# debugId=17E44C1AF7E3C0D164756E2164756E21
|
package/dist/index.js.map
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/index.ts", "../src/errors.ts", "../src/params.ts", "../src/savepoints.ts", "../src/statement-cache.ts", "../src/transaction-sql.ts"],
|
|
3
|
+
"sources": ["../src/index.ts", "../src/errors.ts", "../src/params.ts", "../src/savepoint-gate.ts", "../src/savepoints.ts", "../src/statement-cache.ts", "../src/transaction-budget.ts", "../src/transaction-sql.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n * @vibeorm/adapter-pg — node-postgres (`pg`) adapter for VibeORM v2.\n *\n * Runs on Bun and Node. Owns pooling, optional named prepared statements,\n * transactions (nested → savepoints on the same client) and driver-error\n * mapping. Only `VibeError` ever escapes.\n */\n\nimport type { DatabaseAdapter, QueryResult, TransactionOptions, WireFidelity } from \"@vibeorm/runtime\";\nimport type { Dialect, Provider } from \"@vibeorm/schema\";\nimport pg from \"pg\";\nimport { mapPgDriverError, runMapped } from \"./errors.ts\";\nimport { PgArrayParam, serializeParams, serializeParamsRaw } from \"./params.ts\";\nimport { createSavepointCounter, nextSavepointName, type SavepointCounter } from \"./savepoints.ts\";\nimport { createStatementNameCache } from \"./statement-cache.ts\";\nimport {\n beginStatement,\n classifyRawTransactionControl,\n refuseNestedTransactionOptions,\n statementTimeoutStatement,\n} from \"./transaction-sql.ts\";\n\n// ─── Minimal pg surface ───────────────────────────────────────────\n\n/** The single `pg` query form this adapter uses (config object, never overloads). */\nexport type PgQueryConfig = {\n readonly text: string;\n readonly values?: unknown[];\n readonly name?: string;\n};\n\n/** The parts of a `pg` result this adapter reads. */\nexport type PgQueryResultLike = {\n readonly rows: Record<string, unknown>[];\n readonly rowCount: number | null;\n};\n\n/** The parts of a `pg` PoolClient this adapter uses. */\nexport type PgPoolClientLike = {\n query(config: PgQueryConfig): Promise<PgQueryResultLike>;\n release(): void;\n /**\n * EventEmitter surface. A real `pg.PoolClient` has it; test doubles need not,\n * so both members are optional and the adapter feature-detects them.\n */\n on?(event: \"error\", listener: (error: unknown) => void): void;\n removeListener?(event: \"error\", listener: (error: unknown) => void): void;\n};\n\n/** The parts of a `pg` Pool this adapter uses — satisfied by a real `pg.Pool`. */\nexport type PgPoolLike = {\n connect(): Promise<PgPoolClientLike>;\n query(config: PgQueryConfig): Promise<PgQueryResultLike>;\n end(): Promise<void>;\n /** EventEmitter surface; optional for the same reason as on {@link PgPoolClientLike}. */\n on?(event: \"error\", listener: (error: unknown, client: PgPoolClientLike) => void): void;\n};\n\n/** Anything that can run a query: the pool itself or a checked-out client. */\ntype Queryable = { query(config: PgQueryConfig): Promise<PgQueryResultLike> };\n\n/**\n * Keep a CHECKED-OUT client's background failures from killing the process,\n * returning the detach to run before the client goes back to the pool.\n *\n * node-postgres listens for `'error'` on a pooled client only while that client\n * sits IDLE, and removes the listener the moment the client is checked out\n * (restoring it on release). A client this adapter holds — for a transaction,\n * or as a pinned raw session — therefore has NO listener, so a backend that\n * dies mid-transaction reaches `client.emit('error', …)` with none. An\n * `'error'` event without a listener is an uncaught exception: fatal under\n * Node, which turns a database failover into a dead application process.\n *\n * The listener deliberately does nothing with the error and is NOT an error\n * channel: the in-flight query already rejects on its own with the mapped\n * `VibeError`, and the pool discards the broken client. Its only job is to keep\n * the process alive. Detaching before `release()` matters just as much — a\n * listener left attached would shadow pg's own idle listener and stop the pool\n * evicting a client that fails later, while idle.\n */\nfunction guardBackgroundErrors(params: { client: PgPoolClientLike }): () => void {\n const { client } = params;\n if (typeof client.on !== \"function\") return (): void => undefined;\n const swallow = (): void => {\n /* the failing call rejects with a mapped VibeError; nothing to report here */\n };\n client.on(\"error\", swallow);\n return (): void => {\n client.removeListener?.(\"error\", swallow);\n };\n}\n\n// ─── Options ──────────────────────────────────────────────────────\n\n/**\n * Options for {@link pgAdapter}. Either point it at a connection string (the\n * adapter then owns the pool it creates) or hand it a pool you already own.\n */\nexport type PgAdapterOptions = {\n /** PostgreSQL connection URL. Defaults to `process.env.DATABASE_URL`. */\n readonly connectionString?: string;\n /**\n * An existing `pg.Pool` to use instead of creating one. The adapter never\n * ends a pool it did not create, so `disconnect()` is a no-op in this mode.\n */\n readonly pool?: PgPoolLike;\n /** Maximum pooled connections (default 10). Ignored when `pool` is given. */\n readonly max?: number;\n /**\n * Pool-wide `statement_timeout` in milliseconds. Every connection inherits\n * it; a per-transaction `timeout` overrides it for that transaction.\n */\n readonly statementTimeout?: number;\n /** Milliseconds to wait for a pool checkout before failing (pg's `connectionTimeoutMillis`). */\n readonly connectionTimeout?: number;\n /**\n * Send ORM-path queries as named prepared statements (default false).\n * Named statements save planning time but let PostgreSQL fall back to a\n * generic plan after ~5 executions, which can pick worse indexes for range\n * filters — leave off unless profiling says otherwise.\n */\n readonly preparedStatements?: boolean;\n /** Maximum entries in the prepared-statement name cache (default 1000, LRU). */\n readonly stmtCacheMax?: number;\n};\n\n// ─── Adapter ──────────────────────────────────────────────────────\n\nconst DIALECT: Dialect = \"postgres\";\nconst PROVIDER: Provider = \"postgresql\";\n\n/**\n * node-postgres wire (board #30, live-verified on both execute paths):\n * timestamptz → `Date`, json/jsonb → parsed values, int4/float8 → numbers.\n * (int8 stays a string — BigInt decoding is real work and never pruned.)\n */\nconst WIRE: WireFidelity = Object.freeze({ dateTime: \"native\", json: \"parsed\", numbers: \"native\" } as const);\n\n/**\n * Create a VibeORM adapter backed by node-postgres.\n *\n * @example\n * ```ts\n * const adapter = pgAdapter({ connectionString: process.env.DATABASE_URL, max: 20 });\n * await adapter.connect();\n * const rows = await adapter.execute({ text: 'SELECT * FROM \"User\" WHERE \"id\" = $1', values: [1] });\n * ```\n *\n * @example Reusing a pool you already own\n * ```ts\n * import pg from \"pg\";\n * const pool = new pg.Pool({ connectionString });\n * const adapter = pgAdapter({ pool });\n * ```\n */\nexport function pgAdapter(options?: PgAdapterOptions): DatabaseAdapter {\n const usePrepared = options?.preparedStatements ?? false;\n const statementNames = createStatementNameCache({ max: options?.stmtCacheMax ?? 1000 });\n\n let pool: PgPoolLike | null = null;\n let ownsPool = false;\n\n /**\n * The checked-out client of an OPEN raw transaction — session affinity for\n * the raw path. @vibeorm/migrate wraps transactional DDL in literal `BEGIN`\n * / `COMMIT` / `ROLLBACK` sent through `executeUnsafe`; without pinning,\n * `pool.query(\"BEGIN\")` sequences stay on one client only by LIFO checkout\n * luck, and any concurrent traffic silently splits the transaction across\n * connections. A pure `BEGIN` checks a client out, every raw statement until\n * the matching `COMMIT`/`ROLLBACK` rides it, and the close releases it. The\n * ORM path (`execute`) and `transaction()` stay on the pool. Concurrent raw\n * transactions on one adapter are unsupported.\n */\n let rawSession: PgPoolClientLike | null = null;\n /** Detach for {@link rawSession}'s background-error guard; runs before its release. */\n let rawSessionUnguard: (() => void) | null = null;\n\n function getPool(): PgPoolLike {\n if (pool !== null) return pool;\n\n if (options?.pool !== undefined) {\n pool = options.pool;\n ownsPool = false;\n return pool;\n }\n\n const config: Record<string, unknown> = {\n connectionString: options?.connectionString ?? process.env.DATABASE_URL,\n max: options?.max ?? 10,\n };\n if (options?.statementTimeout !== undefined) {\n config.statement_timeout = options.statementTimeout;\n }\n if (options?.connectionTimeout !== undefined) {\n config.connectionTimeoutMillis = options.connectionTimeout;\n }\n\n const PoolCtor = pg.Pool as unknown as new (poolConfig: Record<string, unknown>) => PgPoolLike;\n pool = new PoolCtor(config);\n /**\n * The IDLE half of the same hazard {@link guardBackgroundErrors} covers: a\n * pooled client that loses its socket while idle makes pg re-emit on the\n * POOL, and an unhandled `'error'` there is equally fatal. The pool already\n * evicts that client, so this listener only keeps the process alive.\n *\n * Attached ONLY to a pool this adapter constructed. A caller-supplied pool\n * (the `pool` option) has its own owner: the adapter never ends it either,\n * node-postgres documents attaching an `'error'` listener as that owner's\n * job, and registering one here that is never removed would stack up a\n * listener per adapter sharing that pool. The dangerous case — a client\n * checked out for a transaction or a raw session, which pg leaves\n * unlistened by construction — is guarded in BOTH modes.\n */\n pool.on?.(\"error\", () => {\n /* the pool has already discarded the failed client */\n });\n ownsPool = true;\n return pool;\n }\n\n /** Build the config for one ORM-path query (statement name only when enabled). */\n function buildQueryConfig(params: { text: string; values: unknown[] }): PgQueryConfig {\n const values = serializeParams({ values: params.values });\n return usePrepared\n ? { name: statementNames.getName({ text: params.text }), text: params.text, values }\n : { text: params.text, values };\n }\n\n async function runExecute(params: {\n queryable: Queryable;\n text: string;\n values: unknown[];\n }): Promise<Record<string, unknown>[]> {\n const config = buildQueryConfig({ text: params.text, values: params.values });\n const result = await runMapped(() => params.queryable.query(config));\n return result.rows;\n }\n\n async function runExecuteUnsafe(params: {\n queryable: Queryable;\n text: string;\n values?: unknown[];\n }): Promise<QueryResult> {\n const values = params.values === undefined ? undefined : serializeParamsRaw({ values: params.values });\n const result = await runMapped(() => params.queryable.query({ text: params.text, values }));\n return { rows: result.rows, affectedRows: result.rowCount ?? 0 };\n }\n\n /**\n * Adapter bound to one checked-out client that is already inside a\n * transaction. Nested `transaction()` calls open savepoints on that same\n * client, naming them from the counter shared across the whole top-level\n * transaction so siblings never collide.\n */\n function createClientAdapter(params: {\n client: PgPoolClientLike;\n savepointCounter: SavepointCounter;\n }): DatabaseAdapter {\n const { client, savepointCounter } = params;\n\n return {\n dialect: DIALECT,\n provider: PROVIDER,\n wire: WIRE,\n\n async execute(execParams) {\n return runExecute({ queryable: client, ...execParams });\n },\n\n async executeUnsafe(execParams) {\n return runExecuteUnsafe({ queryable: client, ...execParams });\n },\n\n async transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n nestedOptions?: TransactionOptions,\n ): Promise<T> {\n refuseNestedTransactionOptions({ options: nestedOptions, provider: PROVIDER });\n const savepoint = nextSavepointName({ counter: savepointCounter });\n await runMapped(() => client.query({ text: `SAVEPOINT ${savepoint}` }));\n try {\n const result = await fn(createClientAdapter({ client, savepointCounter }));\n await runMapped(() => client.query({ text: `RELEASE SAVEPOINT ${savepoint}` }));\n return result;\n } catch (error) {\n // Best effort: never mask the original failure with a rollback failure.\n try {\n await client.query({ text: `ROLLBACK TO SAVEPOINT ${savepoint}` });\n } catch {\n /* rollback is best-effort */\n }\n throw error;\n }\n },\n\n async connect(): Promise<void> {\n // Already connected — this adapter is bound to a live client.\n },\n\n async disconnect(): Promise<void> {\n // The pool owns the connection lifecycle; releasing happens at the\n // top-level transaction boundary.\n },\n\n formatArrayParam(values: unknown[]): unknown {\n return new PgArrayParam(values);\n },\n };\n }\n\n return {\n dialect: DIALECT,\n provider: PROVIDER,\n wire: WIRE,\n\n async execute(params) {\n return runExecute({ queryable: getPool(), ...params });\n },\n\n async executeUnsafe(params) {\n const control = classifyRawTransactionControl({ text: params.text });\n if (rawSession !== null) {\n if (control === \"close\") {\n const session = rawSession;\n const unguard = rawSessionUnguard;\n rawSession = null;\n rawSessionUnguard = null;\n try {\n return await runExecuteUnsafe({ queryable: session, ...params });\n } finally {\n unguard?.();\n session.release();\n }\n }\n // A nested raw BEGIN lands here too — postgres treats it as a warning\n // no-op on the open session, exactly like a single connection would.\n return runExecuteUnsafe({ queryable: rawSession, ...params });\n }\n if (control === \"open\") {\n const client = await runMapped(() => getPool().connect());\n const unguard = guardBackgroundErrors({ client });\n try {\n const result = await runExecuteUnsafe({ queryable: client, ...params });\n rawSession = client;\n rawSessionUnguard = unguard;\n return result;\n } catch (error) {\n unguard();\n client.release();\n throw error;\n }\n }\n return runExecuteUnsafe({ queryable: getPool(), ...params });\n },\n\n async transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n transactionOptions?: TransactionOptions,\n ): Promise<T> {\n const client = await runMapped(() => getPool().connect());\n const unguard = guardBackgroundErrors({ client });\n const savepointCounter = createSavepointCounter();\n try {\n await runMapped(() =>\n client.query({ text: beginStatement({ isolationLevel: transactionOptions?.isolationLevel }) }),\n );\n if (transactionOptions?.timeout !== undefined) {\n const text = statementTimeoutStatement({ timeout: transactionOptions.timeout });\n await runMapped(() => client.query({ text }));\n }\n const result = await fn(createClientAdapter({ client, savepointCounter }));\n await runMapped(() => client.query({ text: \"COMMIT\" }));\n return result;\n } catch (error) {\n try {\n await client.query({ text: \"ROLLBACK\" });\n } catch {\n /* rollback is best-effort */\n }\n throw error;\n } finally {\n unguard();\n client.release();\n }\n },\n\n async connect(): Promise<void> {\n const client = await runMapped(() => getPool().connect());\n client.release();\n },\n\n async disconnect(): Promise<void> {\n if (rawSession !== null) {\n // An abandoned raw transaction must not leak an in-transaction client;\n // roll it back best-effort before the pool ends.\n const session = rawSession;\n const unguard = rawSessionUnguard;\n rawSession = null;\n rawSessionUnguard = null;\n try {\n await session.query({ text: \"ROLLBACK\" });\n } catch {\n /* the pool is closing; the session is going away regardless */\n }\n unguard?.();\n session.release();\n }\n if (pool !== null && ownsPool) {\n const closing = pool;\n pool = null;\n await runMapped(() => closing.end());\n }\n },\n\n formatArrayParam(values: unknown[]): unknown {\n return new PgArrayParam(values);\n },\n };\n}\n\n// ─── Re-exports (driver-error table, markers, helpers) ────────────\n\nexport { PG_SQLSTATE_ERROR_CODES, PG_SQLSTATE_REASONS, mapPgDriverError, pgErrorSqlstate } from \"./errors.ts\";\nexport { PgArrayParam, serializeParams, serializeParamsRaw } from \"./params.ts\";\nexport { createSavepointCounter, nextSavepointName } from \"./savepoints.ts\";\nexport type { SavepointCounter } from \"./savepoints.ts\";\nexport { createStatementNameCache } from \"./statement-cache.ts\";\nexport type { StatementNameCache } from \"./statement-cache.ts\";\nexport {\n ISOLATION_LEVEL_SQL,\n beginStatement,\n classifyRawTransactionControl,\n refuseNestedTransactionOptions,\n statementTimeoutStatement,\n} from \"./transaction-sql.ts\";\nexport type { RawTransactionControl } from \"./transaction-sql.ts\";\n",
|
|
6
|
-
"/**\n * Driver-error mapping for node-postgres (`pg`).\n *\n * Constitution rule 5: a raw driver error never escapes an adapter. Every\n * failure becomes a `VibeError` with a stable code, the driver error attached\n * as `cause`, and the SQLSTATE (plus constraint/table/column when the server\n * reported them) in `meta`.\n */\n\nimport { VibeError, type VibeErrorCode } from \"@vibeorm/schema\";\n\n// ─── SQLSTATE table ───────────────────────────────────────────────\n\n/**\n * PostgreSQL SQLSTATE → stable VibeError code. Frozen and mirrored by tests;\n * anything absent from this table maps to `VIBE_ADAPTER`.\n */\nexport const PG_SQLSTATE_ERROR_CODES: Readonly<Record<string, VibeErrorCode>> = Object.freeze({\n /** unique_violation */\n \"23505\": \"VIBE_UNIQUE_VIOLATION\",\n /** foreign_key_violation */\n \"23503\": \"VIBE_FK_VIOLATION\",\n /** not_null_violation */\n \"23502\": \"VIBE_VALIDATION\",\n /** check_violation */\n \"23514\": \"VIBE_VALIDATION\",\n /**\n * invalid_text_representation — a value the server cannot parse into the\n * column's type (out-of-range enum value, `\"abc\"` for an integer). Bad input,\n * so the same code sqlite reports for its enum CHECK violation.\n */\n \"22P02\": \"VIBE_VALIDATION\",\n /** serialization_failure */\n \"40001\": \"VIBE_TRANSACTION\",\n /** deadlock_detected */\n \"40P01\": \"VIBE_TRANSACTION\",\n /** query_canceled — statement_timeout fired */\n \"57014\": \"VIBE_TRANSACTION\",\n});\n\n/** SQLSTATEs that additionally explain themselves through `meta.reason`. */\nexport const PG_SQLSTATE_REASONS: Readonly<Record<string, string>> = Object.freeze({\n \"57014\": \"timeout\",\n});\n\n// ─── Reading driver errors ────────────────────────────────────────\n\n/** A PostgreSQL SQLSTATE is exactly five digits/uppercase letters (e.g. `40P01`). */\nconst SQLSTATE_PATTERN = /^[0-9A-Z]{5}$/;\n\nfunction readStringField(params: { source: Record<string, unknown>; key: string }): string | undefined {\n const value = params.source[params.key];\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * Extract the SQLSTATE from a pg driver error. `pg` puts the server's SQLSTATE\n * on `error.code`; client-side failures (`ECONNREFUSED`, `ETIMEDOUT`, …) use\n * the same field for a non-SQLSTATE string, which this rejects.\n */\nexport function pgErrorSqlstate(params: { error: unknown }): string | undefined {\n const { error } = params;\n if (error === null || typeof error !== \"object\") return undefined;\n const code = readStringField({ source: error as Record<string, unknown>, key: \"code\" });\n return code !== undefined && SQLSTATE_PATTERN.test(code) ? code : undefined;\n}\n\n// ─── Mapping ──────────────────────────────────────────────────────\n\n/**\n * Map any error thrown by `pg` onto a `VibeError`.\n *\n * A `VibeError` passes through unchanged, so an error raised deeper inside the\n * ORM (or by a nested adapter call) is never re-wrapped.\n */\nexport function mapPgDriverError(params: { error: unknown }): VibeError {\n const { error } = params;\n if (error instanceof VibeError) return error;\n\n const source: Record<string, unknown> =\n error !== null && typeof error === \"object\" ? (error as Record<string, unknown>) : {};\n const sqlstate = pgErrorSqlstate({ error });\n const code: VibeErrorCode =\n (sqlstate === undefined ? undefined : PG_SQLSTATE_ERROR_CODES[sqlstate]) ?? \"VIBE_ADAPTER\";\n\n const meta: Record<string, unknown> = {};\n if (sqlstate !== undefined) meta.sqlstate = sqlstate;\n const constraint = readStringField({ source, key: \"constraint\" });\n if (constraint !== undefined) meta.constraint = constraint;\n const table = readStringField({ source, key: \"table\" });\n if (table !== undefined) meta.table = table;\n const column = readStringField({ source, key: \"column\" });\n if (column !== undefined) meta.column = column;\n const reason = sqlstate === undefined ? undefined : PG_SQLSTATE_REASONS[sqlstate];\n if (reason !== undefined) meta.reason = reason;\n\n const message =\n readStringField({ source, key: \"message\" }) ??\n (typeof error === \"string\" ? error : \"unknown postgres driver error\");\n\n return new VibeError({ code, message, meta, cause: error });\n}\n\n/** Run a driver call, mapping anything it throws onto a `VibeError`. */\nexport async function runMapped<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n throw mapPgDriverError({ error });\n }\n}\n",
|
|
5
|
+
"/**\n * @vibeorm/adapter-pg — node-postgres (`pg`) adapter for VibeORM v2.\n *\n * Runs on Bun and Node. Owns pooling, optional named prepared statements,\n * transactions (nested → savepoints on the same client) and driver-error\n * mapping. Only `VibeError` ever escapes.\n */\n\nimport type {\n AdapterBudgetSupport,\n DatabaseAdapter,\n QueryResult,\n TransactionOptions,\n WireFidelity,\n} from \"@vibeorm/runtime\";\nimport type { Dialect, Provider } from \"@vibeorm/schema\";\nimport pg from \"pg\";\nimport { mapPgDriverError, runMapped } from \"./errors.ts\";\nimport { PgArrayParam, serializeParams, serializeParamsRaw } from \"./params.ts\";\nimport {\n createSavepointScope,\n runNestedSavepoint,\n runRootScope,\n scopeTurn,\n type SavepointScope,\n} from \"./savepoint-gate.ts\";\nimport { createStatementNameCache, type StatementNameCache } from \"./statement-cache.ts\";\nimport {\n engineStatementBudgetMs,\n isTransactionDeadlineError,\n startTransactionBudget,\n type TransactionBudget,\n transactionOutcomeUnknownError,\n validateTransactionDeadline,\n} from \"./transaction-budget.ts\";\nimport {\n beginStatement,\n classifyRawTransactionControl,\n refuseNestedTransactionOptions,\n statementTimeoutStatement,\n} from \"./transaction-sql.ts\";\n\n// ─── Minimal pg surface ───────────────────────────────────────────\n\n/** The single `pg` query form this adapter uses (config object, never overloads). */\nexport type PgQueryConfig = {\n readonly text: string;\n readonly values?: unknown[];\n readonly name?: string;\n /**\n * QUERY-LOCAL result parsers ({@link EXACT_TYPES}). node-postgres reads this\n * off the query config, so nothing outside VibeORM's own statements is\n * affected — a caller's pool keeps the driver's documented behaviour.\n */\n readonly types?: PgTypeParsers;\n};\n\n/** The `pg-types` surface a query config may carry. */\nexport type PgTypeParsers = {\n getTypeParser(oid: number, format?: \"text\" | \"binary\"): (value: string) => unknown;\n};\n\n/** The parts of a `pg` result this adapter reads. */\nexport type PgQueryResultLike = {\n readonly rows: Record<string, unknown>[];\n readonly rowCount: number | null;\n};\n\n/** The parts of a `pg` PoolClient this adapter uses. */\nexport type PgPoolClientLike = {\n query(config: PgQueryConfig): Promise<PgQueryResultLike>;\n /**\n * Hand the client back. A TRUTHY argument tells node-postgres to DESTROY it\n * instead of pooling it — used when a rollback failed and the session state\n * can no longer be asserted (EPIC 6). Optional so existing test doubles that\n * declare `release(): void` still satisfy this type.\n */\n release(destroy?: boolean): void;\n /**\n * EventEmitter surface. A real `pg.PoolClient` has it; test doubles need not,\n * so both members are optional and the adapter feature-detects them.\n */\n on?(event: \"error\", listener: (error: unknown) => void): void;\n removeListener?(event: \"error\", listener: (error: unknown) => void): void;\n};\n\n/** The parts of a `pg` Pool this adapter uses — satisfied by a real `pg.Pool`. */\nexport type PgPoolLike = {\n connect(): Promise<PgPoolClientLike>;\n query(config: PgQueryConfig): Promise<PgQueryResultLike>;\n end(): Promise<void>;\n /** EventEmitter surface; optional for the same reason as on {@link PgPoolClientLike}. */\n on?(event: \"error\", listener: (error: unknown, client: PgPoolClientLike) => void): void;\n};\n\n/** Anything that can run a query: the pool itself or a checked-out client. */\ntype Queryable = { query(config: PgQueryConfig): Promise<PgQueryResultLike> };\n\n/**\n * Keep a CHECKED-OUT client's background failures from killing the process,\n * returning the detach to run before the client goes back to the pool.\n *\n * node-postgres listens for `'error'` on a pooled client only while that client\n * sits IDLE, and removes the listener the moment the client is checked out\n * (restoring it on release). A client this adapter holds — for a transaction,\n * or as a pinned raw session — therefore has NO listener, so a backend that\n * dies mid-transaction reaches `client.emit('error', …)` with none. An\n * `'error'` event without a listener is an uncaught exception: fatal under\n * Node, which turns a database failover into a dead application process.\n *\n * The listener deliberately does nothing with the error and is NOT an error\n * channel: the in-flight query already rejects on its own with the mapped\n * `VibeError`, and the pool discards the broken client. Its only job is to keep\n * the process alive. Detaching before `release()` matters just as much — a\n * listener left attached would shadow pg's own idle listener and stop the pool\n * evicting a client that fails later, while idle.\n */\n/**\n * Prepared-statement name registries, one per POOL (F16/F18) — see\n * ./statement-cache.ts for why they are shared and bounded. Weakly held, so a\n * pool that goes out of scope takes its registry with it.\n */\nconst POOL_STATEMENT_NAMES: WeakMap<PgPoolLike, StatementNameCache> = new WeakMap();\n\nfunction guardBackgroundErrors(params: { client: PgPoolClientLike }): () => void {\n const { client } = params;\n if (typeof client.on !== \"function\") return (): void => undefined;\n const swallow = (): void => {\n /* the failing call rejects with a mapped VibeError; nothing to report here */\n };\n client.on(\"error\", swallow);\n return (): void => {\n client.removeListener?.(\"error\", swallow);\n };\n}\n\n// ─── Options ──────────────────────────────────────────────────────\n\n/**\n * Options for {@link pgAdapter}. Either point it at a connection string (the\n * adapter then owns the pool it creates) or hand it a pool you already own.\n */\nexport type PgAdapterOptions = {\n /** PostgreSQL connection URL. Defaults to `process.env.DATABASE_URL`. */\n readonly connectionString?: string;\n /**\n * An existing `pg.Pool` to use instead of creating one. The adapter never\n * ends a pool it did not create, so `disconnect()` is a no-op in this mode.\n */\n readonly pool?: PgPoolLike;\n /** Maximum pooled connections (default 10). Ignored when `pool` is given. */\n readonly max?: number;\n /**\n * Pool-wide `statement_timeout` in milliseconds. Every connection inherits\n * it; a per-transaction `timeout` overrides it for that transaction.\n */\n readonly statementTimeout?: number;\n /** Milliseconds to wait for a pool checkout before failing (pg's `connectionTimeoutMillis`). */\n readonly connectionTimeout?: number;\n /**\n * Send ORM-path queries as named prepared statements (default false).\n * Named statements save planning time but let PostgreSQL fall back to a\n * generic plan after ~5 executions, which can pick worse indexes for range\n * filters — leave off unless profiling says otherwise.\n */\n readonly preparedStatements?: boolean;\n /** Maximum entries in the prepared-statement name cache (default 1000, LRU). */\n readonly stmtCacheMax?: number;\n};\n\n// ─── Adapter ──────────────────────────────────────────────────────\n\nconst DIALECT: Dialect = \"postgres\";\nconst PROVIDER: Provider = \"postgresql\";\n\n/**\n * node-postgres wire (board #30, live-verified on both execute paths):\n * timestamptz → `Date`, json/jsonb → parsed values, int4/float8 → numbers.\n * (int8 stays a string — BigInt decoding is real work and never pruned.)\n */\nconst WIRE: WireFidelity = Object.freeze({ dateTime: \"native\", json: \"parsed\", numbers: \"native\" } as const);\n\n/**\n * Timing budgets this adapter genuinely enforces (EPIC 6).\n *\n * - `acquireTimeout: true` — {@link PgAdapterOptions.connectionTimeout} maps to\n * node-postgres' `connectionTimeoutMillis`, which bounds the checkout wait\n * and rejects when the pool stays exhausted. The capability is declared here;\n * it is OFF until the option is set (pg's own default is \"wait forever\").\n * - `statementTimeout: \"all-statements\"` — PostgreSQL's `statement_timeout`\n * cancels ANY over-long statement, writes included (SQLSTATE 57014).\n * - `transactionDeadline: \"cancel-running-statements\"` — the strongest level:\n * the remaining budget is handed to the SERVER before each statement, so the\n * database itself stops work that would outlive the deadline. Nothing here is\n * a `Promise.race` over a statement that keeps running.\n */\nconst BUDGETS: AdapterBudgetSupport = Object.freeze({\n acquireTimeout: true,\n statementTimeout: \"all-statements\",\n transactionDeadline: \"cancel-running-statements\",\n} as const);\n\n// ─── Exact numeric arrays (F12) ───────────────────────────────\n\n/** `_numeric`: the array form of `numeric`/`DECIMAL`. */\nconst NUMERIC_ARRAY_OID = 1231;\n/** `_text`: its parser splits a postgres array literal into RAW element strings. */\nconst TEXT_ARRAY_OID = 1009;\n\n/**\n * Query-local type parsers that keep `numeric[]` EXACT.\n *\n * pg-types decodes `_numeric` with `parseFloat` per element, so\n * `9007199254740993` comes back as `9007199254740992` and `12.340` as the\n * number `12.34` — while the SCALAR `numeric` correctly stays a string and\n * VibeORM's Decimal contract is \"string in, string out\" on every dialect. The\n * array is the anomaly, and the loss happens inside the driver, before any\n * codec can see the value.\n *\n * The fix reuses the driver's OWN array-literal parser (`_text`), so array\n * syntax, quoting and NULL elements stay node-postgres' business; only the\n * per-element float conversion is dropped. It is attached PER QUERY (F12's\n * acceptance criterion), never by mutating `pg.types` globally: an injected\n * pool is shared property, and a global override would silently change every\n * other consumer in the process.\n */\nconst EXACT_TYPES: PgTypeParsers = {\n getTypeParser(oid: number, format?: \"text\" | \"binary\"): (value: string) => unknown {\n if (oid === NUMERIC_ARRAY_OID && (format === undefined || format === \"text\")) {\n return driverTypeParser(TEXT_ARRAY_OID, \"text\");\n }\n return driverTypeParser(oid, format);\n },\n};\n\n/**\n * `pg.types.getTypeParser` behind a plain numeric-OID signature. `@types/pg`\n * narrows the two-argument overload to its own `TypeId` union of well-known\n * OIDs, which does not include every array OID this function must look up.\n */\nconst driverTypeParser: (oid: number, format?: \"text\" | \"binary\") => (value: string) => unknown =\n pg.types.getTypeParser as unknown as (oid: number, format?: \"text\" | \"binary\") => (value: string) => unknown;\n\n/**\n * Create a VibeORM adapter backed by node-postgres.\n *\n * @example\n * ```ts\n * const adapter = pgAdapter({ connectionString: process.env.DATABASE_URL, max: 20 });\n * await adapter.connect();\n * const rows = await adapter.execute({ text: 'SELECT * FROM \"User\" WHERE \"id\" = $1', values: [1] });\n * ```\n *\n * @example Reusing a pool you already own\n * ```ts\n * import pg from \"pg\";\n * const pool = new pg.Pool({ connectionString });\n * const adapter = pgAdapter({ pool });\n * ```\n */\nexport function pgAdapter(options?: PgAdapterOptions): DatabaseAdapter {\n const usePrepared = options?.preparedStatements ?? false;\n const stmtCacheMax = options?.stmtCacheMax ?? 1000;\n\n let pool: PgPoolLike | null = null;\n let ownsPool = false;\n\n /**\n * The checked-out client of an OPEN raw transaction — session affinity for\n * the raw path. @vibeorm/migrate wraps transactional DDL in literal `BEGIN`\n * / `COMMIT` / `ROLLBACK` sent through `executeUnsafe`; without pinning,\n * `pool.query(\"BEGIN\")` sequences stay on one client only by LIFO checkout\n * luck, and any concurrent traffic silently splits the transaction across\n * connections. A pure `BEGIN` checks a client out, every raw statement until\n * the matching `COMMIT`/`ROLLBACK` rides it, and the close releases it. The\n * ORM path (`execute`) and `transaction()` stay on the pool. Concurrent raw\n * transactions on one adapter are unsupported.\n */\n let rawSession: PgPoolClientLike | null = null;\n /** Detach for {@link rawSession}'s background-error guard; runs before its release. */\n let rawSessionUnguard: (() => void) | null = null;\n\n function getPool(): PgPoolLike {\n if (pool !== null) return pool;\n\n if (options?.pool !== undefined) {\n pool = options.pool;\n ownsPool = false;\n return pool;\n }\n\n const config: Record<string, unknown> = {\n connectionString: options?.connectionString ?? process.env.DATABASE_URL,\n max: options?.max ?? 10,\n };\n if (options?.statementTimeout !== undefined) {\n config.statement_timeout = options.statementTimeout;\n }\n if (options?.connectionTimeout !== undefined) {\n config.connectionTimeoutMillis = options.connectionTimeout;\n }\n\n const PoolCtor = pg.Pool as unknown as new (poolConfig: Record<string, unknown>) => PgPoolLike;\n pool = new PoolCtor(config);\n /**\n * The IDLE half of the same hazard {@link guardBackgroundErrors} covers: a\n * pooled client that loses its socket while idle makes pg re-emit on the\n * POOL, and an unhandled `'error'` there is equally fatal. The pool already\n * evicts that client, so this listener only keeps the process alive.\n *\n * Attached ONLY to a pool this adapter constructed. A caller-supplied pool\n * (the `pool` option) has its own owner: the adapter never ends it either,\n * node-postgres documents attaching an `'error'` listener as that owner's\n * job, and registering one here that is never removed would stack up a\n * listener per adapter sharing that pool. The dangerous case — a client\n * checked out for a transaction or a raw session, which pg leaves\n * unlistened by construction — is guarded in BOTH modes.\n */\n pool.on?.(\"error\", () => {\n /* the pool has already discarded the failed client */\n });\n ownsPool = true;\n return pool;\n }\n\n /**\n * Prepared-statement names for the pool this adapter runs on (F18): the\n * registry is keyed by the POOL, so two adapters sharing one pool share one\n * name space instead of both starting at `vibeorm_0` and colliding on a\n * connection. It also bounds how many names that pool can ever put on a\n * backend (F16) no matter how many adapters come and go over it.\n */\n function statementNamesFor(params: { pool: PgPoolLike }): StatementNameCache {\n const existing = POOL_STATEMENT_NAMES.get(params.pool);\n if (existing !== undefined) return existing;\n const created = createStatementNameCache({ max: stmtCacheMax });\n POOL_STATEMENT_NAMES.set(params.pool, created);\n return created;\n }\n\n /** Build the config for one ORM-path query (statement name only when enabled). */\n function buildQueryConfig(params: { text: string; values: unknown[] }): PgQueryConfig {\n const values = serializeParams({ values: params.values });\n if (!usePrepared) return { text: params.text, values, types: EXACT_TYPES };\n // `undefined` once the pool's name budget is spent: the statement runs\n // unnamed rather than growing the server's prepared-statement retention.\n const name = statementNamesFor({ pool: getPool() }).getName({ text: params.text });\n return name === undefined\n ? { text: params.text, values, types: EXACT_TYPES }\n : { name, text: params.text, values, types: EXACT_TYPES };\n }\n\n async function runExecute(params: {\n queryable: Queryable;\n text: string;\n values: unknown[];\n }): Promise<Record<string, unknown>[]> {\n const config = buildQueryConfig({ text: params.text, values: params.values });\n const result = await runMapped(() => params.queryable.query(config));\n return result.rows;\n }\n\n async function runExecuteUnsafe(params: {\n queryable: Queryable;\n text: string;\n values?: unknown[];\n }): Promise<QueryResult> {\n const values = params.values === undefined ? undefined : serializeParamsRaw({ values: params.values });\n const result = await runMapped(() => params.queryable.query({ text: params.text, values, types: EXACT_TYPES }));\n return { rows: result.rows, affectedRows: result.rowCount ?? 0 };\n }\n\n /**\n * Adapter bound to one checked-out client that is already inside a\n * transaction. Nested `transaction()` calls open savepoints on that same\n * client, and their LIFETIMES are serialized by the savepoint gate (F14):\n * overlapping siblings share one savepoint stack, so the earlier one's\n * rollback would erase the later one's already released work.\n */\n function createClientAdapter(params: {\n client: PgPoolClientLike;\n scope: SavepointScope;\n budget: TransactionBudget;\n }): DatabaseAdapter {\n const { client, scope, budget } = params;\n\n /**\n * Hand the SERVER the remaining budget before a statement runs, when the\n * caller bought `\"cancel-running-statements\"`. `SET LOCAL` is\n * transaction-scoped, so PostgreSQL reverts it at COMMIT/ROLLBACK and the\n * connection returns to the pool with its session settings intact.\n *\n * Costs one extra round trip per statement, and only while a deadline is\n * active — the price of a deadline the database itself enforces.\n */\n async function applyEngineBudget(): Promise<void> {\n const ms = engineStatementBudgetMs({ budget });\n if (ms === null) return;\n await runMapped(() => client.query({ text: statementTimeoutStatement({ timeout: ms }) }));\n }\n\n return {\n dialect: DIALECT,\n provider: PROVIDER,\n wire: WIRE,\n budgets: BUDGETS,\n\n async execute(execParams) {\n const turn = scopeTurn({ scope });\n if (turn !== undefined) await turn;\n // After the turn, not before: waiting for a sibling savepoint spends\n // the same budget the statement is about to run against.\n budget.assertUsable({ stage: \"statement\" });\n await applyEngineBudget();\n return runExecute({ queryable: client, ...execParams });\n },\n\n async executeUnsafe(execParams) {\n const turn = scopeTurn({ scope });\n if (turn !== undefined) await turn;\n budget.assertUsable({ stage: \"statement\" });\n await applyEngineBudget();\n return runExecuteUnsafe({ queryable: client, ...execParams });\n },\n\n async transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n nestedOptions?: TransactionOptions,\n ): Promise<T> {\n refuseNestedTransactionOptions({ options: nestedOptions, provider: PROVIDER });\n budget.assertUsable({ stage: \"nested\" });\n return runNestedSavepoint({\n scope,\n execute: (statement) => runMapped(() => client.query({ text: statement })),\n // The child shares the ROOT budget by reference: a savepoint never\n // gets an independent clock or session setting.\n body: (child) => fn(createClientAdapter({ client, scope: child, budget })),\n });\n },\n\n async connect(): Promise<void> {\n // Already connected — this adapter is bound to a live client.\n },\n\n async disconnect(): Promise<void> {\n // The pool owns the connection lifecycle; releasing happens at the\n // top-level transaction boundary.\n },\n\n formatArrayParam(values: unknown[]): unknown {\n return new PgArrayParam(values);\n },\n };\n }\n\n return {\n dialect: DIALECT,\n provider: PROVIDER,\n wire: WIRE,\n budgets: BUDGETS,\n\n async execute(params) {\n return runExecute({ queryable: getPool(), ...params });\n },\n\n async executeUnsafe(params) {\n const control = classifyRawTransactionControl({ text: params.text });\n if (rawSession !== null) {\n if (control === \"close\") {\n const session = rawSession;\n const unguard = rawSessionUnguard;\n rawSession = null;\n rawSessionUnguard = null;\n try {\n return await runExecuteUnsafe({ queryable: session, ...params });\n } finally {\n unguard?.();\n session.release();\n }\n }\n // A nested raw BEGIN lands here too — postgres treats it as a warning\n // no-op on the open session, exactly like a single connection would.\n return runExecuteUnsafe({ queryable: rawSession, ...params });\n }\n if (control === \"open\") {\n const client = await runMapped(() => getPool().connect());\n const unguard = guardBackgroundErrors({ client });\n try {\n const result = await runExecuteUnsafe({ queryable: client, ...params });\n rawSession = client;\n rawSessionUnguard = unguard;\n return result;\n } catch (error) {\n unguard();\n client.release();\n throw error;\n }\n }\n return runExecuteUnsafe({ queryable: getPool(), ...params });\n },\n\n async transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n transactionOptions?: TransactionOptions,\n ): Promise<T> {\n // Refuse an unsupportable budget BEFORE checking a connection out, so a\n // bad option never costs a checkout and never leaves a transaction open.\n validateTransactionDeadline({\n options: transactionOptions,\n support: BUDGETS.transactionDeadline,\n provider: PROVIDER,\n });\n const client = await runMapped(() => getPool().connect());\n const unguard = guardBackgroundErrors({ client });\n const scope = createSavepointScope();\n // The deadline clock starts HERE: the connection is already in hand, so\n // acquisition (bounded separately by `connectionTimeout`) is not charged\n // against the caller's transaction budget.\n const budget = startTransactionBudget({ options: transactionOptions, provider: PROVIDER });\n /** Set when the session's state can no longer be asserted (see below). */\n let discard = false;\n try {\n await runMapped(() =>\n client.query({ text: beginStatement({ isolationLevel: transactionOptions?.isolationLevel }) }),\n );\n if (transactionOptions?.timeout !== undefined) {\n const text = statementTimeoutStatement({ timeout: transactionOptions.timeout });\n await runMapped(() => client.query({ text }));\n }\n const result = await runRootScope({\n scope,\n body: () => fn(createClientAdapter({ client, scope, budget })),\n });\n // An expired budget must never commit, however the callback ended.\n budget.assertUsable({ stage: \"commit\" });\n await runMapped(() => client.query({ text: \"COMMIT\" }));\n budget.close({ outcome: \"committed\" });\n return result;\n } catch (error) {\n try {\n await client.query({ text: \"ROLLBACK\" });\n budget.close({ outcome: \"rolled-back\" });\n } catch {\n // The rollback that should have cleaned up failed: this connection may\n // still be inside a transaction with `SET LOCAL` settings that were\n // never reverted, so it is DESTROYED rather than pooled, and the\n // commit state is reported as genuinely unknown.\n discard = true;\n budget.close({ outcome: \"unknown\" });\n if (budget.totalMs !== null && isTransactionDeadlineError(error)) {\n throw transactionOutcomeUnknownError({\n provider: PROVIDER,\n totalMs: budget.totalMs,\n cause: error,\n });\n }\n }\n throw error;\n } finally {\n unguard();\n client.release(discard);\n }\n },\n\n async connect(): Promise<void> {\n const client = await runMapped(() => getPool().connect());\n client.release();\n },\n\n async disconnect(): Promise<void> {\n if (rawSession !== null) {\n // An abandoned raw transaction must not leak an in-transaction client;\n // roll it back best-effort before the pool ends.\n const session = rawSession;\n const unguard = rawSessionUnguard;\n rawSession = null;\n rawSessionUnguard = null;\n try {\n await session.query({ text: \"ROLLBACK\" });\n } catch {\n /* the pool is closing; the session is going away regardless */\n }\n unguard?.();\n session.release();\n }\n if (pool !== null && ownsPool) {\n const closing = pool;\n pool = null;\n await runMapped(() => closing.end());\n }\n },\n\n formatArrayParam(values: unknown[]): unknown {\n return new PgArrayParam(values);\n },\n };\n}\n\n// ─── Re-exports (driver-error table, markers, helpers) ────────────\n\nexport { PG_SQLSTATE_ERROR_CODES, PG_SQLSTATE_REASONS, mapPgDriverError, pgErrorSqlstate } from \"./errors.ts\";\nexport { PgArrayParam, serializeParams, serializeParamsRaw } from \"./params.ts\";\nexport { createSavepointCounter, nextSavepointName } from \"./savepoints.ts\";\nexport type { SavepointCounter } from \"./savepoints.ts\";\nexport { createStatementNameCache } from \"./statement-cache.ts\";\nexport type { StatementNameCache } from \"./statement-cache.ts\";\nexport {\n ISOLATION_LEVEL_SQL,\n beginStatement,\n classifyRawTransactionControl,\n refuseNestedTransactionOptions,\n statementTimeoutStatement,\n} from \"./transaction-sql.ts\";\nexport type { RawTransactionControl } from \"./transaction-sql.ts\";\n// ─── EPIC 6: transaction budgets ──────────────────────────────────\nexport {\n DEFAULT_DEADLINE_CLOCK,\n engineStatementBudgetMs,\n isTransactionDeadlineError,\n startTransactionBudget,\n transactionClosedError,\n transactionDeadlineError,\n transactionOutcomeUnknownError,\n validateTransactionDeadline,\n} from \"./transaction-budget.ts\";\nexport type { BudgetStage, DeadlineClock, TransactionBudget, TransactionOutcome } from \"./transaction-budget.ts\";\n",
|
|
6
|
+
"/**\n * Driver-error mapping for node-postgres (`pg`).\n *\n * Constitution rule 5: a raw driver error never escapes an adapter. Every\n * failure becomes a `VibeError` with a stable code, the driver error attached\n * as `cause`, and the SQLSTATE (plus constraint/table/column when the server\n * reported them) in `meta`.\n */\n\nimport { VibeError, type VibeErrorCode } from \"@vibeorm/schema\";\n\n// ─── SQLSTATE table ───────────────────────────────────────────────\n\n/**\n * PostgreSQL SQLSTATE → stable VibeError code. Frozen and mirrored by tests;\n * anything absent from this table maps to `VIBE_ADAPTER`.\n */\nexport const PG_SQLSTATE_ERROR_CODES: Readonly<Record<string, VibeErrorCode>> = Object.freeze({\n /** unique_violation */\n \"23505\": \"VIBE_UNIQUE_VIOLATION\",\n /** foreign_key_violation */\n \"23503\": \"VIBE_FK_VIOLATION\",\n /** not_null_violation */\n \"23502\": \"VIBE_VALIDATION\",\n /** check_violation */\n \"23514\": \"VIBE_VALIDATION\",\n /**\n * invalid_text_representation — a value the server cannot parse into the\n * column's type (out-of-range enum value, `\"abc\"` for an integer). Bad input,\n * so the same code sqlite reports for its enum CHECK violation.\n */\n \"22P02\": \"VIBE_VALIDATION\",\n /**\n * insufficient_privilege — a denied table/column privilege, and the SQLSTATE a\n * native row-level-security policy raises when its WITH CHECK refuses a write.\n * Callers identify it by this code, never by message text.\n */\n \"42501\": \"VIBE_PERMISSION_DENIED\",\n /** serialization_failure */\n \"40001\": \"VIBE_TRANSACTION\",\n /** deadlock_detected */\n \"40P01\": \"VIBE_TRANSACTION\",\n /** query_canceled — statement_timeout fired */\n \"57014\": \"VIBE_TRANSACTION\",\n});\n\n/** SQLSTATEs that additionally explain themselves through `meta.reason`. */\nexport const PG_SQLSTATE_REASONS: Readonly<Record<string, string>> = Object.freeze({\n \"57014\": \"timeout\",\n});\n\n// ─── Reading driver errors ────────────────────────────────────────\n\n/** A PostgreSQL SQLSTATE is exactly five digits/uppercase letters (e.g. `40P01`). */\nconst SQLSTATE_PATTERN = /^[0-9A-Z]{5}$/;\n\nfunction readStringField(params: { source: Record<string, unknown>; key: string }): string | undefined {\n const value = params.source[params.key];\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * Extract the SQLSTATE from a pg driver error. `pg` puts the server's SQLSTATE\n * on `error.code`; client-side failures (`ECONNREFUSED`, `ETIMEDOUT`, …) use\n * the same field for a non-SQLSTATE string, which this rejects.\n */\nexport function pgErrorSqlstate(params: { error: unknown }): string | undefined {\n const { error } = params;\n if (error === null || typeof error !== \"object\") return undefined;\n const code = readStringField({ source: error as Record<string, unknown>, key: \"code\" });\n return code !== undefined && SQLSTATE_PATTERN.test(code) ? code : undefined;\n}\n\n// ─── Mapping ──────────────────────────────────────────────────────\n\n/**\n * Map any error thrown by `pg` onto a `VibeError`.\n *\n * A `VibeError` passes through unchanged, so an error raised deeper inside the\n * ORM (or by a nested adapter call) is never re-wrapped.\n */\nexport function mapPgDriverError(params: { error: unknown }): VibeError {\n const { error } = params;\n if (error instanceof VibeError) return error;\n\n const source: Record<string, unknown> =\n error !== null && typeof error === \"object\" ? (error as Record<string, unknown>) : {};\n const sqlstate = pgErrorSqlstate({ error });\n const code: VibeErrorCode =\n (sqlstate === undefined ? undefined : PG_SQLSTATE_ERROR_CODES[sqlstate]) ?? \"VIBE_ADAPTER\";\n\n const meta: Record<string, unknown> = {};\n if (sqlstate !== undefined) meta.sqlstate = sqlstate;\n const constraint = readStringField({ source, key: \"constraint\" });\n if (constraint !== undefined) meta.constraint = constraint;\n const table = readStringField({ source, key: \"table\" });\n if (table !== undefined) meta.table = table;\n const column = readStringField({ source, key: \"column\" });\n if (column !== undefined) meta.column = column;\n const reason = sqlstate === undefined ? undefined : PG_SQLSTATE_REASONS[sqlstate];\n if (reason !== undefined) meta.reason = reason;\n\n const message =\n readStringField({ source, key: \"message\" }) ??\n (typeof error === \"string\" ? error : \"unknown postgres driver error\");\n\n return new VibeError({ code, message, meta, cause: error });\n}\n\n/** Run a driver call, mapping anything it throws onto a `VibeError`. */\nexport async function runMapped<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n throw mapPgDriverError({ error });\n }\n}\n",
|
|
7
7
|
"/**\n * Parameter serialization for node-postgres — the ORM path and the raw path\n * differ, deliberately (see LEARNINGS.md).\n *\n * `pg` natively turns a JS array into a PostgreSQL array literal (`{1,2,3}`),\n * which is exactly what a raw query wants. The ORM hot path cannot tell whether\n * a JS array is destined for a `jsonb` column or for a scalar-list / `= ANY($n)`\n * parameter, so it JSON-stringifies arrays and objects — scalar-list values are\n * tagged with `PgArrayParam` by `formatArrayParam` and unwrapped here, reaching\n * the driver as the untouched JS array.\n */\n\n// ─── Scalar-list marker ───────────────────────────────────────────\n\n/**\n * Opaque token returned by `pgAdapter().formatArrayParam` marking a value as a\n * PostgreSQL array parameter (rather than a JSON value that happens to be an\n * array). The wrapped array reaches `pg` as-is; the driver serializes it.\n */\nexport class PgArrayParam {\n /** The untouched scalar-list values. */\n readonly values: unknown[];\n\n constructor(values: unknown[]) {\n this.values = values;\n }\n}\n\n// ─── Serialization ────────────────────────────────────────────────\n\n/** True for values `pg` must receive verbatim (dates, binary, primitives, null). */\nfunction isDriverNativeValue(value: unknown): boolean {\n return (\n value === null ||\n value === undefined ||\n typeof value !== \"object\" ||\n value instanceof Date ||\n ArrayBuffer.isView(value) ||\n value instanceof ArrayBuffer\n );\n}\n\n/**\n * ORM hot path: unwrap scalar-list markers, JSON-stringify plain objects **and**\n * plain arrays (they can only be `json`/`jsonb` values at this point).\n */\nexport function serializeParams(params: { values: readonly unknown[] }): unknown[] {\n return params.values.map((value) => {\n if (value instanceof PgArrayParam) return value.values;\n if (isDriverNativeValue(value)) return value;\n return JSON.stringify(value);\n });\n}\n\n/**\n * Raw path (`$queryRaw*` / `$executeRaw*` / DDL): identical to\n * {@link serializeParams} except that plain JS arrays pass straight through, so\n * `db.$queryRawUnsafe('… WHERE \"id\" = ANY($1)', [1, 2, 3])` matches rows.\n *\n * Trade-off (v1 lesson): binding a JS array **into** a `jsonb` column from a raw\n * query means calling `JSON.stringify` yourself.\n */\nexport function serializeParamsRaw(params: { values: readonly unknown[] }): unknown[] {\n return params.values.map((value) => {\n if (value instanceof PgArrayParam) return value.values;\n if (Array.isArray(value)) return value;\n if (isDriverNativeValue(value)) return value;\n return JSON.stringify(value);\n });\n}\n",
|
|
8
|
+
"/**\n * Savepoint lifetimes inside one top-level transaction (F14).\n *\n * A savepoint stack lives on ONE connection: `ROLLBACK TO SAVEPOINT s` undoes\n * everything done after `s`, including work a LATER savepoint already released.\n * Two `transaction()` callbacks opened from the same handle and overlapping in\n * time therefore share that one stack, and the earlier one's rollback silently\n * erases the later one's already committed work. Unique savepoint names do not\n * help — the names never collided, the lifetimes did.\n *\n * The rule enforced here, on every handle of a transaction:\n *\n * > A handle runs when nothing deeper than itself is open. Otherwise it waits\n * > for the innermost open savepoint to settle — unless the call is being made\n * > from INSIDE that savepoint's own callback, which is genuine nesting and\n * > proceeds immediately.\n *\n * The \"from inside\" test is an {@link AsyncLocalStorage} lookup, so the common\n * nesting shapes never wait on themselves: a child opened from its parent's\n * callback, and the parent handle used from within an open child's callback,\n * both proceed. Only genuinely concurrent siblings serialize.\n *\n * Not covered: a callback that awaits a sibling it did not start. That\n * arrangement asks for two savepoints to be open at once, which is exactly what\n * loses work; it now blocks instead. Deliberate — see the notes for this fix.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { type SavepointCounter, createSavepointCounter, nextSavepointName } from \"./savepoints.ts\";\n\n// ─── Types ────────────────────────────────────────────────────────\n\n/**\n * One handle's position in the savepoint stack of a top-level transaction.\n * `state` is shared by reference across every handle of that transaction.\n */\nexport type SavepointScope = {\n /** Physical savepoint depth; 0 is the top-level transaction itself. */\n readonly depth: number;\n /** Shared state: name allocation plus the innermost open savepoint. */\n readonly state: SavepointState;\n};\n\n/** Mutable state shared by every scope of one top-level transaction. */\nexport type SavepointState = {\n /** Savepoint name counter (shared, so names never collide). */\n readonly counter: SavepointCounter;\n /** The innermost savepoint currently open, or `null` when none is. */\n open: OpenSavepoint | null;\n};\n\n/** An open savepoint: its handle, its name, and when it finished. */\ntype OpenSavepoint = {\n readonly scope: SavepointScope;\n readonly name: string;\n readonly parent: OpenSavepoint | null;\n readonly settled: Promise<void>;\n readonly settle: () => void;\n};\n\n/**\n * The savepoint whose callback the current async context is running inside.\n * This is the discriminator between genuine nesting (proceed) and an\n * overlapping sibling (wait).\n */\nconst CURRENT = new AsyncLocalStorage<SavepointScope>();\n\n// ─── Public API ───────────────────────────────────────────────────\n\n/** Fresh scope for one top-level transaction: depth 0, nothing open. */\nexport function createSavepointScope(): SavepointScope {\n return { depth: 0, state: { counter: createSavepointCounter(), open: null } };\n}\n\n/**\n * Run a top-level transaction callback inside its scope's async context, so\n * nested calls made from it can be told apart from calls made inside an open\n * child.\n */\nexport function runRootScope<T>(params: { scope: SavepointScope; body: () => Promise<T> }): Promise<T> {\n return CURRENT.run(params.scope, params.body);\n}\n\n/**\n * The wait a statement on `scope` owes before it may run, or `undefined` when\n * it may run now. Returning `undefined` keeps the uncontended path — nothing\n * deeper open — free of an extra promise and microtask.\n */\nexport function scopeTurn(params: { scope: SavepointScope }): Promise<void> | undefined {\n const open = params.scope.state.open;\n if (mayProceed({ scope: params.scope, open })) return undefined;\n return waitForTurn({ scope: params.scope });\n}\n\n/**\n * Open a nested savepoint under `scope`, run `body` inside it and release it —\n * rolling back to it if `body` throws, exactly as before this gate existed.\n *\n * `execute` runs the savepoint control SQL (already wrapped in the adapter's\n * own driver-error mapping). Omit it when the driver manages the savepoint\n * itself (bun:sql's `savepoint()`), in which case only the lifetime is gated.\n */\nexport async function runNestedSavepoint<T>(params: {\n readonly scope: SavepointScope;\n readonly execute?: (statement: string) => Promise<unknown> | unknown;\n readonly body: (scope: SavepointScope) => Promise<T>;\n}): Promise<T> {\n const { scope, execute, body } = params;\n const node = await acquire({ scope });\n try {\n if (execute !== undefined) await execute(`SAVEPOINT ${node.name}`);\n let result: T;\n try {\n result = await CURRENT.run(node.scope, () => body(node.scope));\n } catch (error) {\n // A descendant the callback started but never awaited must finish before\n // this savepoint may be rolled back — releasing out of order corrupts\n // the stack.\n await drainDescendants({ node });\n if (execute !== undefined) {\n // Best effort: never mask the original failure with a rollback failure.\n try {\n await execute(`ROLLBACK TO SAVEPOINT ${node.name}`);\n } catch {\n /* rollback is best-effort */\n }\n }\n throw error;\n }\n await drainDescendants({ node });\n if (execute !== undefined) await execute(`RELEASE SAVEPOINT ${node.name}`);\n return result;\n } finally {\n closeNode({ node });\n }\n}\n\n// ─── Internals ────────────────────────────────────────────────────\n\n/** Whether `scope` may act while `open` is the innermost open savepoint. */\nfunction mayProceed(params: { scope: SavepointScope; open: OpenSavepoint | null }): boolean {\n const { scope, open } = params;\n if (open === null) return true;\n // This handle IS the innermost open savepoint.\n if (open.scope === scope) return true;\n // This handle's own savepoint has already closed (a retained child handle):\n // it can only act at the connection's current depth, and waiting for a\n // shallower savepoint it does not own would never resolve.\n if (open.scope.depth < scope.depth) return true;\n // Genuine nesting: the call is being made from inside the open callback.\n return CURRENT.getStore() === open.scope;\n}\n\nasync function waitForTurn(params: { scope: SavepointScope }): Promise<void> {\n for (;;) {\n const open = params.scope.state.open;\n if (open === null || mayProceed({ scope: params.scope, open })) return;\n await open.settled;\n }\n}\n\n/**\n * Wait for this handle's turn and take it in the SAME synchronous step — the\n * check and the push must not be separated by an await, or two waiters woken\n * together would both open a savepoint.\n */\nasync function acquire(params: { scope: SavepointScope }): Promise<OpenSavepoint> {\n const { scope } = params;\n for (;;) {\n const open = scope.state.open;\n if (mayProceed({ scope, open })) return pushNode({ scope, parent: open });\n // `mayProceed` returns true for a null `open`, so this is never null here.\n await (open as OpenSavepoint).settled;\n }\n}\n\nfunction pushNode(params: { scope: SavepointScope; parent: OpenSavepoint | null }): OpenSavepoint {\n const { scope, parent } = params;\n const state = scope.state;\n let settle: () => void = () => undefined;\n const settled = new Promise<void>((resolve) => {\n settle = () => resolve();\n });\n // Physical depth follows the connection's stack, not the handle that opened\n // it: a savepoint opened from an outer handle inside a child's callback still\n // nests inside that child.\n const node: OpenSavepoint = {\n scope: { depth: (parent === null ? 0 : parent.scope.depth) + 1, state },\n name: nextSavepointName({ counter: state.counter }),\n parent,\n settled,\n settle,\n };\n state.open = node;\n return node;\n}\n\nfunction closeNode(params: { node: OpenSavepoint }): void {\n const { node } = params;\n const state = node.scope.state;\n if (state.open === node) state.open = node.parent;\n node.settle();\n}\n\n/** Wait out savepoints a callback opened below this node and never awaited. */\nasync function drainDescendants(params: { node: OpenSavepoint }): Promise<void> {\n const state = params.node.scope.state;\n for (;;) {\n const open = state.open;\n if (open === null || open === params.node || open.scope.depth <= params.node.scope.depth) return;\n await open.settled;\n }\n}\n",
|
|
8
9
|
"/**\n * Savepoint naming for nested transactions.\n *\n * v1 lesson (LEARNINGS.md): the counter is shared **by reference** across every\n * adapter created for one top-level transaction, so sibling and deeply nested\n * savepoints can never collide on a name.\n */\n\n/** Mutable counter shared by reference across one top-level transaction. */\nexport type SavepointCounter = { n: number };\n\n/** Fresh counter — one per top-level transaction. */\nexport function createSavepointCounter(): SavepointCounter {\n return { n: 0 };\n}\n\n/**\n * Allocate the next savepoint name (`vibeorm_sp_0`, `vibeorm_sp_1`, …) and\n * advance the shared counter. The name is an identifier by construction, so it\n * is safe to interpolate into `SAVEPOINT` / `RELEASE` / `ROLLBACK TO` SQL.\n */\nexport function nextSavepointName(params: { counter: SavepointCounter }): string {\n return `vibeorm_sp_${params.counter.n++}`;\n}\n",
|
|
9
|
-
"/**\n * Bounded prepared-statement
|
|
10
|
-
"/**\n * Transaction-control SQL text (postgres dialect).\n *\n * Kept apart from the adapter so the mapping from `TransactionOptions` to SQL\n * is unit-testable without a server, and so the timeout value is validated\n * before it is ever interpolated into a statement.\n */\n\nimport type { IsolationLevel, TransactionOptions } from \"@vibeorm/runtime\";\nimport { VibeError } from \"@vibeorm/schema\";\n\n/** VibeORM isolation level → PostgreSQL isolation level keyword. */\nexport const ISOLATION_LEVEL_SQL: Readonly<Record<IsolationLevel, string>> = Object.freeze({\n ReadCommitted: \"READ COMMITTED\",\n RepeatableRead: \"REPEATABLE READ\",\n Serializable: \"SERIALIZABLE\",\n});\n\n/** `BEGIN`, with an `ISOLATION LEVEL` clause when the caller asked for one. */\nexport function beginStatement(params: { isolationLevel?: IsolationLevel }): string {\n const { isolationLevel } = params;\n return isolationLevel === undefined\n ? \"BEGIN\"\n : `BEGIN ISOLATION LEVEL ${ISOLATION_LEVEL_SQL[isolationLevel]}`;\n}\n\n/**\n * `SET LOCAL statement_timeout = <ms>` — transaction-scoped, so PostgreSQL\n * cancels an over-long statement with SQLSTATE 57014 (mapped to\n * `VIBE_TRANSACTION` with `meta.reason = \"timeout\"`).\n *\n * @throws VibeError `VIBE_VALIDATION` when the timeout is not a non-negative\n * integer — the value is interpolated into SQL, so it is never trusted blindly.\n */\nexport function statementTimeoutStatement(params: { timeout: number }): string {\n const { timeout } = params;\n if (!Number.isInteger(timeout) || timeout < 0) {\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `transaction timeout must be a non-negative integer of milliseconds, received ${String(timeout)}`,\n meta: { timeout },\n });\n }\n return `SET LOCAL statement_timeout = ${timeout}`;\n}\n\n// ─── Raw transaction control (session affinity) ─────────────────\n\n/** How a raw statement steers the adapter's session-affine raw transaction. */\nexport type RawTransactionControl = \"open\" | \"close\" | null;\n\nconst RAW_OPEN_PATTERN: RegExp = /^\\s*(?:begin|start\\s+transaction)\\b[^;]*;?\\s*$/i;\nconst RAW_CLOSE_PATTERN: RegExp = /^\\s*(?:commit|end|rollback|abort)(?:\\s+(?:transaction|work))?\\s*;?\\s*$/i;\n\n/**\n * Classify a raw statement as transaction control.\n *\n * @vibeorm/migrate drives transactional DDL by sending literal `BEGIN` /\n * `COMMIT` / `ROLLBACK` through its stateless `SqlExecutor` — sound only when\n * every statement in between rides the SAME connection. Without pinning, a\n * pooled `pool.query(\"BEGIN\")` sequence stays on one client only by LIFO\n * checkout luck; any concurrent traffic silently splits the transaction\n * across connections. The adapter uses this to pin one client for the whole\n * raw transaction (\"open\" checks out, \"close\" releases).\n *\n * Deliberately strict: only PURE single-statement control text matches\n * (`BEGIN`, `BEGIN ISOLATION LEVEL …;`, `COMMIT`, `ROLLBACK WORK`, `END`,\n * `ABORT`). Compound scripts, `ROLLBACK TO SAVEPOINT`, two-phase\n * `COMMIT PREPARED` and `COMMIT AND CHAIN` (which keeps a transaction open)\n * never engage the pinning.\n */\nexport function classifyRawTransactionControl(params: { text: string }): RawTransactionControl {\n if (RAW_OPEN_PATTERN.test(params.text)) return \"open\";\n if (RAW_CLOSE_PATTERN.test(params.text)) return \"close\";\n return null;\n}\n\n// ─── Nested transaction options (the cross-adapter contract) ──────\n\n/**\n * Refuse options on a NESTED `transaction()` call — the same contract on every\n * adapter (see the `DatabaseAdapter.transaction` JSDoc in @vibeorm/runtime):\n * a nested transaction is a SAVEPOINT, and a savepoint can neither change the\n * isolation level of the transaction it joins nor enforce its own timeout.\n * Silently dropping the option (the pre-#3 behaviour) hid exactly that.\n *\n * @throws VibeError `VIBE_VALIDATION` when `isolationLevel` or `timeout` is\n * present (an `undefined` or empty options object is accepted).\n */\nexport function refuseNestedTransactionOptions(params: {\n options?: TransactionOptions;\n provider: string;\n}): void {\n const { options, provider } = params;\n if (options === undefined) return;\n\n const passed: string[] = [];\n if (options.isolationLevel !== undefined) passed.push(\"isolationLevel\");\n if (options.timeout !== undefined) passed.push(\"timeout\");\n if (passed.length === 0) return;\n\n const meta: Record<string, unknown> = { provider, nested: true };\n if (options.isolationLevel !== undefined) meta.isolationLevel = options.isolationLevel;\n if (options.timeout !== undefined) meta.timeout = options.timeout;\n\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `nested transactions run as savepoints and cannot honor ${passed.join(\" or \")} — a savepoint cannot change the isolation level of the transaction it joins, and a nested timeout is not enforceable; pass options on the top-level $transaction`,\n meta,\n });\n}\n"
|
|
10
|
+
"/**\n * Bounded prepared-statement NAME registry, shared per pool.\n *\n * With `preparedStatements: true` every distinct SQL text gets a stable name, so\n * PostgreSQL keeps a cached plan for it. Two properties matter, and the first\n * version of this file had neither:\n *\n * 1. **The bound has to be a bound on the SERVER** (F16). Evicting a local\n * mapping and minting a fresh name leaves the old prepared statement on\n * every backend that ever saw it — the local map stayed small while server\n * retention grew without limit. Nor can eviction be repaired with\n * `DEALLOCATE`: a name is prepared per CONNECTION, the adapter does not know\n * which pooled connections hold it, and deallocating behind node-postgres'\n * back invalidates its own per-client name registry (it would keep sending\n * the name and the server would refuse it).\n *\n * So the registry never re-uses a name for another text and never evicts:\n * it allocates at most `max` names, and once that budget is spent a new text\n * runs UNNAMED — bounded preparation fallback. Server retention is then\n * `max` per connection, permanently. Statements still bind their parameters;\n * only the server-side plan cache is skipped.\n *\n * 2. **Adapters sharing one pool must not collide** (F18). Each adapter used to\n * start its own counter at zero, so two adapters on one pool both sent\n * `vibeorm_0` for different SQL and postgres refused the second\n * (\"Prepared statements must be unique\"). Names are therefore allocated by a\n * registry shared per pool, which also stops N adapters from preparing the\n * same text N times.\n */\n\n/** Registry mapping SQL text to the prepared-statement name `pg` should send. */\nexport type StatementNameCache = {\n /**\n * Stable statement name for `text`, allocating one on first sight — or\n * `undefined` once the name budget is spent, meaning \"send this one unnamed\".\n */\n getName(params: { text: string }): string | undefined;\n /** Number of names allocated — diagnostics and tests. */\n size(): number;\n};\n\n/**\n * Create a statement-name registry that allocates at most `max` names\n * (`vibeorm_0`, `vibeorm_1`, …). Texts beyond the budget get no name and run\n * unprepared, so the server's prepared-statement retention stays bounded.\n */\nexport function createStatementNameCache(params: { max: number }): StatementNameCache {\n const max = Math.max(0, params.max);\n const names = new Map<string, string>();\n let counter = 0;\n\n return {\n getName(nameParams: { text: string }): string | undefined {\n const { text } = nameParams;\n const existing = names.get(text);\n if (existing !== undefined) return existing;\n if (names.size >= max) return undefined;\n const name = `vibeorm_${counter++}`;\n names.set(text, name);\n return name;\n },\n\n size(): number {\n return names.size;\n },\n };\n}\n",
|
|
11
|
+
"/**\n * Transaction budgets — the total-deadline clock and the handle-closure gate.\n *\n * BYTE-IDENTICAL in all six adapter packages, exactly like `savepoint-gate.ts`:\n * adapters depend on `@vibeorm/runtime` for TYPES only, so a shared value\n * module there would invert the dependency direction, and `@vibeorm/schema` is\n * the IR package, not a home for a transaction clock. Keep the six copies in\n * lockstep — a divergence here is a silent per-engine behaviour difference.\n *\n * WHAT A DEADLINE IS, AND IS NOT\n *\n * `TransactionOptions.timeout` is unchanged: a PER-STATEMENT engine-side bound.\n * `TransactionOptions.deadline` is new and different — a TOTAL wall-clock bound\n * on one top-level transaction. Its clock starts immediately before `BEGIN` is\n * sent, so connection acquisition (which has its own budget on the pooled\n * adapters) is deliberately NOT counted.\n *\n * Enforcement is never `Promise.race` over a statement that keeps running:\n *\n * - `\"between-statements\"` (the default, and all six adapters can deliver it):\n * before every statement, every nested `transaction()` and the `COMMIT`, an\n * expired budget refuses. The statement is never sent and the transaction is\n * rolled back. A statement ALREADY IN FLIGHT is not interrupted.\n * - `\"cancel-running-statements\"` (postgres servers only): additionally hands\n * the engine the remaining budget as `statement_timeout`, so the SERVER\n * cancels an over-long statement. An adapter that cannot do this refuses the\n * request outright rather than quietly delivering the weaker level.\n *\n * JavaScript cannot forcibly stop a running callback. A callback that keeps\n * going past the deadline finds its later database calls refused; work it does\n * outside the database (an HTTP call, an SMS) is not stopped and cannot be.\n * There is no automatic retry: a deadline failure is terminal for that\n * transaction, because external side effects may already have happened.\n */\n\nimport type {\n TransactionDeadlineEnforcement,\n TransactionDeadlineSupport,\n TransactionOptions,\n} from \"@vibeorm/runtime\";\nimport { VibeError } from \"@vibeorm/schema\";\n\n// ─── Types ────────────────────────────────────────────────────────\n\n/** Where a budget check happened, reported as `meta.stage`. */\nexport type BudgetStage = \"statement\" | \"nested\" | \"commit\";\n\n/**\n * What is known about a finished transaction. `\"unknown\"` is a first-class\n * outcome, not a failure to decide: when a rollback itself fails the commit\n * state genuinely cannot be asserted, and claiming \"rolled back\" would be a lie.\n */\nexport type TransactionOutcome = \"committed\" | \"rolled-back\" | \"unknown\";\n\n/** Wall clock, injectable so tests are deterministic instead of sleep-timed. */\nexport type DeadlineClock = () => number;\n\n/** The ambient clock, used whenever no seam is injected. */\nexport const DEFAULT_DEADLINE_CLOCK: DeadlineClock = (): number => Date.now();\n\n/**\n * One top-level transaction's budget. Nested savepoint handles share this\n * object BY REFERENCE — they never get an independent clock, connection or\n * session setting.\n */\nexport type TransactionBudget = {\n /** The enforcement level in force, or `null` when no deadline was requested. */\n readonly enforcement: TransactionDeadlineEnforcement | null;\n /** The requested total budget in milliseconds, or `null` when none was. */\n readonly totalMs: number | null;\n /** Existing per-statement limit, independent of the total deadline. Zero disables it. */\n readonly statementTimeoutMs: number | null;\n /** Milliseconds left (never negative), or `null` when no deadline is set. */\n remainingMs(): number | null;\n /** True only when a deadline is set and has passed. */\n expired(): boolean;\n /** Refuse a closed handle or an expired budget. Called BEFORE anything is sent. */\n assertUsable(params: { stage: BudgetStage }): void;\n /** Record the terminal outcome; the first call wins and later ones are ignored. */\n close(params: { outcome: TransactionOutcome }): void;\n /** The recorded outcome, or `null` while the transaction is still open. */\n readonly outcome: TransactionOutcome | null;\n};\n\n// ─── Validation (before BEGIN, before any write) ──────────────────\n\n/**\n * Check `options.deadline` against what this adapter can honestly deliver.\n * Called BEFORE `BEGIN` — a budget this engine cannot honour must never leave\n * a transaction open behind it.\n *\n * @throws VibeError `VIBE_VALIDATION` when `totalMs` is not a positive integer.\n * @throws VibeError `VIBE_UNSUPPORTED_CAPABILITY` when the requested\n * `enforcement` is stronger than `support` — refused, never silently degraded.\n */\nexport function validateTransactionDeadline(params: {\n options?: TransactionOptions;\n support: TransactionDeadlineSupport;\n provider: string;\n}): void {\n const { options, support, provider } = params;\n const deadline = options?.deadline;\n if (deadline === undefined) return;\n\n if (support === \"unsupported\") {\n throw new VibeError({\n code: \"VIBE_UNSUPPORTED_CAPABILITY\",\n message: `${provider} cannot enforce a transaction deadline — remove the \\`deadline\\` option`,\n meta: { provider, feature: \"transactionDeadline\", supported: support },\n });\n }\n\n if (!Number.isInteger(deadline.totalMs) || deadline.totalMs <= 0) {\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `transaction deadline \\`totalMs\\` must be a positive integer of milliseconds, received ${String(deadline.totalMs)}`,\n meta: { provider, feature: \"transactionDeadline\", totalMs: deadline.totalMs },\n });\n }\n\n const requested: TransactionDeadlineEnforcement = deadline.enforcement ?? \"between-statements\";\n if (requested === \"cancel-running-statements\" && support !== \"cancel-running-statements\") {\n throw new VibeError({\n code: \"VIBE_UNSUPPORTED_CAPABILITY\",\n message:\n `${provider} cannot cancel a statement that is already running, so the requested ` +\n \"`cancel-running-statements` deadline guarantee is refused rather than silently downgraded — \" +\n 'ask for \"between-statements\" if a budget checked between statements is enough',\n meta: { provider, feature: \"transactionDeadline\", requested, supported: support },\n });\n }\n}\n\n// ─── The budget ───────────────────────────────────────────────────\n\n/**\n * Start the clock for one top-level transaction. Call it immediately before\n * `BEGIN`; {@link validateTransactionDeadline} must already have run.\n */\nexport function startTransactionBudget(params: {\n options?: TransactionOptions;\n provider: string;\n clock?: DeadlineClock;\n}): TransactionBudget {\n const { options, provider } = params;\n const clock = params.clock ?? DEFAULT_DEADLINE_CLOCK;\n const deadline = options?.deadline;\n const totalMs = deadline === undefined ? null : deadline.totalMs;\n const enforcement: TransactionDeadlineEnforcement | null =\n deadline === undefined ? null : (deadline.enforcement ?? \"between-statements\");\n const expiresAt = totalMs === null ? null : clock() + totalMs;\n let outcome: TransactionOutcome | null = null;\n\n const budget: TransactionBudget = {\n enforcement,\n totalMs,\n statementTimeoutMs: options?.timeout ?? null,\n remainingMs(): number | null {\n return expiresAt === null ? null : Math.max(0, expiresAt - clock());\n },\n expired(): boolean {\n return expiresAt !== null && clock() >= expiresAt;\n },\n assertUsable(assertParams: { stage: BudgetStage }): void {\n if (outcome !== null) {\n throw transactionClosedError({ provider, outcome, stage: assertParams.stage });\n }\n if (expiresAt !== null && clock() >= expiresAt) {\n throw transactionDeadlineError({\n provider,\n stage: assertParams.stage,\n totalMs: totalMs as number,\n overdueMs: clock() - expiresAt,\n });\n }\n },\n close(closeParams: { outcome: TransactionOutcome }): void {\n if (outcome === null) outcome = closeParams.outcome;\n },\n get outcome(): TransactionOutcome | null {\n return outcome;\n },\n };\n return budget;\n}\n\n/**\n * The engine-side bound for the NEXT statement, or `null` when the caller did\n * not buy `\"cancel-running-statements\"`. Floored at 1 ms: on postgres `0` means\n * \"no limit\", so a spent budget must never be handed over as a zero.\n */\nexport function engineStatementBudgetMs(params: { budget: TransactionBudget }): number | null {\n const { budget } = params;\n if (budget.enforcement !== \"cancel-running-statements\") return null;\n const remaining = budget.remainingMs();\n if (remaining === null) return null;\n const totalBound = Math.max(1, Math.ceil(remaining));\n return budget.statementTimeoutMs !== null && budget.statementTimeoutMs > 0\n ? Math.min(totalBound, budget.statementTimeoutMs) : totalBound;\n}\n\n// ─── Errors ───────────────────────────────────────────────────────\n\n/**\n * The refusal an expired budget raises. `VIBE_TRANSACTION` with a stable\n * `meta.reason` — no SQL text, no parameter values, no credentials.\n */\nexport function transactionDeadlineError(params: {\n provider: string;\n stage: BudgetStage;\n totalMs: number;\n overdueMs: number;\n}): VibeError {\n const { provider, stage, totalMs, overdueMs } = params;\n const what =\n stage === \"commit\"\n ? \"the transaction was rolled back instead of committed\"\n : \"the statement was never sent and the transaction is being rolled back\";\n return new VibeError({\n code: \"VIBE_TRANSACTION\",\n message:\n `transaction deadline of ${totalMs} ms expired ${Math.max(0, Math.round(overdueMs))} ms ago — ${what}. ` +\n \"Nothing is retried automatically: work the callback did outside the database may already have happened.\",\n meta: { provider, reason: \"transaction-deadline\", stage, totalMs, overdueMs: Math.max(0, Math.round(overdueMs)) },\n });\n}\n\n/**\n * The refusal an ESCAPED transaction handle raises — a transactional adapter\n * kept past the end of its transaction. Without this it would run on a\n * connection that is back in the pool, outside any transaction.\n */\nexport function transactionClosedError(params: {\n provider: string;\n outcome: TransactionOutcome;\n stage: BudgetStage;\n}): VibeError {\n const { provider, outcome, stage } = params;\n return new VibeError({\n code: \"VIBE_TRANSACTION\",\n message:\n `this transaction has already finished (${outcome}), so its client can no longer be used — ` +\n \"a handle kept past the end of `$transaction` would run outside the transaction, on a connection \" +\n \"that now belongs to someone else\",\n meta: { provider, reason: \"transaction-closed\", outcome, stage },\n });\n}\n\n/**\n * The stable typed outcome for \"the deadline expired and the rollback that was\n * supposed to clean up failed too\". Promising a rollback here would be false;\n * promising a retry would be worse.\n *\n * `cause` is the CAUSAL error (the deadline refusal), so the reason the\n * transaction was being abandoned survives. The rollback failure itself is\n * reported only as `meta.rollbackFailed`: a raw driver failure can carry\n * statement text, and this error is meant to be logged.\n */\nexport function transactionOutcomeUnknownError(params: {\n provider: string;\n totalMs: number;\n cause: unknown;\n}): VibeError {\n const { provider, totalMs, cause } = params;\n return new VibeError({\n code: \"VIBE_TRANSACTION\",\n message:\n `transaction deadline of ${totalMs} ms expired and the rollback that should have cleaned up failed — ` +\n \"the commit state of this transaction is UNKNOWN. It is not retried automatically; inspect the data \" +\n \"before deciding.\",\n meta: {\n provider,\n reason: \"transaction-outcome-unknown\",\n outcome: \"unknown\",\n totalMs,\n rollbackFailed: true,\n },\n cause,\n });\n}\n\n/** Whether `error` is this module's deadline refusal (used to pick the cleanup path). */\nexport function isTransactionDeadlineError(error: unknown): boolean {\n const reason = (error as { meta?: { reason?: unknown } } | null)?.meta?.reason;\n return reason === \"transaction-deadline\";\n}\n",
|
|
12
|
+
"/**\n * Transaction-control SQL text (postgres dialect).\n *\n * Kept apart from the adapter so the mapping from `TransactionOptions` to SQL\n * is unit-testable without a server, and so the timeout value is validated\n * before it is ever interpolated into a statement.\n */\n\nimport type { IsolationLevel, TransactionOptions } from \"@vibeorm/runtime\";\nimport { VibeError } from \"@vibeorm/schema\";\n\n/** VibeORM isolation level → PostgreSQL isolation level keyword. */\nexport const ISOLATION_LEVEL_SQL: Readonly<Record<IsolationLevel, string>> = Object.freeze({\n ReadCommitted: \"READ COMMITTED\",\n RepeatableRead: \"REPEATABLE READ\",\n Serializable: \"SERIALIZABLE\",\n});\n\n/** `BEGIN`, with an `ISOLATION LEVEL` clause when the caller asked for one. */\nexport function beginStatement(params: { isolationLevel?: IsolationLevel }): string {\n const { isolationLevel } = params;\n return isolationLevel === undefined\n ? \"BEGIN\"\n : `BEGIN ISOLATION LEVEL ${ISOLATION_LEVEL_SQL[isolationLevel]}`;\n}\n\n/**\n * `SET LOCAL statement_timeout = <ms>` — transaction-scoped, so PostgreSQL\n * cancels an over-long statement with SQLSTATE 57014 (mapped to\n * `VIBE_TRANSACTION` with `meta.reason = \"timeout\"`).\n *\n * @throws VibeError `VIBE_VALIDATION` when the timeout is not a non-negative\n * integer — the value is interpolated into SQL, so it is never trusted blindly.\n */\nexport function statementTimeoutStatement(params: { timeout: number }): string {\n const { timeout } = params;\n if (!Number.isInteger(timeout) || timeout < 0) {\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `transaction timeout must be a non-negative integer of milliseconds, received ${String(timeout)}`,\n meta: { timeout },\n });\n }\n return `SET LOCAL statement_timeout = ${timeout}`;\n}\n\n// ─── Raw transaction control (session affinity) ─────────────────\n\n/** How a raw statement steers the adapter's session-affine raw transaction. */\nexport type RawTransactionControl = \"open\" | \"close\" | null;\n\nconst RAW_OPEN_PATTERN: RegExp = /^\\s*(?:begin|start\\s+transaction)\\b[^;]*;?\\s*$/i;\nconst RAW_CLOSE_PATTERN: RegExp = /^\\s*(?:commit|end|rollback|abort)(?:\\s+(?:transaction|work))?\\s*;?\\s*$/i;\n\n/**\n * Classify a raw statement as transaction control.\n *\n * @vibeorm/migrate drives transactional DDL by sending literal `BEGIN` /\n * `COMMIT` / `ROLLBACK` through its stateless `SqlExecutor` — sound only when\n * every statement in between rides the SAME connection. Without pinning, a\n * pooled `pool.query(\"BEGIN\")` sequence stays on one client only by LIFO\n * checkout luck; any concurrent traffic silently splits the transaction\n * across connections. The adapter uses this to pin one client for the whole\n * raw transaction (\"open\" checks out, \"close\" releases).\n *\n * Deliberately strict: only PURE single-statement control text matches\n * (`BEGIN`, `BEGIN ISOLATION LEVEL …;`, `COMMIT`, `ROLLBACK WORK`, `END`,\n * `ABORT`). Compound scripts, `ROLLBACK TO SAVEPOINT`, two-phase\n * `COMMIT PREPARED` and `COMMIT AND CHAIN` (which keeps a transaction open)\n * never engage the pinning.\n */\nexport function classifyRawTransactionControl(params: { text: string }): RawTransactionControl {\n if (RAW_OPEN_PATTERN.test(params.text)) return \"open\";\n if (RAW_CLOSE_PATTERN.test(params.text)) return \"close\";\n return null;\n}\n\n// ─── Nested transaction options (the cross-adapter contract) ──────\n\n/**\n * Refuse options on a NESTED `transaction()` call — the same contract on every\n * adapter (see the `DatabaseAdapter.transaction` JSDoc in @vibeorm/runtime):\n * a nested transaction is a SAVEPOINT, and a savepoint can neither change the\n * isolation level of the transaction it joins nor enforce its own timeout.\n * Silently dropping the option (the pre-#3 behaviour) hid exactly that.\n *\n * @throws VibeError `VIBE_VALIDATION` when `isolationLevel` or `timeout` is\n * present (an `undefined` or empty options object is accepted).\n */\nexport function refuseNestedTransactionOptions(params: {\n options?: TransactionOptions;\n provider: string;\n}): void {\n const { options, provider } = params;\n if (options === undefined) return;\n\n const passed: string[] = [];\n if (options.isolationLevel !== undefined) passed.push(\"isolationLevel\");\n if (options.timeout !== undefined) passed.push(\"timeout\");\n if (options.deadline !== undefined) passed.push(\"deadline\");\n if (passed.length === 0) return;\n\n const meta: Record<string, unknown> = { provider, nested: true };\n if (options.isolationLevel !== undefined) meta.isolationLevel = options.isolationLevel;\n if (options.timeout !== undefined) meta.timeout = options.timeout;\n if (options.deadline !== undefined) meta.deadline = options.deadline;\n\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `nested transactions run as savepoints and cannot honor ${passed.join(\" or \")} — a savepoint cannot change the isolation level of the transaction it joins, a nested timeout is not enforceable, and a nested deadline would need its own session setting on a connection it does not own (it inherits the top-level one instead); pass options on the top-level $transaction`,\n meta,\n });\n}\n"
|
|
11
13
|
],
|
|
12
|
-
"mappings": ";;AAUA;;;ACDA;AAQO,IAAM,0BAAmE,OAAO,OAAO;AAAA,EAE5F,SAAS;AAAA,EAET,SAAS;AAAA,EAET,SAAS;AAAA,EAET,SAAS;AAAA,EAMT,SAAS;AAAA,EAET,SAAS;AAAA,EAET,SAAS;AAAA,EAET,SAAS;AACX,CAAC;AAGM,IAAM,sBAAwD,OAAO,OAAO;AAAA,EACjF,SAAS;AACX,CAAC;AAKD,IAAM,mBAAmB;AAEzB,SAAS,eAAe,CAAC,QAA8E;AAAA,EACrG,MAAM,QAAQ,OAAO,OAAO,OAAO;AAAA,EACnC,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;AAAA;AAQ1D,SAAS,eAAe,CAAC,QAAgD;AAAA,EAC9E,QAAQ,UAAU;AAAA,EAClB,IAAI,UAAU,QAAQ,OAAO,UAAU;AAAA,IAAU;AAAA,EACjD,MAAM,OAAO,gBAAgB,EAAE,QAAQ,OAAkC,KAAK,OAAO,CAAC;AAAA,EACtF,OAAO,SAAS,aAAa,iBAAiB,KAAK,IAAI,IAAI,OAAO;AAAA;AAW7D,SAAS,gBAAgB,CAAC,QAAuC;AAAA,EACtE,QAAQ,UAAU;AAAA,EAClB,IAAI,iBAAiB;AAAA,IAAW,OAAO;AAAA,EAEvC,MAAM,SACJ,UAAU,QAAQ,OAAO,UAAU,WAAY,QAAoC,CAAC;AAAA,EACtF,MAAM,WAAW,gBAAgB,EAAE,MAAM,CAAC;AAAA,EAC1C,MAAM,QACH,aAAa,YAAY,YAAY,wBAAwB,cAAc;AAAA,EAE9E,MAA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
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Savepoint lifetimes inside one top-level transaction (F14).
|
|
3
|
+
*
|
|
4
|
+
* A savepoint stack lives on ONE connection: `ROLLBACK TO SAVEPOINT s` undoes
|
|
5
|
+
* everything done after `s`, including work a LATER savepoint already released.
|
|
6
|
+
* Two `transaction()` callbacks opened from the same handle and overlapping in
|
|
7
|
+
* time therefore share that one stack, and the earlier one's rollback silently
|
|
8
|
+
* erases the later one's already committed work. Unique savepoint names do not
|
|
9
|
+
* help — the names never collided, the lifetimes did.
|
|
10
|
+
*
|
|
11
|
+
* The rule enforced here, on every handle of a transaction:
|
|
12
|
+
*
|
|
13
|
+
* > A handle runs when nothing deeper than itself is open. Otherwise it waits
|
|
14
|
+
* > for the innermost open savepoint to settle — unless the call is being made
|
|
15
|
+
* > from INSIDE that savepoint's own callback, which is genuine nesting and
|
|
16
|
+
* > proceeds immediately.
|
|
17
|
+
*
|
|
18
|
+
* The "from inside" test is an {@link AsyncLocalStorage} lookup, so the common
|
|
19
|
+
* nesting shapes never wait on themselves: a child opened from its parent's
|
|
20
|
+
* callback, and the parent handle used from within an open child's callback,
|
|
21
|
+
* both proceed. Only genuinely concurrent siblings serialize.
|
|
22
|
+
*
|
|
23
|
+
* Not covered: a callback that awaits a sibling it did not start. That
|
|
24
|
+
* arrangement asks for two savepoints to be open at once, which is exactly what
|
|
25
|
+
* loses work; it now blocks instead. Deliberate — see the notes for this fix.
|
|
26
|
+
*/
|
|
27
|
+
import { type SavepointCounter } from "./savepoints.ts";
|
|
28
|
+
/**
|
|
29
|
+
* One handle's position in the savepoint stack of a top-level transaction.
|
|
30
|
+
* `state` is shared by reference across every handle of that transaction.
|
|
31
|
+
*/
|
|
32
|
+
export type SavepointScope = {
|
|
33
|
+
/** Physical savepoint depth; 0 is the top-level transaction itself. */
|
|
34
|
+
readonly depth: number;
|
|
35
|
+
/** Shared state: name allocation plus the innermost open savepoint. */
|
|
36
|
+
readonly state: SavepointState;
|
|
37
|
+
};
|
|
38
|
+
/** Mutable state shared by every scope of one top-level transaction. */
|
|
39
|
+
export type SavepointState = {
|
|
40
|
+
/** Savepoint name counter (shared, so names never collide). */
|
|
41
|
+
readonly counter: SavepointCounter;
|
|
42
|
+
/** The innermost savepoint currently open, or `null` when none is. */
|
|
43
|
+
open: OpenSavepoint | null;
|
|
44
|
+
};
|
|
45
|
+
/** An open savepoint: its handle, its name, and when it finished. */
|
|
46
|
+
type OpenSavepoint = {
|
|
47
|
+
readonly scope: SavepointScope;
|
|
48
|
+
readonly name: string;
|
|
49
|
+
readonly parent: OpenSavepoint | null;
|
|
50
|
+
readonly settled: Promise<void>;
|
|
51
|
+
readonly settle: () => void;
|
|
52
|
+
};
|
|
53
|
+
/** Fresh scope for one top-level transaction: depth 0, nothing open. */
|
|
54
|
+
export declare function createSavepointScope(): SavepointScope;
|
|
55
|
+
/**
|
|
56
|
+
* Run a top-level transaction callback inside its scope's async context, so
|
|
57
|
+
* nested calls made from it can be told apart from calls made inside an open
|
|
58
|
+
* child.
|
|
59
|
+
*/
|
|
60
|
+
export declare function runRootScope<T>(params: {
|
|
61
|
+
scope: SavepointScope;
|
|
62
|
+
body: () => Promise<T>;
|
|
63
|
+
}): Promise<T>;
|
|
64
|
+
/**
|
|
65
|
+
* The wait a statement on `scope` owes before it may run, or `undefined` when
|
|
66
|
+
* it may run now. Returning `undefined` keeps the uncontended path — nothing
|
|
67
|
+
* deeper open — free of an extra promise and microtask.
|
|
68
|
+
*/
|
|
69
|
+
export declare function scopeTurn(params: {
|
|
70
|
+
scope: SavepointScope;
|
|
71
|
+
}): Promise<void> | undefined;
|
|
72
|
+
/**
|
|
73
|
+
* Open a nested savepoint under `scope`, run `body` inside it and release it —
|
|
74
|
+
* rolling back to it if `body` throws, exactly as before this gate existed.
|
|
75
|
+
*
|
|
76
|
+
* `execute` runs the savepoint control SQL (already wrapped in the adapter's
|
|
77
|
+
* own driver-error mapping). Omit it when the driver manages the savepoint
|
|
78
|
+
* itself (bun:sql's `savepoint()`), in which case only the lifetime is gated.
|
|
79
|
+
*/
|
|
80
|
+
export declare function runNestedSavepoint<T>(params: {
|
|
81
|
+
readonly scope: SavepointScope;
|
|
82
|
+
readonly execute?: (statement: string) => Promise<unknown> | unknown;
|
|
83
|
+
readonly body: (scope: SavepointScope) => Promise<T>;
|
|
84
|
+
}): Promise<T>;
|
|
85
|
+
export {};
|
|
86
|
+
//# sourceMappingURL=savepoint-gate.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"savepoint-gate.d.ts","sourceRoot":"","sources":["../src/savepoint-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAGH,OAAO,EAAE,KAAK,gBAAgB,EAA6C,MAAM,iBAAiB,CAAC;AAInG;;;GAGG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,uEAAuE;IACvE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,uEAAuE;IACvE,QAAQ,CAAC,KAAK,EAAE,cAAc,CAAC;CAChC,CAAC;AAEF,wEAAwE;AACxE,MAAM,MAAM,cAAc,GAAG;IAC3B,+DAA+D;IAC/D,QAAQ,CAAC,OAAO,EAAE,gBAAgB,CAAC;IACnC,sEAAsE;IACtE,IAAI,EAAE,aAAa,GAAG,IAAI,CAAC;CAC5B,CAAC;AAEF,qEAAqE;AACrE,KAAK,aAAa,GAAG;IACnB,QAAQ,CAAC,KAAK,EAAE,cAAc,CAAC;IAC/B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI,CAAC;IACtC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAChC,QAAQ,CAAC,MAAM,EAAE,MAAM,IAAI,CAAC;CAC7B,CAAC;AAWF,wEAAwE;AACxE,wBAAgB,oBAAoB,IAAI,cAAc,CAErD;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE;IAAE,KAAK,EAAE,cAAc,CAAC;IAAC,IAAI,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,CAAA;CAAE,GAAG,OAAO,CAAC,CAAC,CAAC,CAErG;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE;IAAE,KAAK,EAAE,cAAc,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAItF;AAED;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,MAAM,EAAE;IAClD,QAAQ,CAAC,KAAK,EAAE,cAAc,CAAC;IAC/B,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;IACrE,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;CACtD,GAAG,OAAO,CAAC,CAAC,CAAC,CA6Bb"}
|
|
@@ -1,22 +1,48 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Bounded prepared-statement
|
|
2
|
+
* Bounded prepared-statement NAME registry, shared per pool.
|
|
3
3
|
*
|
|
4
4
|
* With `preparedStatements: true` every distinct SQL text gets a stable name, so
|
|
5
|
-
* PostgreSQL keeps a cached plan for it.
|
|
6
|
-
*
|
|
5
|
+
* PostgreSQL keeps a cached plan for it. Two properties matter, and the first
|
|
6
|
+
* version of this file had neither:
|
|
7
|
+
*
|
|
8
|
+
* 1. **The bound has to be a bound on the SERVER** (F16). Evicting a local
|
|
9
|
+
* mapping and minting a fresh name leaves the old prepared statement on
|
|
10
|
+
* every backend that ever saw it — the local map stayed small while server
|
|
11
|
+
* retention grew without limit. Nor can eviction be repaired with
|
|
12
|
+
* `DEALLOCATE`: a name is prepared per CONNECTION, the adapter does not know
|
|
13
|
+
* which pooled connections hold it, and deallocating behind node-postgres'
|
|
14
|
+
* back invalidates its own per-client name registry (it would keep sending
|
|
15
|
+
* the name and the server would refuse it).
|
|
16
|
+
*
|
|
17
|
+
* So the registry never re-uses a name for another text and never evicts:
|
|
18
|
+
* it allocates at most `max` names, and once that budget is spent a new text
|
|
19
|
+
* runs UNNAMED — bounded preparation fallback. Server retention is then
|
|
20
|
+
* `max` per connection, permanently. Statements still bind their parameters;
|
|
21
|
+
* only the server-side plan cache is skipped.
|
|
22
|
+
*
|
|
23
|
+
* 2. **Adapters sharing one pool must not collide** (F18). Each adapter used to
|
|
24
|
+
* start its own counter at zero, so two adapters on one pool both sent
|
|
25
|
+
* `vibeorm_0` for different SQL and postgres refused the second
|
|
26
|
+
* ("Prepared statements must be unique"). Names are therefore allocated by a
|
|
27
|
+
* registry shared per pool, which also stops N adapters from preparing the
|
|
28
|
+
* same text N times.
|
|
7
29
|
*/
|
|
8
|
-
/**
|
|
30
|
+
/** Registry mapping SQL text to the prepared-statement name `pg` should send. */
|
|
9
31
|
export type StatementNameCache = {
|
|
10
|
-
/**
|
|
32
|
+
/**
|
|
33
|
+
* Stable statement name for `text`, allocating one on first sight — or
|
|
34
|
+
* `undefined` once the name budget is spent, meaning "send this one unnamed".
|
|
35
|
+
*/
|
|
11
36
|
getName(params: {
|
|
12
37
|
text: string;
|
|
13
|
-
}): string;
|
|
14
|
-
/** Number of
|
|
38
|
+
}): string | undefined;
|
|
39
|
+
/** Number of names allocated — diagnostics and tests. */
|
|
15
40
|
size(): number;
|
|
16
41
|
};
|
|
17
42
|
/**
|
|
18
|
-
* Create a statement-name
|
|
19
|
-
*
|
|
43
|
+
* Create a statement-name registry that allocates at most `max` names
|
|
44
|
+
* (`vibeorm_0`, `vibeorm_1`, …). Texts beyond the budget get no name and run
|
|
45
|
+
* unprepared, so the server's prepared-statement retention stays bounded.
|
|
20
46
|
*/
|
|
21
47
|
export declare function createStatementNameCache(params: {
|
|
22
48
|
max: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"statement-cache.d.ts","sourceRoot":"","sources":["../src/statement-cache.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"statement-cache.d.ts","sourceRoot":"","sources":["../src/statement-cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,iFAAiF;AACjF,MAAM,MAAM,kBAAkB,GAAG;IAC/B;;;OAGG;IACH,OAAO,CAAC,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,GAAG,SAAS,CAAC;IACtD,yDAAyD;IACzD,IAAI,IAAI,MAAM,CAAC;CAChB,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,MAAM,EAAE;IAAE,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,kBAAkB,CAoBpF"}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transaction budgets — the total-deadline clock and the handle-closure gate.
|
|
3
|
+
*
|
|
4
|
+
* BYTE-IDENTICAL in all six adapter packages, exactly like `savepoint-gate.ts`:
|
|
5
|
+
* adapters depend on `@vibeorm/runtime` for TYPES only, so a shared value
|
|
6
|
+
* module there would invert the dependency direction, and `@vibeorm/schema` is
|
|
7
|
+
* the IR package, not a home for a transaction clock. Keep the six copies in
|
|
8
|
+
* lockstep — a divergence here is a silent per-engine behaviour difference.
|
|
9
|
+
*
|
|
10
|
+
* WHAT A DEADLINE IS, AND IS NOT
|
|
11
|
+
*
|
|
12
|
+
* `TransactionOptions.timeout` is unchanged: a PER-STATEMENT engine-side bound.
|
|
13
|
+
* `TransactionOptions.deadline` is new and different — a TOTAL wall-clock bound
|
|
14
|
+
* on one top-level transaction. Its clock starts immediately before `BEGIN` is
|
|
15
|
+
* sent, so connection acquisition (which has its own budget on the pooled
|
|
16
|
+
* adapters) is deliberately NOT counted.
|
|
17
|
+
*
|
|
18
|
+
* Enforcement is never `Promise.race` over a statement that keeps running:
|
|
19
|
+
*
|
|
20
|
+
* - `"between-statements"` (the default, and all six adapters can deliver it):
|
|
21
|
+
* before every statement, every nested `transaction()` and the `COMMIT`, an
|
|
22
|
+
* expired budget refuses. The statement is never sent and the transaction is
|
|
23
|
+
* rolled back. A statement ALREADY IN FLIGHT is not interrupted.
|
|
24
|
+
* - `"cancel-running-statements"` (postgres servers only): additionally hands
|
|
25
|
+
* the engine the remaining budget as `statement_timeout`, so the SERVER
|
|
26
|
+
* cancels an over-long statement. An adapter that cannot do this refuses the
|
|
27
|
+
* request outright rather than quietly delivering the weaker level.
|
|
28
|
+
*
|
|
29
|
+
* JavaScript cannot forcibly stop a running callback. A callback that keeps
|
|
30
|
+
* going past the deadline finds its later database calls refused; work it does
|
|
31
|
+
* outside the database (an HTTP call, an SMS) is not stopped and cannot be.
|
|
32
|
+
* There is no automatic retry: a deadline failure is terminal for that
|
|
33
|
+
* transaction, because external side effects may already have happened.
|
|
34
|
+
*/
|
|
35
|
+
import type { TransactionDeadlineEnforcement, TransactionDeadlineSupport, TransactionOptions } from "@vibeorm/runtime";
|
|
36
|
+
import { VibeError } from "@vibeorm/schema";
|
|
37
|
+
/** Where a budget check happened, reported as `meta.stage`. */
|
|
38
|
+
export type BudgetStage = "statement" | "nested" | "commit";
|
|
39
|
+
/**
|
|
40
|
+
* What is known about a finished transaction. `"unknown"` is a first-class
|
|
41
|
+
* outcome, not a failure to decide: when a rollback itself fails the commit
|
|
42
|
+
* state genuinely cannot be asserted, and claiming "rolled back" would be a lie.
|
|
43
|
+
*/
|
|
44
|
+
export type TransactionOutcome = "committed" | "rolled-back" | "unknown";
|
|
45
|
+
/** Wall clock, injectable so tests are deterministic instead of sleep-timed. */
|
|
46
|
+
export type DeadlineClock = () => number;
|
|
47
|
+
/** The ambient clock, used whenever no seam is injected. */
|
|
48
|
+
export declare const DEFAULT_DEADLINE_CLOCK: DeadlineClock;
|
|
49
|
+
/**
|
|
50
|
+
* One top-level transaction's budget. Nested savepoint handles share this
|
|
51
|
+
* object BY REFERENCE — they never get an independent clock, connection or
|
|
52
|
+
* session setting.
|
|
53
|
+
*/
|
|
54
|
+
export type TransactionBudget = {
|
|
55
|
+
/** The enforcement level in force, or `null` when no deadline was requested. */
|
|
56
|
+
readonly enforcement: TransactionDeadlineEnforcement | null;
|
|
57
|
+
/** The requested total budget in milliseconds, or `null` when none was. */
|
|
58
|
+
readonly totalMs: number | null;
|
|
59
|
+
/** Existing per-statement limit, independent of the total deadline. Zero disables it. */
|
|
60
|
+
readonly statementTimeoutMs: number | null;
|
|
61
|
+
/** Milliseconds left (never negative), or `null` when no deadline is set. */
|
|
62
|
+
remainingMs(): number | null;
|
|
63
|
+
/** True only when a deadline is set and has passed. */
|
|
64
|
+
expired(): boolean;
|
|
65
|
+
/** Refuse a closed handle or an expired budget. Called BEFORE anything is sent. */
|
|
66
|
+
assertUsable(params: {
|
|
67
|
+
stage: BudgetStage;
|
|
68
|
+
}): void;
|
|
69
|
+
/** Record the terminal outcome; the first call wins and later ones are ignored. */
|
|
70
|
+
close(params: {
|
|
71
|
+
outcome: TransactionOutcome;
|
|
72
|
+
}): void;
|
|
73
|
+
/** The recorded outcome, or `null` while the transaction is still open. */
|
|
74
|
+
readonly outcome: TransactionOutcome | null;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Check `options.deadline` against what this adapter can honestly deliver.
|
|
78
|
+
* Called BEFORE `BEGIN` — a budget this engine cannot honour must never leave
|
|
79
|
+
* a transaction open behind it.
|
|
80
|
+
*
|
|
81
|
+
* @throws VibeError `VIBE_VALIDATION` when `totalMs` is not a positive integer.
|
|
82
|
+
* @throws VibeError `VIBE_UNSUPPORTED_CAPABILITY` when the requested
|
|
83
|
+
* `enforcement` is stronger than `support` — refused, never silently degraded.
|
|
84
|
+
*/
|
|
85
|
+
export declare function validateTransactionDeadline(params: {
|
|
86
|
+
options?: TransactionOptions;
|
|
87
|
+
support: TransactionDeadlineSupport;
|
|
88
|
+
provider: string;
|
|
89
|
+
}): void;
|
|
90
|
+
/**
|
|
91
|
+
* Start the clock for one top-level transaction. Call it immediately before
|
|
92
|
+
* `BEGIN`; {@link validateTransactionDeadline} must already have run.
|
|
93
|
+
*/
|
|
94
|
+
export declare function startTransactionBudget(params: {
|
|
95
|
+
options?: TransactionOptions;
|
|
96
|
+
provider: string;
|
|
97
|
+
clock?: DeadlineClock;
|
|
98
|
+
}): TransactionBudget;
|
|
99
|
+
/**
|
|
100
|
+
* The engine-side bound for the NEXT statement, or `null` when the caller did
|
|
101
|
+
* not buy `"cancel-running-statements"`. Floored at 1 ms: on postgres `0` means
|
|
102
|
+
* "no limit", so a spent budget must never be handed over as a zero.
|
|
103
|
+
*/
|
|
104
|
+
export declare function engineStatementBudgetMs(params: {
|
|
105
|
+
budget: TransactionBudget;
|
|
106
|
+
}): number | null;
|
|
107
|
+
/**
|
|
108
|
+
* The refusal an expired budget raises. `VIBE_TRANSACTION` with a stable
|
|
109
|
+
* `meta.reason` — no SQL text, no parameter values, no credentials.
|
|
110
|
+
*/
|
|
111
|
+
export declare function transactionDeadlineError(params: {
|
|
112
|
+
provider: string;
|
|
113
|
+
stage: BudgetStage;
|
|
114
|
+
totalMs: number;
|
|
115
|
+
overdueMs: number;
|
|
116
|
+
}): VibeError;
|
|
117
|
+
/**
|
|
118
|
+
* The refusal an ESCAPED transaction handle raises — a transactional adapter
|
|
119
|
+
* kept past the end of its transaction. Without this it would run on a
|
|
120
|
+
* connection that is back in the pool, outside any transaction.
|
|
121
|
+
*/
|
|
122
|
+
export declare function transactionClosedError(params: {
|
|
123
|
+
provider: string;
|
|
124
|
+
outcome: TransactionOutcome;
|
|
125
|
+
stage: BudgetStage;
|
|
126
|
+
}): VibeError;
|
|
127
|
+
/**
|
|
128
|
+
* The stable typed outcome for "the deadline expired and the rollback that was
|
|
129
|
+
* supposed to clean up failed too". Promising a rollback here would be false;
|
|
130
|
+
* promising a retry would be worse.
|
|
131
|
+
*
|
|
132
|
+
* `cause` is the CAUSAL error (the deadline refusal), so the reason the
|
|
133
|
+
* transaction was being abandoned survives. The rollback failure itself is
|
|
134
|
+
* reported only as `meta.rollbackFailed`: a raw driver failure can carry
|
|
135
|
+
* statement text, and this error is meant to be logged.
|
|
136
|
+
*/
|
|
137
|
+
export declare function transactionOutcomeUnknownError(params: {
|
|
138
|
+
provider: string;
|
|
139
|
+
totalMs: number;
|
|
140
|
+
cause: unknown;
|
|
141
|
+
}): VibeError;
|
|
142
|
+
/** Whether `error` is this module's deadline refusal (used to pick the cleanup path). */
|
|
143
|
+
export declare function isTransactionDeadlineError(error: unknown): boolean;
|
|
144
|
+
//# sourceMappingURL=transaction-budget.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transaction-budget.d.ts","sourceRoot":"","sources":["../src/transaction-budget.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,OAAO,KAAK,EACV,8BAA8B,EAC9B,0BAA0B,EAC1B,kBAAkB,EACnB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAI5C,+DAA+D;AAC/D,MAAM,MAAM,WAAW,GAAG,WAAW,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAE5D;;;;GAIG;AACH,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,aAAa,GAAG,SAAS,CAAC;AAEzE,gFAAgF;AAChF,MAAM,MAAM,aAAa,GAAG,MAAM,MAAM,CAAC;AAEzC,4DAA4D;AAC5D,eAAO,MAAM,sBAAsB,EAAE,aAAwC,CAAC;AAE9E;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,gFAAgF;IAChF,QAAQ,CAAC,WAAW,EAAE,8BAA8B,GAAG,IAAI,CAAC;IAC5D,2EAA2E;IAC3E,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,yFAAyF;IACzF,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,GAAG,IAAI,
|
|
1
|
+
{"version":3,"file":"transaction-sql.d.ts","sourceRoot":"","sources":["../src/transaction-sql.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAG3E,oEAAoE;AACpE,eAAO,MAAM,mBAAmB,EAAE,QAAQ,CAAC,MAAM,CAAC,cAAc,EAAE,MAAM,CAAC,CAIvE,CAAC;AAEH,+EAA+E;AAC/E,wBAAgB,cAAc,CAAC,MAAM,EAAE;IAAE,cAAc,CAAC,EAAE,cAAc,CAAA;CAAE,GAAG,MAAM,CAKlF;AAED;;;;;;;GAOG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAU7E;AAID,+EAA+E;AAC/E,MAAM,MAAM,qBAAqB,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC;AAK5D;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,6BAA6B,CAAC,MAAM,EAAE;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,qBAAqB,CAI7F;AAID;;;;;;;;;GASG;AACH,wBAAgB,8BAA8B,CAAC,MAAM,EAAE;IACrD,OAAO,CAAC,EAAE,kBAAkB,CAAC;IAC7B,QAAQ,EAAE,MAAM,CAAC;CAClB,GAAG,IAAI,CAoBP"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vibeorm/adapter-pg",
|
|
3
|
-
"version": "2.0.0
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "node-postgres adapter for VibeORM v2 — Bun or Node.js",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"orm",
|
|
@@ -43,8 +43,8 @@
|
|
|
43
43
|
"bun": ">=1.2.0"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@vibeorm/runtime": "2.0.0
|
|
47
|
-
"@vibeorm/schema": "2.0.0
|
|
46
|
+
"@vibeorm/runtime": "2.0.0",
|
|
47
|
+
"@vibeorm/schema": "2.0.0"
|
|
48
48
|
},
|
|
49
49
|
"peerDependencies": {
|
|
50
50
|
"pg": ">=8"
|