@happyvertical/sql 0.116.0 → 0.116.1
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 +5 -0
- package/dist/chunks/{duckdb-_d9aSOht.js → duckdb-ddmnqn5l.js} +2 -2
- package/dist/chunks/{duckdb-_d9aSOht.js.map → duckdb-ddmnqn5l.js.map} +1 -1
- package/dist/chunks/postgres-dbGVT9aR.js +610 -0
- package/dist/chunks/postgres-dbGVT9aR.js.map +1 -0
- package/dist/chunks/{postgres-dialect-CevaHPBb.js → postgres-dialect-uyqX-KB-.js} +3 -413
- package/dist/chunks/postgres-dialect-uyqX-KB-.js.map +1 -0
- package/dist/chunks/{sqlite-4D5RuZT0.js → sqlite-DQXS8fAo.js} +6 -9
- package/dist/chunks/sqlite-DQXS8fAo.js.map +1 -0
- package/dist/chunks/{sqlite-engine-BLAv3Esk.js → sqlite-engine-DpcUbF-P.js} +2 -2
- package/dist/chunks/{sqlite-engine-BLAv3Esk.js.map → sqlite-engine-DpcUbF-P.js.map} +1 -1
- package/dist/chunks/{sqlite-native-Bqs856IC.js → sqlite-native-BJcrl8b4.js} +3 -3
- package/dist/chunks/{sqlite-native-Bqs856IC.js.map → sqlite-native-BJcrl8b4.js.map} +1 -1
- package/dist/chunks/transaction-lock-BX2GJ4ei.js +415 -0
- package/dist/chunks/transaction-lock-BX2GJ4ei.js.map +1 -0
- package/dist/index.d.ts +8 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +16 -613
- package/dist/index.js.map +1 -1
- package/dist/pglite.js +2 -1
- package/dist/pglite.js.map +1 -1
- package/dist/sqlite.d.ts.map +1 -1
- package/package.json +2 -2
- package/dist/chunks/postgres-dialect-CevaHPBb.js.map +0 -1
- package/dist/chunks/sqlite-4D5RuZT0.js.map +0 -1
|
@@ -0,0 +1,610 @@
|
|
|
1
|
+
import { i as DatabaseSchemaManager, p as wrapDatabaseError } from "./types-DihIt7ez.js";
|
|
2
|
+
import { i as ConnectionCache, o as validateDatabaseCacheOptions } from "./transaction-lock-BX2GJ4ei.js";
|
|
3
|
+
import { a as normalizePostgresRawQuery, i as createVectorCapabilities, n as createPostgresDialect, r as createTransactionErrorTracker, t as createAlterTable } from "./postgres-dialect-uyqX-KB-.js";
|
|
4
|
+
import { DatabaseError } from "@happyvertical/utils";
|
|
5
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6
|
+
import { webcrypto } from "node:crypto";
|
|
7
|
+
import { DatabaseError as DatabaseError$1, Pool } from "pg";
|
|
8
|
+
//#region src/postgres.ts
|
|
9
|
+
/** Default pool size of a reopened PostgreSQL connection. */
|
|
10
|
+
var REOPEN_POOL_MAX = 5;
|
|
11
|
+
var MAX_TIMER_DELAY_MILLIS = 2147483647;
|
|
12
|
+
globalThis.__haveSqlPostgresConnectionCache ??= new ConnectionCache();
|
|
13
|
+
var connectionCache = globalThis.__haveSqlPostgresConnectionCache;
|
|
14
|
+
/**
|
|
15
|
+
* Returns the process-local cache identity HMAC key, generating it on first
|
|
16
|
+
* use. Generating it at import would leave a WebCrypto key job in flight in
|
|
17
|
+
* every isolate that loads the package, and Node aborts the whole process when
|
|
18
|
+
* a worker thread is terminated while such a job completes (#1518).
|
|
19
|
+
*
|
|
20
|
+
* Concurrent first callers share one pending promise. The promise lives on
|
|
21
|
+
* `globalThis` so every copy of this module in an isolate derives the same
|
|
22
|
+
* cache identities. A rejected generation is dropped so the next call retries.
|
|
23
|
+
*/
|
|
24
|
+
function getPostgresCacheHmacKey() {
|
|
25
|
+
const existing = globalThis.__haveSqlPostgresCacheHmacKey;
|
|
26
|
+
if (existing) return existing;
|
|
27
|
+
let pending;
|
|
28
|
+
try {
|
|
29
|
+
pending = webcrypto.subtle.generateKey({
|
|
30
|
+
name: "HMAC",
|
|
31
|
+
hash: "SHA-256"
|
|
32
|
+
}, false, ["sign"]);
|
|
33
|
+
} catch (error) {
|
|
34
|
+
pending = Promise.reject(error);
|
|
35
|
+
}
|
|
36
|
+
globalThis.__haveSqlPostgresCacheHmacKey = pending;
|
|
37
|
+
pending.catch(() => {
|
|
38
|
+
if (globalThis.__haveSqlPostgresCacheHmacKey === pending) globalThis.__haveSqlPostgresCacheHmacKey = void 0;
|
|
39
|
+
});
|
|
40
|
+
return pending;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Clears the PostgreSQL connection cache.
|
|
44
|
+
* Useful for test isolation and reconnection scenarios.
|
|
45
|
+
*/
|
|
46
|
+
async function clearPostgresConnectionCache() {
|
|
47
|
+
await connectionCache.clear(closePostgresDatabase);
|
|
48
|
+
}
|
|
49
|
+
async function closePostgresDatabase(db) {
|
|
50
|
+
if (db.close) {
|
|
51
|
+
await db.close();
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
await db.client.end();
|
|
55
|
+
}
|
|
56
|
+
function resolvePostgresConfig(options) {
|
|
57
|
+
const preferred = (option, environment) => option !== void 0 ? option : environment;
|
|
58
|
+
const envPort = process.env.HAVE_SQL_PORT;
|
|
59
|
+
const primary = {
|
|
60
|
+
url: preferred(options.url, process.env.HAVE_SQL_URL),
|
|
61
|
+
database: preferred(options.database, process.env.HAVE_SQL_DATABASE),
|
|
62
|
+
host: preferred(options.host, process.env.HAVE_SQL_HOST),
|
|
63
|
+
user: preferred(options.user, process.env.HAVE_SQL_USER),
|
|
64
|
+
password: preferred(options.password, process.env.HAVE_SQL_PASSWORD),
|
|
65
|
+
port: preferred(options.port, envPort === void 0 ? void 0 : Number(envPort))
|
|
66
|
+
};
|
|
67
|
+
const useLegacy = !primary.url && !primary.host && !primary.database && !primary.user;
|
|
68
|
+
const legacy = (value, environment) => value !== void 0 || !useLegacy ? value : environment;
|
|
69
|
+
const legacyPort = process.env.SQLOO_PORT;
|
|
70
|
+
const port = legacy(primary.port, legacyPort === void 0 ? void 0 : Number(legacyPort)) ?? 5432;
|
|
71
|
+
const max = options.max ?? 20;
|
|
72
|
+
const { connectionTimeoutMillis, idleTimeoutMillis } = options;
|
|
73
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("PostgreSQL port must be an integer between 1 and 65535");
|
|
74
|
+
if (!Number.isInteger(max) || max < 1) throw new Error("PostgreSQL pool max must be a positive integer");
|
|
75
|
+
if (connectionTimeoutMillis !== void 0 && (!Number.isInteger(connectionTimeoutMillis) || connectionTimeoutMillis < 0 || connectionTimeoutMillis > MAX_TIMER_DELAY_MILLIS)) throw new Error(`PostgreSQL pool connectionTimeoutMillis must be an integer between 0 and ${MAX_TIMER_DELAY_MILLIS}`);
|
|
76
|
+
if (idleTimeoutMillis !== void 0 && (!Number.isInteger(idleTimeoutMillis) || idleTimeoutMillis < 0 || idleTimeoutMillis > MAX_TIMER_DELAY_MILLIS)) throw new Error(`PostgreSQL pool idleTimeoutMillis must be an integer between 0 and ${MAX_TIMER_DELAY_MILLIS}`);
|
|
77
|
+
return {
|
|
78
|
+
url: legacy(primary.url, process.env.SQLOO_URL),
|
|
79
|
+
database: legacy(primary.database, process.env.SQLOO_DATABASE),
|
|
80
|
+
host: legacy(primary.host, process.env.SQLOO_HOST),
|
|
81
|
+
user: legacy(primary.user, process.env.SQLOO_USER),
|
|
82
|
+
password: legacy(primary.password, process.env.SQLOO_PASSWORD),
|
|
83
|
+
port,
|
|
84
|
+
max,
|
|
85
|
+
connectionTimeoutMillis,
|
|
86
|
+
idleTimeoutMillis
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
async function derivePostgresConnectionCacheKey(options, effective) {
|
|
90
|
+
if (options.dbid) return options.dbid;
|
|
91
|
+
const identity = JSON.stringify({
|
|
92
|
+
url: effective.url ?? null,
|
|
93
|
+
host: effective.host ?? "localhost",
|
|
94
|
+
port: effective.port,
|
|
95
|
+
database: effective.database ?? null,
|
|
96
|
+
user: effective.user ?? null,
|
|
97
|
+
password: effective.password ?? null,
|
|
98
|
+
max: effective.max,
|
|
99
|
+
connectionTimeoutMillis: effective.connectionTimeoutMillis ?? null,
|
|
100
|
+
idleTimeoutMillis: effective.idleTimeoutMillis ?? null
|
|
101
|
+
});
|
|
102
|
+
const hmacKey = await getPostgresCacheHmacKey();
|
|
103
|
+
const signature = await webcrypto.subtle.sign("HMAC", hmacKey, new TextEncoder().encode(`@happyvertical/sql:postgres-cache:v1\0${identity}`));
|
|
104
|
+
return `pg:hmac-sha256:v1:${Buffer.from(signature).toString("hex")}`;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Creates a PostgreSQL database adapter
|
|
108
|
+
*
|
|
109
|
+
* Loads configuration from environment variables with backward compatibility:
|
|
110
|
+
* - First checks HAVE_SQL_* environment variables (new standard)
|
|
111
|
+
* - Falls back to SQLOO_* environment variables (legacy)
|
|
112
|
+
* - User-provided options always take precedence
|
|
113
|
+
*
|
|
114
|
+
* Environment variables:
|
|
115
|
+
* - HAVE_SQL_URL / SQLOO_URL → Connection string (takes precedence)
|
|
116
|
+
* - HAVE_SQL_DATABASE / SQLOO_DATABASE → Database name
|
|
117
|
+
* - HAVE_SQL_HOST / SQLOO_HOST → Host (default: 'localhost')
|
|
118
|
+
* - HAVE_SQL_USER / SQLOO_USER → Username
|
|
119
|
+
* - HAVE_SQL_PASSWORD / SQLOO_PASSWORD → Password
|
|
120
|
+
* - HAVE_SQL_PORT / SQLOO_PORT → Port (default: 5432)
|
|
121
|
+
*
|
|
122
|
+
* @param options - PostgreSQL connection options
|
|
123
|
+
* @returns Database interface for PostgreSQL
|
|
124
|
+
*/
|
|
125
|
+
async function getDatabase(options = {}) {
|
|
126
|
+
validateDatabaseCacheOptions(options);
|
|
127
|
+
const effective = resolvePostgresConfig(options);
|
|
128
|
+
const cacheKey = await derivePostgresConnectionCacheKey(options, effective);
|
|
129
|
+
return connectionCache.getOrCreate(cacheKey, options, () => createDatabase(effective), closePostgresDatabase);
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Internal: creates the actual database connection and caches it.
|
|
133
|
+
*/
|
|
134
|
+
async function createDatabase(config) {
|
|
135
|
+
const { database, host = "localhost", user, password, port = 5432 } = config;
|
|
136
|
+
const url = config.url || `postgresql://${user}${password ? `:${password}` : ""}@${host}:${port}/${database || "postgres"}`;
|
|
137
|
+
const reopenOptions = () => {
|
|
138
|
+
return {
|
|
139
|
+
...Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0)),
|
|
140
|
+
type: "postgres",
|
|
141
|
+
cache: false,
|
|
142
|
+
max: Math.min(config.max, REOPEN_POOL_MAX)
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
const { max: poolMax, connectionTimeoutMillis, idleTimeoutMillis } = config;
|
|
146
|
+
const pool = new Pool(config.url ? {
|
|
147
|
+
connectionString: config.url,
|
|
148
|
+
max: poolMax,
|
|
149
|
+
connectionTimeoutMillis,
|
|
150
|
+
idleTimeoutMillis
|
|
151
|
+
} : {
|
|
152
|
+
host,
|
|
153
|
+
user,
|
|
154
|
+
password,
|
|
155
|
+
port,
|
|
156
|
+
database,
|
|
157
|
+
max: poolMax,
|
|
158
|
+
connectionTimeoutMillis,
|
|
159
|
+
idleTimeoutMillis
|
|
160
|
+
});
|
|
161
|
+
pool.on("error", (error) => {
|
|
162
|
+
console.warn("Warning: PostgreSQL pool client error (connection discarded):", error instanceof Error ? error.message : String(error));
|
|
163
|
+
});
|
|
164
|
+
const originalEnd = pool.end.bind(pool);
|
|
165
|
+
let db;
|
|
166
|
+
let endPromise;
|
|
167
|
+
const evictFromCache = () => connectionCache.forget(db);
|
|
168
|
+
pool.end = (callback) => {
|
|
169
|
+
if (!endPromise) {
|
|
170
|
+
evictFromCache();
|
|
171
|
+
endPromise = originalEnd();
|
|
172
|
+
}
|
|
173
|
+
if (callback) {
|
|
174
|
+
endPromise.then(() => callback(), (error) => callback(error instanceof Error ? error : new Error(String(error))));
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
return endPromise;
|
|
178
|
+
};
|
|
179
|
+
const client = pool;
|
|
180
|
+
/**
|
|
181
|
+
* Absorbs 'error' events for the clients currently checked out for a
|
|
182
|
+
* transaction, keyed by client so the listener can be removed on release.
|
|
183
|
+
*/
|
|
184
|
+
const txErrorAbsorbers = /* @__PURE__ */ new WeakMap();
|
|
185
|
+
const releasedTxClients = /* @__PURE__ */ new WeakSet();
|
|
186
|
+
/**
|
|
187
|
+
* Checks out a pooled client for a transaction.
|
|
188
|
+
*
|
|
189
|
+
* pg-pool drops its own idle 'error' listener while a client is checked out,
|
|
190
|
+
* so a backend that dies mid-transaction would emit an unhandled 'error' and
|
|
191
|
+
* terminate the process. Absorb it here — the failure still reaches the
|
|
192
|
+
* caller as a rejected query — and drop the listener again on release so
|
|
193
|
+
* repeated checkouts of the same client cannot accumulate them.
|
|
194
|
+
*/
|
|
195
|
+
const acquireTxClient = async () => {
|
|
196
|
+
const txClient = await client.connect();
|
|
197
|
+
releasedTxClients.delete(txClient);
|
|
198
|
+
const absorb = () => {};
|
|
199
|
+
txClient.on("error", absorb);
|
|
200
|
+
txErrorAbsorbers.set(txClient, absorb);
|
|
201
|
+
return txClient;
|
|
202
|
+
};
|
|
203
|
+
/**
|
|
204
|
+
* Returns a transaction client to the pool exactly once.
|
|
205
|
+
*
|
|
206
|
+
* Every teardown path must run this, including the ones reached by a throwing
|
|
207
|
+
* COMMIT or ROLLBACK — a client that is never released stays checked out for
|
|
208
|
+
* the life of the process, and enough of them exhaust the pool. Releasing
|
|
209
|
+
* twice throws, so the released clients are tracked rather than assumed.
|
|
210
|
+
*
|
|
211
|
+
* @param txClient - The pooled client backing a transaction
|
|
212
|
+
* @param destroy - Destroy the connection instead of reusing it, for when the
|
|
213
|
+
* transaction state could not be cleaned up
|
|
214
|
+
*/
|
|
215
|
+
const releaseTxClient = (txClient, destroy = false) => {
|
|
216
|
+
if (releasedTxClients.has(txClient)) return;
|
|
217
|
+
releasedTxClients.add(txClient);
|
|
218
|
+
const absorb = txErrorAbsorbers.get(txClient);
|
|
219
|
+
if (absorb) {
|
|
220
|
+
txClient.off("error", absorb);
|
|
221
|
+
txErrorAbsorbers.delete(txClient);
|
|
222
|
+
}
|
|
223
|
+
txClient.release(destroy || void 0);
|
|
224
|
+
};
|
|
225
|
+
/**
|
|
226
|
+
* Rolls back a failed transaction and returns its client to the pool.
|
|
227
|
+
*
|
|
228
|
+
* The connection may still be inside a transaction, so ROLLBACK is attempted
|
|
229
|
+
* to normalize it. If that works the connection is clean and worth reusing;
|
|
230
|
+
* if it does not, the state is unknown and the connection is destroyed rather
|
|
231
|
+
* than handed to unrelated code later.
|
|
232
|
+
*
|
|
233
|
+
* @returns The rollback failure, if the connection could not be normalized
|
|
234
|
+
*/
|
|
235
|
+
const discardTxClient = async (txClient) => {
|
|
236
|
+
try {
|
|
237
|
+
await txClient.query("ROLLBACK");
|
|
238
|
+
releaseTxClient(txClient);
|
|
239
|
+
return;
|
|
240
|
+
} catch (rollbackError) {
|
|
241
|
+
releaseTxClient(txClient, true);
|
|
242
|
+
return rollbackError;
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
/**
|
|
246
|
+
* Keeps the first PostgreSQL statement failure attached to a transaction.
|
|
247
|
+
*
|
|
248
|
+
* PostgreSQL reports every later statement in an aborted transaction as
|
|
249
|
+
* 25P02. Replacing the first failure with that generic state error hides the
|
|
250
|
+
* actionable code and diagnostics from callers. The scoped executor instead
|
|
251
|
+
* rethrows the first failure whenever PostgreSQL reports 25P02, and exposes
|
|
252
|
+
* the recorded failure so a swallowed statement error cannot make COMMIT's
|
|
253
|
+
* implicit rollback look successful.
|
|
254
|
+
*/
|
|
255
|
+
const createTransactionExecutor = (txClient) => {
|
|
256
|
+
const tracker = createTransactionErrorTracker((error) => error instanceof DatabaseError$1);
|
|
257
|
+
const { pending, preserve: preserveFirstError } = tracker;
|
|
258
|
+
return {
|
|
259
|
+
client: new Proxy(txClient, { get(target, property) {
|
|
260
|
+
if (property === "query") return (...args) => {
|
|
261
|
+
const query = args[0];
|
|
262
|
+
const callbackIndex = typeof args.at(-1) === "function" ? args.length - 1 : -1;
|
|
263
|
+
if (typeof query === "object" && query !== null && "submit" in query && typeof query.submit === "function") {
|
|
264
|
+
if (!("handleError" in query) || typeof query.handleError !== "function" || !("handleReadyForQuery" in query) || typeof query.handleReadyForQuery !== "function") return Reflect.apply(target.query, target, args);
|
|
265
|
+
const handleError = query.handleError;
|
|
266
|
+
const handleReadyForQuery = query.handleReadyForQuery;
|
|
267
|
+
let complete;
|
|
268
|
+
const completion = new Promise((resolve) => {
|
|
269
|
+
complete = resolve;
|
|
270
|
+
});
|
|
271
|
+
let completed = false;
|
|
272
|
+
const finish = () => {
|
|
273
|
+
if (completed) return;
|
|
274
|
+
completed = true;
|
|
275
|
+
query.handleError = handleError;
|
|
276
|
+
query.handleReadyForQuery = handleReadyForQuery;
|
|
277
|
+
pending.delete(completion);
|
|
278
|
+
complete();
|
|
279
|
+
};
|
|
280
|
+
pending.add(completion);
|
|
281
|
+
query.handleError = function(...handlerArgs) {
|
|
282
|
+
const error = preserveFirstError(handlerArgs[0]);
|
|
283
|
+
try {
|
|
284
|
+
return Reflect.apply(handleError, this, [error, ...handlerArgs.slice(1)]);
|
|
285
|
+
} finally {
|
|
286
|
+
finish();
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
query.handleReadyForQuery = function(...handlerArgs) {
|
|
290
|
+
try {
|
|
291
|
+
const result = Reflect.apply(handleReadyForQuery, this, handlerArgs);
|
|
292
|
+
tracker.confirm(query);
|
|
293
|
+
return result;
|
|
294
|
+
} finally {
|
|
295
|
+
finish();
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
try {
|
|
299
|
+
return Reflect.apply(target.query, target, args);
|
|
300
|
+
} catch (error) {
|
|
301
|
+
finish();
|
|
302
|
+
throw preserveFirstError(error);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
if (callbackIndex !== -1) {
|
|
306
|
+
const callback = args[callbackIndex];
|
|
307
|
+
let complete;
|
|
308
|
+
const completion = new Promise((resolve) => {
|
|
309
|
+
complete = resolve;
|
|
310
|
+
});
|
|
311
|
+
pending.add(completion);
|
|
312
|
+
args[callbackIndex] = (error, result) => {
|
|
313
|
+
const callbackError = error === null || error === void 0 ? error : preserveFirstError(error);
|
|
314
|
+
if (callbackError === null || callbackError === void 0) tracker.confirm(query);
|
|
315
|
+
pending.delete(completion);
|
|
316
|
+
complete();
|
|
317
|
+
callback(callbackError, result);
|
|
318
|
+
};
|
|
319
|
+
try {
|
|
320
|
+
return Reflect.apply(target.query, target, args);
|
|
321
|
+
} catch (error) {
|
|
322
|
+
pending.delete(completion);
|
|
323
|
+
complete();
|
|
324
|
+
throw preserveFirstError(error);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
const result = Reflect.apply(target.query, target, args);
|
|
328
|
+
if (typeof result === "object" && result !== null && "then" in result && typeof result.then === "function") return tracker.track(Promise.resolve(result), query);
|
|
329
|
+
if (typeof result === "object" && result !== null && "once" in result && typeof result.once === "function") {
|
|
330
|
+
let complete;
|
|
331
|
+
const completion = new Promise((resolve) => {
|
|
332
|
+
complete = resolve;
|
|
333
|
+
});
|
|
334
|
+
const finish = () => {
|
|
335
|
+
pending.delete(completion);
|
|
336
|
+
complete();
|
|
337
|
+
};
|
|
338
|
+
pending.add(completion);
|
|
339
|
+
result.once("error", (error) => {
|
|
340
|
+
preserveFirstError(error);
|
|
341
|
+
finish();
|
|
342
|
+
});
|
|
343
|
+
result.once("end", () => {
|
|
344
|
+
tracker.confirm(query);
|
|
345
|
+
finish();
|
|
346
|
+
});
|
|
347
|
+
result.once("close", finish);
|
|
348
|
+
}
|
|
349
|
+
return result;
|
|
350
|
+
};
|
|
351
|
+
return Reflect.get(target, property, target);
|
|
352
|
+
} }),
|
|
353
|
+
executor: { query: (sql, values) => tracker.track(txClient.query(sql, values), sql) },
|
|
354
|
+
clearError: tracker.clearError,
|
|
355
|
+
drain: tracker.drain,
|
|
356
|
+
getError: tracker.getError,
|
|
357
|
+
getUnconfirmedError: tracker.getUnconfirmedError
|
|
358
|
+
};
|
|
359
|
+
};
|
|
360
|
+
const assertCommitted = (result, transactionState) => {
|
|
361
|
+
if (result.command === "COMMIT") return;
|
|
362
|
+
const queryError = transactionState?.getError() ?? transactionState?.getUnconfirmedError();
|
|
363
|
+
if (queryError !== void 0) throw queryError;
|
|
364
|
+
throw new DatabaseError("PostgreSQL rolled back the transaction at commit", { command: result.command });
|
|
365
|
+
};
|
|
366
|
+
const { serializeRecord, createClientMethods, createNestedTransaction } = createPostgresDialect({
|
|
367
|
+
client,
|
|
368
|
+
probeExecutor: () => client,
|
|
369
|
+
runInTransaction: async (work) => {
|
|
370
|
+
const txClient = await acquireTxClient();
|
|
371
|
+
try {
|
|
372
|
+
await txClient.query("BEGIN");
|
|
373
|
+
const result = await work(txClient);
|
|
374
|
+
const commitResult = await txClient.query("COMMIT");
|
|
375
|
+
assertCommitted(commitResult);
|
|
376
|
+
releaseTxClient(txClient);
|
|
377
|
+
return result;
|
|
378
|
+
} catch (error) {
|
|
379
|
+
const rollbackError = await discardTxClient(txClient);
|
|
380
|
+
if (rollbackError !== void 0 && error instanceof Error) error.cause ??= rollbackError;
|
|
381
|
+
throw error;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
});
|
|
385
|
+
const { insert, get, list, update, upsert, getOrInsert, delete: deleteRecords, count, table, many, single, pluck, execute, query, oo, oO, ox, xx, tableExists, getTableSchema, syncSchema } = createClientMethods(client, false, serializeRecord);
|
|
386
|
+
const alterTable = createAlterTable(client);
|
|
387
|
+
/**
|
|
388
|
+
* Acquire a pinned connection from the pool for session-scoped state such as
|
|
389
|
+
* `pg_advisory_lock`. Every query on the returned handle runs on the same
|
|
390
|
+
* client until {@link SessionHandle.release} drops the connection (which
|
|
391
|
+
* frees any session locks it held). The connection is held for the handle's
|
|
392
|
+
* lifetime, so hold one session per process, not per operation.
|
|
393
|
+
*/
|
|
394
|
+
const acquireSession = async () => {
|
|
395
|
+
const sessionClient = await pool.connect();
|
|
396
|
+
let released = false;
|
|
397
|
+
let lost = false;
|
|
398
|
+
sessionClient.on("error", () => {
|
|
399
|
+
lost = true;
|
|
400
|
+
});
|
|
401
|
+
return {
|
|
402
|
+
query: async (sql, ...values) => {
|
|
403
|
+
if (released) throw new DatabaseError("Session has been released", {});
|
|
404
|
+
if (lost) throw new DatabaseError("Session connection was lost", {});
|
|
405
|
+
const normalized = normalizePostgresRawQuery(sql, values);
|
|
406
|
+
try {
|
|
407
|
+
const result = await sessionClient.query(normalized.sql, normalized.values);
|
|
408
|
+
return {
|
|
409
|
+
rows: result.rows,
|
|
410
|
+
rowCount: result.rowCount ?? 0
|
|
411
|
+
};
|
|
412
|
+
} catch (e) {
|
|
413
|
+
throw wrapDatabaseError("Failed to execute session query", e, {
|
|
414
|
+
sql: normalized.sql,
|
|
415
|
+
values: normalized.values
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
},
|
|
419
|
+
isActive: () => !released && !lost,
|
|
420
|
+
release: async () => {
|
|
421
|
+
if (released) return;
|
|
422
|
+
released = true;
|
|
423
|
+
if (!lost) {
|
|
424
|
+
try {
|
|
425
|
+
await sessionClient.query("ROLLBACK");
|
|
426
|
+
} catch {}
|
|
427
|
+
try {
|
|
428
|
+
await sessionClient.query("SELECT pg_advisory_unlock_all()");
|
|
429
|
+
} catch {}
|
|
430
|
+
}
|
|
431
|
+
sessionClient.release(true);
|
|
432
|
+
}
|
|
433
|
+
};
|
|
434
|
+
};
|
|
435
|
+
/**
|
|
436
|
+
* Executes a callback within a database transaction
|
|
437
|
+
* Automatically commits on success or rolls back on error
|
|
438
|
+
*
|
|
439
|
+
* @param callback - Function to execute within transaction
|
|
440
|
+
* @returns Promise resolving to callback result
|
|
441
|
+
*/
|
|
442
|
+
const transaction = async (callback) => {
|
|
443
|
+
const txClient = await acquireTxClient();
|
|
444
|
+
let nestedTransaction;
|
|
445
|
+
const transactionState = createTransactionExecutor(txClient);
|
|
446
|
+
try {
|
|
447
|
+
await txClient.query("BEGIN");
|
|
448
|
+
let txDb;
|
|
449
|
+
nestedTransaction = createNestedTransaction(transactionState.executor, () => txDb, transactionState.clearError, new AsyncLocalStorage());
|
|
450
|
+
txDb = {
|
|
451
|
+
url,
|
|
452
|
+
engine: "postgres",
|
|
453
|
+
reopenOptions,
|
|
454
|
+
client: transactionState.client,
|
|
455
|
+
...createClientMethods(transactionState.executor, true, serializeRecord, transactionState.clearError),
|
|
456
|
+
transaction: nestedTransaction
|
|
457
|
+
};
|
|
458
|
+
const result = await callback(txDb);
|
|
459
|
+
await nestedTransaction.drain();
|
|
460
|
+
await transactionState.drain();
|
|
461
|
+
const statementError = transactionState.getError();
|
|
462
|
+
if (statementError !== void 0) throw statementError;
|
|
463
|
+
const commitResult = await txClient.query("COMMIT");
|
|
464
|
+
assertCommitted(commitResult, transactionState);
|
|
465
|
+
releaseTxClient(txClient);
|
|
466
|
+
return result;
|
|
467
|
+
} catch (error) {
|
|
468
|
+
await nestedTransaction?.drain();
|
|
469
|
+
await transactionState.drain();
|
|
470
|
+
const rollbackError = await discardTxClient(txClient);
|
|
471
|
+
if (rollbackError !== void 0 && error instanceof Error) error.cause ??= rollbackError;
|
|
472
|
+
throw error;
|
|
473
|
+
}
|
|
474
|
+
};
|
|
475
|
+
/**
|
|
476
|
+
* Begins a new transaction and returns a handle for manual control
|
|
477
|
+
*
|
|
478
|
+
* Unlike transaction(), this gives you explicit control over commit/rollback.
|
|
479
|
+
* Ideal for test isolation where you want to rollback after each test.
|
|
480
|
+
*
|
|
481
|
+
* @returns Promise resolving to a TransactionHandle
|
|
482
|
+
*/
|
|
483
|
+
const beginTransaction = async () => {
|
|
484
|
+
const txClient = await acquireTxClient();
|
|
485
|
+
try {
|
|
486
|
+
await txClient.query("BEGIN");
|
|
487
|
+
} catch (error) {
|
|
488
|
+
releaseTxClient(txClient, true);
|
|
489
|
+
throw error;
|
|
490
|
+
}
|
|
491
|
+
let active = true;
|
|
492
|
+
let nestedTransaction;
|
|
493
|
+
const transactionState = createTransactionExecutor(txClient);
|
|
494
|
+
const end = async (command) => {
|
|
495
|
+
if (!active) throw new DatabaseError("Transaction already ended", {});
|
|
496
|
+
try {
|
|
497
|
+
await nestedTransaction?.drain();
|
|
498
|
+
await transactionState.drain();
|
|
499
|
+
const statementError = transactionState.getError();
|
|
500
|
+
if (command === "COMMIT" && statementError !== void 0) throw statementError;
|
|
501
|
+
const result = await txClient.query(command);
|
|
502
|
+
if (command === "COMMIT") assertCommitted(result, transactionState);
|
|
503
|
+
active = false;
|
|
504
|
+
releaseTxClient(txClient);
|
|
505
|
+
} catch (error) {
|
|
506
|
+
active = false;
|
|
507
|
+
const rollbackError = await discardTxClient(txClient);
|
|
508
|
+
if (rollbackError !== void 0 && error instanceof Error) error.cause ??= rollbackError;
|
|
509
|
+
throw error;
|
|
510
|
+
}
|
|
511
|
+
};
|
|
512
|
+
const commit = () => end("COMMIT");
|
|
513
|
+
const rollback = () => end("ROLLBACK");
|
|
514
|
+
const isActive = () => active;
|
|
515
|
+
let txHandle;
|
|
516
|
+
nestedTransaction = createNestedTransaction(transactionState.executor, () => txHandle, transactionState.clearError, new AsyncLocalStorage());
|
|
517
|
+
txHandle = {
|
|
518
|
+
url,
|
|
519
|
+
engine: "postgres",
|
|
520
|
+
reopenOptions,
|
|
521
|
+
client: transactionState.client,
|
|
522
|
+
...createClientMethods(transactionState.executor, true, serializeRecord, transactionState.clearError),
|
|
523
|
+
transaction: nestedTransaction,
|
|
524
|
+
commit,
|
|
525
|
+
rollback,
|
|
526
|
+
isActive
|
|
527
|
+
};
|
|
528
|
+
return txHandle;
|
|
529
|
+
};
|
|
530
|
+
/**
|
|
531
|
+
* Initialize database schemas from JSON manifest
|
|
532
|
+
* Supports dependency resolution and schema overrides
|
|
533
|
+
*
|
|
534
|
+
* @param options - Schema initialization options
|
|
535
|
+
* @returns Promise that resolves when schemas are initialized
|
|
536
|
+
*/
|
|
537
|
+
const initializeSchemas = async (options) => {
|
|
538
|
+
const schemaManager = new DatabaseSchemaManager();
|
|
539
|
+
const currentDb = {
|
|
540
|
+
url,
|
|
541
|
+
engine: "postgres",
|
|
542
|
+
reopenOptions,
|
|
543
|
+
client,
|
|
544
|
+
insert,
|
|
545
|
+
update,
|
|
546
|
+
upsert,
|
|
547
|
+
get,
|
|
548
|
+
getOrInsert,
|
|
549
|
+
delete: deleteRecords,
|
|
550
|
+
count,
|
|
551
|
+
list,
|
|
552
|
+
table,
|
|
553
|
+
many,
|
|
554
|
+
single,
|
|
555
|
+
pluck,
|
|
556
|
+
execute,
|
|
557
|
+
query,
|
|
558
|
+
oo,
|
|
559
|
+
oO,
|
|
560
|
+
ox,
|
|
561
|
+
xx,
|
|
562
|
+
tableExists,
|
|
563
|
+
getTableSchema,
|
|
564
|
+
syncSchema,
|
|
565
|
+
transaction
|
|
566
|
+
};
|
|
567
|
+
await schemaManager.initializeSchemas(currentDb, options);
|
|
568
|
+
};
|
|
569
|
+
db = {
|
|
570
|
+
url,
|
|
571
|
+
engine: "postgres",
|
|
572
|
+
reopenOptions,
|
|
573
|
+
client,
|
|
574
|
+
insert,
|
|
575
|
+
update,
|
|
576
|
+
upsert,
|
|
577
|
+
get,
|
|
578
|
+
getOrInsert,
|
|
579
|
+
delete: deleteRecords,
|
|
580
|
+
count,
|
|
581
|
+
list,
|
|
582
|
+
table,
|
|
583
|
+
many,
|
|
584
|
+
single,
|
|
585
|
+
pluck,
|
|
586
|
+
execute,
|
|
587
|
+
query,
|
|
588
|
+
oo,
|
|
589
|
+
oO,
|
|
590
|
+
ox,
|
|
591
|
+
xx,
|
|
592
|
+
tableExists,
|
|
593
|
+
syncSchema,
|
|
594
|
+
initializeSchemas,
|
|
595
|
+
transaction,
|
|
596
|
+
beginTransaction,
|
|
597
|
+
acquireSession,
|
|
598
|
+
getTableSchema,
|
|
599
|
+
alterTable,
|
|
600
|
+
vector: createVectorCapabilities(pool),
|
|
601
|
+
close: async () => {
|
|
602
|
+
await pool.end();
|
|
603
|
+
}
|
|
604
|
+
};
|
|
605
|
+
return db;
|
|
606
|
+
}
|
|
607
|
+
//#endregion
|
|
608
|
+
export { clearPostgresConnectionCache, getDatabase };
|
|
609
|
+
|
|
610
|
+
//# sourceMappingURL=postgres-dbGVT9aR.js.map
|