@prisma/orm-target-postgres 8.0.0-rc.4-dev.7 → 8.0.0-rc.4-dev.8

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.
@@ -3,6 +3,7 @@ import { ifDefined } from "@prisma/orm-framework/utils/defined";
3
3
  import { SqlQueryError } from "@prisma/orm-family-sql/errors";
4
4
  import { errorRuntime } from "@prisma/orm-framework/errors/execution";
5
5
  import { redactDatabaseUrl } from "@prisma/orm-framework/utils/redact-db-url";
6
+ import { suppressIdleConnectionErrors } from "@prisma/orm-framework/utils/suppress-idle-connection-errors";
6
7
  import { Client } from "pg";
7
8
  //#region ../../../3-targets/7-drivers/postgres/dist/control.mjs
8
9
  var PostgresControlDriver = class {
@@ -33,8 +34,7 @@ var PostgresControlDriver = class {
33
34
  const postgresDriverDescriptor = {
34
35
  ...postgresDriverDescriptorMeta,
35
36
  async create(url) {
36
- const client = new Client({ connectionString: url });
37
- client.on("error", () => {});
37
+ const client = suppressIdleConnectionErrors(new Client({ connectionString: url }));
38
38
  try {
39
39
  await client.connect();
40
40
  return new PostgresControlDriver(client);
@@ -62,4 +62,4 @@ const postgresDriverDescriptor = {
62
62
  //#endregion
63
63
  export { postgresDriverDescriptor as n, PostgresControlDriver as t };
64
64
 
65
- //# sourceMappingURL=control-Y6FxMu3o.mjs.map
65
+ //# sourceMappingURL=control-DzK5mSLo.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"control-DzK5mSLo.mjs","names":[],"sources":["../../../../3-targets/7-drivers/postgres/dist/control.mjs"],"sourcesContent":["import { i as postgresDriverDescriptorMeta, r as normalizePgError } from \"./normalize-error-CNjgVO71.mjs\";\nimport { errorRuntime } from \"@internal/errors/execution\";\nimport { SqlQueryError } from \"@internal/sql-errors\";\nimport { ifDefined } from \"@internal/utils/defined\";\nimport { redactDatabaseUrl } from \"@internal/utils/redact-db-url\";\nimport { suppressIdleConnectionErrors } from \"@internal/utils/suppress-idle-connection-errors\";\nimport { Client } from \"pg\";\n//#region src/exports/control.ts\nvar PostgresControlDriver = class {\n\tclient;\n\tfamilyId = \"sql\";\n\ttargetId = \"postgres\";\n\tconstructor(client) {\n\t\tthis.client = client;\n\t}\n\tasync query(sql, params) {\n\t\ttry {\n\t\t\treturn { rows: (await this.client.query(sql, params)).rows };\n\t\t} catch (error) {\n\t\t\tthrow normalizePgError(error);\n\t\t}\n\t}\n\tasync databaseName() {\n\t\tconst name = (await this.query(\"select current_database() as name\")).rows[0]?.name;\n\t\treturn typeof name === \"string\" && name.length > 0 ? name : void 0;\n\t}\n\tasync close() {\n\t\tawait this.client.end().catch(() => {});\n\t}\n};\n/**\n* Postgres driver descriptor for CLI config.\n*/\nconst postgresDriverDescriptor = {\n\t...postgresDriverDescriptorMeta,\n\tasync create(url) {\n\t\tconst client = suppressIdleConnectionErrors(new Client({ connectionString: url }));\n\t\ttry {\n\t\t\tawait client.connect();\n\t\t\treturn new PostgresControlDriver(client);\n\t\t} catch (error) {\n\t\t\tconst normalized = normalizePgError(error);\n\t\t\tconst redacted = redactDatabaseUrl(url);\n\t\t\ttry {\n\t\t\t\tawait client.end();\n\t\t\t} catch {}\n\t\t\tconst codeFromSqlState = SqlQueryError.is(normalized) ? normalized.sqlState : void 0;\n\t\t\tconst causeCode = \"cause\" in normalized && normalized.cause ? normalized.cause.code : void 0;\n\t\t\tconst sqlState = codeFromSqlState ?? causeCode;\n\t\t\tthrow errorRuntime(\"DRIVER.CONNECTION_FAILED\", \"Database connection failed\", {\n\t\t\t\twhy: normalized.message,\n\t\t\t\tfix: \"Verify the database URL, ensure the database is reachable, and confirm credentials/permissions\",\n\t\t\t\tmeta: {\n\t\t\t\t\t...ifDefined(\"sqlState\", sqlState),\n\t\t\t\t\t...redacted\n\t\t\t\t},\n\t\t\t\tcause: error\n\t\t\t});\n\t\t}\n\t}\n};\n//#endregion\nexport { PostgresControlDriver, postgresDriverDescriptor as default };\n\n//# sourceMappingURL=control.mjs.map"],"mappings":";;;;;;;;AAQA,IAAI,wBAAwB,MAAM;CACjC;CACA,WAAW;CACX,WAAW;CACX,YAAY,QAAQ;EACnB,KAAK,SAAS;CACf;CACA,MAAM,MAAM,KAAK,QAAQ;EACxB,IAAI;GACH,OAAO,EAAE,OAAO,MAAM,KAAK,OAAO,MAAM,KAAK,MAAM,EAAA,CAAG,KAAK;EAC5D,SAAS,OAAO;GACf,MAAM,iBAAiB,KAAK;EAC7B;CACD;CACA,MAAM,eAAe;EACpB,MAAM,QAAQ,MAAM,KAAK,MAAM,mCAAmC,EAAA,CAAG,KAAK,EAAE,EAAE;EAC9E,OAAO,OAAO,SAAS,YAAY,KAAK,SAAS,IAAI,OAAO,KAAK;CAClE;CACA,MAAM,QAAQ;EACb,MAAM,KAAK,OAAO,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC;CACvC;AACD;;;;AAIA,MAAM,2BAA2B;CAChC,GAAG;CACH,MAAM,OAAO,KAAK;EACjB,MAAM,SAAS,6BAA6B,IAAI,OAAO,EAAE,kBAAkB,IAAI,CAAC,CAAC;EACjF,IAAI;GACH,MAAM,OAAO,QAAQ;GACrB,OAAO,IAAI,sBAAsB,MAAM;EACxC,SAAS,OAAO;GACf,MAAM,aAAa,iBAAiB,KAAK;GACzC,MAAM,WAAW,kBAAkB,GAAG;GACtC,IAAI;IACH,MAAM,OAAO,IAAI;GAClB,QAAQ,CAAC;GACT,MAAM,mBAAmB,cAAc,GAAG,UAAU,IAAI,WAAW,WAAW,KAAK;GACnF,MAAM,YAAY,WAAW,cAAc,WAAW,QAAQ,WAAW,MAAM,OAAO,KAAK;GAC3F,MAAM,WAAW,oBAAoB;GACrC,MAAM,aAAa,4BAA4B,8BAA8B;IAC5E,KAAK,WAAW;IAChB,KAAK;IACL,MAAM;KACL,GAAG,UAAU,YAAY,QAAQ;KACjC,GAAG;IACJ;IACA,OAAO;GACR,CAAC;EACF;CACD;AACD"}
package/dist/driver.d.mts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { t as PostgresControlDriver } from "./control-BaUpALVp.mjs";
2
- import { i as QueryResult, n as PostgresDriverCreateOptions, r as PostgresRuntimeDriver, t as PostgresBinding } from "./runtime-lHBKgjB9.mjs";
3
- export { type PostgresBinding, PostgresControlDriver, type PostgresDriverCreateOptions, PostgresRuntimeDriver, type QueryResult };
2
+ import { i as QueryResult, n as PostgresDriverCreateOptions, o as suppressIdleConnectionErrors, r as PostgresRuntimeDriver, t as PostgresBinding } from "./runtime-DtoNQntj.mjs";
3
+ export { type PostgresBinding, PostgresControlDriver, type PostgresDriverCreateOptions, PostgresRuntimeDriver, type QueryResult, suppressIdleConnectionErrors };
package/dist/driver.mjs CHANGED
@@ -1,2 +1,3 @@
1
- import { t as PostgresControlDriver } from "./control-Y6FxMu3o.mjs";
2
- export { PostgresControlDriver };
1
+ import { t as PostgresControlDriver } from "./control-DzK5mSLo.mjs";
2
+ import { n as suppressIdleConnectionErrors } from "./runtime-C-Hh2m1R.mjs";
3
+ export { PostgresControlDriver, suppressIdleConnectionErrors };
@@ -1,2 +1,2 @@
1
- import { n as postgresDriverDescriptor, t as PostgresControlDriver } from "./control-Y6FxMu3o.mjs";
1
+ import { n as postgresDriverDescriptor, t as PostgresControlDriver } from "./control-DzK5mSLo.mjs";
2
2
  export { PostgresControlDriver, postgresDriverDescriptor as default };
@@ -1,2 +1,2 @@
1
- import { a as postgresRuntimeDriverDescriptor, i as QueryResult, n as PostgresDriverCreateOptions, r as PostgresRuntimeDriver, t as PostgresBinding } from "./runtime-lHBKgjB9.mjs";
2
- export { type PostgresBinding, type PostgresDriverCreateOptions, PostgresRuntimeDriver, type QueryResult, postgresRuntimeDriverDescriptor as default };
1
+ import { a as postgresRuntimeDriverDescriptor, i as QueryResult, n as PostgresDriverCreateOptions, o as suppressIdleConnectionErrors, r as PostgresRuntimeDriver, t as PostgresBinding } from "./runtime-DtoNQntj.mjs";
2
+ export { type PostgresBinding, type PostgresDriverCreateOptions, PostgresRuntimeDriver, type QueryResult, postgresRuntimeDriverDescriptor as default, suppressIdleConnectionErrors };
@@ -1,639 +1,2 @@
1
- import { i as postgresDriverDescriptorMeta, n as isPostgresError, r as normalizePgError, t as isAlreadyConnectedError } from "./normalize-error-CNjgVO71-CLlZ3CuJ.mjs";
2
- import { blindCast } from "@prisma/orm-framework/utils/casts";
3
- import { Pool } from "pg";
4
- import Cursor from "pg-cursor";
5
- //#region ../../../3-targets/7-drivers/postgres/dist/runtime.mjs
6
- function driverError(code, message, details) {
7
- const error = new Error(message);
8
- Object.defineProperty(error, "name", {
9
- value: "RuntimeError",
10
- configurable: true
11
- });
12
- return details === void 0 ? Object.assign(error, {
13
- code,
14
- category: "DRIVER",
15
- severity: "error"
16
- }) : Object.assign(error, {
17
- code,
18
- category: "DRIVER",
19
- severity: "error",
20
- details
21
- });
22
- }
23
- function callbackToPromise(fn) {
24
- return new Promise((resolve, reject) => {
25
- fn((err, result) => {
26
- if (err) {
27
- reject(err);
28
- return;
29
- }
30
- resolve(result);
31
- });
32
- });
33
- }
34
- let nextNamedPortalId = 1;
35
- /** Streaming cursor for a server-side named prepared statement. */
36
- var NamedCursor = class extends Cursor {
37
- name;
38
- constructor(opts) {
39
- super(opts.text, [...opts.values], opts.config);
40
- this.name = opts.name;
41
- this.submit = this.submitNamed;
42
- }
43
- submitNamed(connection) {
44
- const self = this;
45
- const conn = connection;
46
- self.state = "submitted";
47
- self.connection = conn;
48
- self._portal = `np_${nextNamedPortalId++}`;
49
- if (!conn.parsedStatements[this.name]) {
50
- const parseMessage = {
51
- text: self.text,
52
- name: this.name,
53
- types: []
54
- };
55
- conn.parse(parseMessage, true);
56
- }
57
- const bindMessage = {
58
- portal: self._portal,
59
- statement: this.name,
60
- values: self.values ?? []
61
- };
62
- conn.bind(bindMessage, true);
63
- conn.describe({
64
- type: "P",
65
- name: self._portal
66
- }, true);
67
- conn.flush();
68
- if (self._conf.types) self._result._getTypeParser = self._conf.types.getTypeParser;
69
- conn.once("noData", self._ifNoData);
70
- conn.once("rowDescription", self._rowDescription);
71
- }
72
- };
73
- const DEFAULT_BATCH_SIZE = 100;
74
- const DEFAULT_PREPARED_STATEMENTS = true;
75
- function createHandleAllocator() {
76
- let next = 1;
77
- return { mint: () => `pn_${next++}` };
78
- }
79
- function buildConnectionOptions(options) {
80
- return {
81
- ...options.cursor?.disabled ? { cursorDisabled: true } : {
82
- cursorBatchSize: options.cursor?.batchSize ?? DEFAULT_BATCH_SIZE,
83
- cursorDisabled: false
84
- },
85
- preparedStatementsEnabled: options.preparedStatements ?? DEFAULT_PREPARED_STATEMENTS,
86
- handleAllocator: createHandleAllocator()
87
- };
88
- }
89
- function isStalePreparedStatementError(error) {
90
- if (!(error instanceof Error) || !("code" in error) || typeof error.code !== "string") return false;
91
- const code = error.code;
92
- return code === "26000" || code === "0A000";
93
- }
94
- var AsyncMutex = class {
95
- #queue = Promise.resolve();
96
- async lock() {
97
- const previous = this.#queue;
98
- let releaseLock;
99
- this.#queue = new Promise((resolve) => {
100
- releaseLock = resolve;
101
- });
102
- await previous;
103
- return () => {
104
- releaseLock?.();
105
- releaseLock = void 0;
106
- };
107
- }
108
- };
109
- const clientQueryLocks = /* @__PURE__ */ new WeakMap();
110
- function acquireClientQueryLock(client) {
111
- let mutex = clientQueryLocks.get(client);
112
- if (mutex === void 0) {
113
- mutex = new AsyncMutex();
114
- clientQueryLocks.set(client, mutex);
115
- }
116
- return mutex.lock();
117
- }
118
- var PostgresQueryable = class {
119
- options;
120
- constructor(options) {
121
- this.options = options;
122
- }
123
- async *query(request) {
124
- try {
125
- const preparedStatementHandle = request.preparedStatementHandle;
126
- if (preparedStatementHandle === void 0 || !this.options.preparedStatementsEnabled) {
127
- yield* this.runQuery(request);
128
- return;
129
- }
130
- const name = this.preparedStatementName(preparedStatementHandle);
131
- yield* this.withStaleHandleStreamRetry(preparedStatementHandle, name, (name) => this.runQuery(request, name));
132
- } catch (error) {
133
- throw normalizePgError(error);
134
- }
135
- }
136
- async execute(request) {
137
- try {
138
- const preparedStatementHandle = request.preparedStatementHandle;
139
- if (preparedStatementHandle === void 0 || !this.options.preparedStatementsEnabled) return await this.runExecute(request);
140
- const name = this.preparedStatementName(preparedStatementHandle);
141
- return await this.withStaleHandleRetry(preparedStatementHandle, name, (name) => this.runExecute(request, name));
142
- } catch (error) {
143
- throw normalizePgError(error);
144
- }
145
- }
146
- preparedStatementName(handle) {
147
- const existingName = handle.get();
148
- if (typeof existingName === "string") return existingName;
149
- const mintedName = this.options.handleAllocator.mint();
150
- handle.set(mintedName);
151
- return mintedName;
152
- }
153
- async withStaleHandleRetry(preparedStatementHandle, name, attempt) {
154
- try {
155
- return await attempt(name);
156
- } catch (error) {
157
- if (!isStalePreparedStatementError(error)) throw error;
158
- const retryName = this.options.handleAllocator.mint();
159
- preparedStatementHandle.set(retryName);
160
- try {
161
- return await attempt(retryName);
162
- } catch (retryError) {
163
- throw prepareFailedError(retryError, retryName);
164
- }
165
- }
166
- }
167
- async *withStaleHandleStreamRetry(preparedStatementHandle, name, attempt) {
168
- const stream = await this.withStaleHandleRetry(preparedStatementHandle, name, async (name) => {
169
- const iterator = attempt(name)[Symbol.asyncIterator]();
170
- return {
171
- iterator,
172
- first: await iterator.next()
173
- };
174
- });
175
- if (stream.first.done) return;
176
- let streamCompleted = false;
177
- try {
178
- yield stream.first.value;
179
- while (true) {
180
- const next = await stream.iterator.next();
181
- if (next.done) {
182
- streamCompleted = true;
183
- return;
184
- }
185
- yield next.value;
186
- }
187
- } finally {
188
- if (!streamCompleted) await stream.iterator.return?.();
189
- }
190
- }
191
- async runExecute(request, name) {
192
- const client = await this.acquireClient();
193
- try {
194
- const releaseLock = await acquireClientQueryLock(client);
195
- try {
196
- return { affectedRows: (await client.query({
197
- name,
198
- text: request.sql,
199
- values: blindCast(request.params ?? [])
200
- })).rowCount ?? 0 };
201
- } finally {
202
- releaseLock();
203
- }
204
- } finally {
205
- await this.releaseClient(client);
206
- }
207
- }
208
- inExplicitTransaction() {
209
- return false;
210
- }
211
- async *runQuery(request, name) {
212
- const client = await this.acquireClient();
213
- try {
214
- if (!this.options.cursorDisabled) {
215
- const releaseLock = await acquireClientQueryLock(client);
216
- try {
217
- for await (const row of this.streamWithPortalProtection(client, request, this.options.cursorBatchSize, name)) yield blindCast(row);
218
- return;
219
- } catch (cursorError) {
220
- if (!(cursorError instanceof Error) || isPostgresError(cursorError)) throw cursorError;
221
- } finally {
222
- releaseLock();
223
- }
224
- }
225
- for await (const row of this.executeBuffered(client, request.sql, request.params, name)) yield blindCast(row);
226
- } finally {
227
- await this.releaseClient(client);
228
- }
229
- }
230
- async explain(request) {
231
- const text = `EXPLAIN (FORMAT JSON) ${request.sql}`;
232
- const client = await this.acquireClient();
233
- try {
234
- const releaseLock = await acquireClientQueryLock(client);
235
- try {
236
- return { rows: blindCast((await client.query(text, request.params === void 0 ? void 0 : [...request.params]).catch(rethrowNormalizedError)).rows) };
237
- } finally {
238
- releaseLock();
239
- }
240
- } finally {
241
- await this.releaseClient(client);
242
- }
243
- }
244
- async *streamWithPortalProtection(client, request, cursorBatchSize, name) {
245
- if (this.inExplicitTransaction()) {
246
- yield* this.executeWithCursor(client, request.sql, request.params, cursorBatchSize, name);
247
- return;
248
- }
249
- await client.query("BEGIN");
250
- let streamFailed = false;
251
- try {
252
- yield* this.executeWithCursor(client, request.sql, request.params, cursorBatchSize, name);
253
- } catch (error) {
254
- streamFailed = true;
255
- throw error;
256
- } finally {
257
- await this.commitStreamSpan(client, streamFailed);
258
- }
259
- }
260
- async commitStreamSpan(client, streamFailed) {
261
- try {
262
- await client.query("COMMIT");
263
- } catch (commitError) {
264
- if (!streamFailed) throw commitError;
265
- }
266
- }
267
- async *executeWithCursor(client, sql, params, cursorBatchSize, name) {
268
- const values = blindCast(params ?? []);
269
- const cursor = client.query(name === void 0 ? new Cursor(sql, values) : new NamedCursor({
270
- name,
271
- text: sql,
272
- values
273
- }));
274
- try {
275
- while (true) {
276
- const rows = await readCursor(cursor, cursorBatchSize);
277
- if (rows.length === 0) break;
278
- for (const row of rows) yield row;
279
- }
280
- } finally {
281
- await closeCursor(cursor);
282
- }
283
- }
284
- async *executeBuffered(client, sql, params, name) {
285
- const config = {
286
- name,
287
- text: sql,
288
- values: blindCast(params ?? [])
289
- };
290
- const releaseLock = await acquireClientQueryLock(client);
291
- let result;
292
- try {
293
- result = await client.query(config);
294
- } finally {
295
- releaseLock();
296
- }
297
- for (const row of blindCast(result.rows)) yield row;
298
- }
299
- };
300
- var PostgresConnectionImpl = class extends PostgresQueryable {
301
- #connection;
302
- #onRelease;
303
- #onDestroy;
304
- #txState;
305
- constructor(connection, options, onRelease, onDestroy, txState) {
306
- super(options);
307
- this.#connection = connection;
308
- this.#onRelease = onRelease;
309
- this.#onDestroy = onDestroy;
310
- this.#txState = txState ?? { open: false };
311
- }
312
- acquireClient() {
313
- return Promise.resolve(this.#connection);
314
- }
315
- releaseClient(_client) {
316
- return Promise.resolve();
317
- }
318
- inExplicitTransaction() {
319
- return this.#txState.open;
320
- }
321
- async beginTransaction() {
322
- const releaseLock = await acquireClientQueryLock(this.#connection);
323
- try {
324
- await this.#connection.query("BEGIN").catch(rethrowNormalizedError);
325
- } finally {
326
- releaseLock();
327
- }
328
- this.#txState.open = true;
329
- return new PostgresTransactionImpl(this.#connection, this.options, () => {
330
- this.#txState.open = false;
331
- });
332
- }
333
- async release() {
334
- const conn = this.#connection;
335
- if ("release" in conn) conn.release();
336
- const onRelease = this.#onRelease;
337
- this.#onRelease = void 0;
338
- this.#onDestroy = void 0;
339
- onRelease?.();
340
- }
341
- async destroy(reason) {
342
- const onDestroy = this.#onDestroy;
343
- const onRelease = this.#onRelease;
344
- this.#onDestroy = void 0;
345
- this.#onRelease = void 0;
346
- const conn = this.#connection;
347
- if ("release" in conn) {
348
- const releaseArg = reason instanceof Error ? reason : /* @__PURE__ */ new Error("Connection destroyed");
349
- conn.release(releaseArg);
350
- }
351
- if (onDestroy) await onDestroy(reason);
352
- else onRelease?.();
353
- }
354
- };
355
- var PostgresTransactionImpl = class extends PostgresQueryable {
356
- #connection;
357
- #onSettled;
358
- constructor(connection, options, onSettled) {
359
- super(options);
360
- this.#connection = connection;
361
- this.#onSettled = onSettled;
362
- }
363
- acquireClient() {
364
- return Promise.resolve(this.#connection);
365
- }
366
- releaseClient(_client) {
367
- return Promise.resolve();
368
- }
369
- inExplicitTransaction() {
370
- return true;
371
- }
372
- #settle() {
373
- const onSettled = this.#onSettled;
374
- this.#onSettled = void 0;
375
- onSettled?.();
376
- }
377
- async commit() {
378
- const releaseLock = await acquireClientQueryLock(this.#connection);
379
- try {
380
- await this.#connection.query("COMMIT").catch(rethrowNormalizedError);
381
- } finally {
382
- releaseLock();
383
- this.#settle();
384
- }
385
- }
386
- async rollback() {
387
- const releaseLock = await acquireClientQueryLock(this.#connection);
388
- try {
389
- await this.#connection.query("ROLLBACK").catch(rethrowNormalizedError);
390
- } finally {
391
- releaseLock();
392
- this.#settle();
393
- }
394
- }
395
- };
396
- var PostgresPoolDriverImpl = class extends PostgresQueryable {
397
- pool;
398
- #closed = false;
399
- constructor(options) {
400
- super(buildConnectionOptions(options));
401
- this.pool = options.connect.pool;
402
- }
403
- get state() {
404
- return this.#closed ? "closed" : "connected";
405
- }
406
- async connect(_binding) {}
407
- async acquireConnection() {
408
- return new PostgresConnectionImpl(await this.acquireClient(), this.options);
409
- }
410
- async close() {
411
- if (this.#closed) return;
412
- this.#closed = true;
413
- await this.pool.end();
414
- }
415
- async acquireClient() {
416
- return this.pool.connect();
417
- }
418
- async releaseClient(client) {
419
- client.release();
420
- }
421
- };
422
- var PostgresDirectDriverImpl = class extends PostgresQueryable {
423
- directClient;
424
- #connectionMutex = new AsyncMutex();
425
- #closed = false;
426
- #connected = false;
427
- #connectPromise;
428
- #txState = { open: false };
429
- constructor(options) {
430
- super(buildConnectionOptions(options));
431
- this.directClient = options.connect.client;
432
- }
433
- inExplicitTransaction() {
434
- return this.#txState.open;
435
- }
436
- get state() {
437
- return this.#closed ? "closed" : "connected";
438
- }
439
- async connect(_binding) {}
440
- async acquireConnection() {
441
- const releaseLease = await this.#connectionMutex.lock();
442
- try {
443
- return new PostgresConnectionImpl(await this.acquireClient(), this.options, releaseLease, async () => {
444
- try {
445
- await this.#closeWhileHoldingLease();
446
- } finally {
447
- releaseLease();
448
- }
449
- }, this.#txState);
450
- } catch (error) {
451
- releaseLease();
452
- throw error;
453
- }
454
- }
455
- async close() {
456
- const releaseLease = await this.#connectionMutex.lock();
457
- try {
458
- await this.#closeWhileHoldingLease();
459
- } finally {
460
- releaseLease();
461
- }
462
- }
463
- async #closeWhileHoldingLease() {
464
- if (this.#closed) return;
465
- this.#closed = true;
466
- await this.directClient.end();
467
- this.#connected = false;
468
- }
469
- async acquireClient() {
470
- if (this.#connected) return this.directClient;
471
- if (this.#connectPromise !== void 0) {
472
- await this.#connectPromise;
473
- return this.directClient;
474
- }
475
- this.#connectPromise = (async () => {
476
- try {
477
- await this.directClient.connect();
478
- } catch (error) {
479
- if (!isAlreadyConnectedError(error)) throw error;
480
- } finally {
481
- this.#connectPromise = void 0;
482
- }
483
- this.#connected = true;
484
- })();
485
- await this.#connectPromise;
486
- return this.directClient;
487
- }
488
- async releaseClient(_client) {}
489
- };
490
- function createBoundDriverFromBinding(binding, cursorOpts, extraOpts) {
491
- const preparedStatements = extraOpts?.preparedStatements;
492
- switch (binding.kind) {
493
- case "url": return new PostgresPoolDriverImpl({
494
- connect: { pool: new Pool({
495
- connectionString: binding.url,
496
- connectionTimeoutMillis: 2e4,
497
- idleTimeoutMillis: 3e4
498
- }) },
499
- cursor: cursorOpts,
500
- preparedStatements
501
- });
502
- case "pgPool": return new PostgresPoolDriverImpl({
503
- connect: { pool: binding.pool },
504
- cursor: cursorOpts,
505
- preparedStatements
506
- });
507
- case "pgClient": return new PostgresDirectDriverImpl({
508
- connect: { client: binding.client },
509
- cursor: cursorOpts,
510
- preparedStatements
511
- });
512
- }
513
- }
514
- function readCursor(cursor, size) {
515
- return callbackToPromise((cb) => {
516
- cursor.read(size, (err, rows) => cb(err, rows));
517
- });
518
- }
519
- function closeCursor(cursor) {
520
- return callbackToPromise((cb) => cursor.close(cb));
521
- }
522
- function rethrowNormalizedError(error) {
523
- throw normalizePgError(error);
524
- }
525
- function prepareFailedError(retryError, handle) {
526
- const cause = normalizePgError(retryError);
527
- return Object.assign(driverError("DRIVER.PREPARE_FAILED", `Prepared statement failed again after re-preparing with a fresh handle: ${cause.message}`, { handle }), { cause });
528
- }
529
- const USE_BEFORE_CONNECT_MESSAGE = "Postgres driver not connected. Call connect(binding) before acquireConnection or execute.";
530
- const ALREADY_CONNECTED_MESSAGE = "Postgres driver already connected. Call close() before reconnecting with a new binding.";
531
- function unboundQuery() {
532
- return { [Symbol.asyncIterator]() {
533
- return { async next() {
534
- throw driverError("DRIVER.NOT_CONNECTED", USE_BEFORE_CONNECT_MESSAGE);
535
- } };
536
- } };
537
- }
538
- var PostgresUnboundDriverImpl = class {
539
- familyId = "sql";
540
- targetId = "postgres";
541
- #delegate = null;
542
- #closed = false;
543
- #cursorOpts;
544
- #preparedStatements;
545
- constructor(options) {
546
- this.#cursorOpts = options?.cursor;
547
- this.#preparedStatements = options?.preparedStatements;
548
- }
549
- get state() {
550
- if (this.#delegate !== null) return "connected";
551
- if (this.#closed) return "closed";
552
- return "unbound";
553
- }
554
- #requireDelegate() {
555
- const delegate = this.#delegate;
556
- if (delegate === null) throw driverError("DRIVER.NOT_CONNECTED", USE_BEFORE_CONNECT_MESSAGE);
557
- return delegate;
558
- }
559
- async connect(binding) {
560
- if (this.#delegate !== null) throw driverError("DRIVER.ALREADY_CONNECTED", ALREADY_CONNECTED_MESSAGE, { bindingKind: binding.kind });
561
- this.#delegate = createBoundDriverFromBinding(binding, this.#cursorOpts, { preparedStatements: this.#preparedStatements });
562
- this.#closed = false;
563
- }
564
- async acquireConnection() {
565
- const delegate = this.#requireDelegate();
566
- const connection = await delegate.acquireConnection();
567
- return this.#wrapConnection(connection, delegate);
568
- }
569
- /**
570
- * Wraps an acquired connection so that teardown paths which close the
571
- * underlying delegate (notably `destroy()` on a pgClient binding, where
572
- * the single socket means a destroyed connection invalidates the driver)
573
- * also reset our own `#delegate` reference. Without this, a failed
574
- * transaction rollback would leave the outer unbound wrapper reporting
575
- * `connected` while routing subsequent work to an already-ended delegate.
576
- */
577
- #wrapConnection(connection, delegate) {
578
- const syncDelegateState = () => {
579
- if (this.#delegate === delegate && delegate.state === "closed") {
580
- this.#delegate = null;
581
- this.#closed = true;
582
- }
583
- };
584
- const wrapped = {
585
- beginTransaction: connection.beginTransaction.bind(connection),
586
- query: connection.query.bind(connection),
587
- execute: connection.execute.bind(connection),
588
- release: async () => {
589
- try {
590
- await connection.release();
591
- } finally {
592
- syncDelegateState();
593
- }
594
- },
595
- destroy: async (reason) => {
596
- try {
597
- await connection.destroy(reason);
598
- } finally {
599
- syncDelegateState();
600
- }
601
- }
602
- };
603
- if (connection.explain) wrapped.explain = connection.explain.bind(connection);
604
- return wrapped;
605
- }
606
- async close() {
607
- const delegate = this.#delegate;
608
- if (delegate !== null) {
609
- this.#delegate = null;
610
- await delegate.close();
611
- }
612
- this.#closed = true;
613
- }
614
- query(request) {
615
- const delegate = this.#delegate;
616
- return delegate === null ? unboundQuery() : delegate.query(request);
617
- }
618
- async execute(request) {
619
- const delegate = this.#delegate;
620
- if (delegate === null) throw driverError("DRIVER.NOT_CONNECTED", USE_BEFORE_CONNECT_MESSAGE);
621
- return delegate.execute(request);
622
- }
623
- async explain(request) {
624
- const delegate = this.#requireDelegate();
625
- const explain = delegate.explain;
626
- if (explain === void 0) throw driverError("DRIVER.NOT_CONNECTED", USE_BEFORE_CONNECT_MESSAGE);
627
- return explain.call(delegate, request);
628
- }
629
- };
630
- const postgresRuntimeDriverDescriptor = {
631
- ...postgresDriverDescriptorMeta,
632
- create(options) {
633
- return new PostgresUnboundDriverImpl(options);
634
- }
635
- };
636
- //#endregion
637
- export { postgresRuntimeDriverDescriptor as default };
638
-
639
- //# sourceMappingURL=driver__runtime.mjs.map
1
+ import { n as suppressIdleConnectionErrors, t as postgresRuntimeDriverDescriptor } from "./runtime-C-Hh2m1R.mjs";
2
+ export { postgresRuntimeDriverDescriptor as default, suppressIdleConnectionErrors };