@nextlyhq/adapter-postgres 0.0.2-alpha.72 → 0.0.2-alpha.74

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/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as net from "node:net";
2
2
  import { DrizzleAdapter } from "@nextlyhq/adapter-drizzle";
3
3
  import { assertSchemaName } from "@nextlyhq/adapter-drizzle/schema-name";
4
- import { createDatabaseError, isApplicationError, isDatabaseError, poolWaitTimeoutError } from "@nextlyhq/adapter-drizzle/types";
4
+ import { createDatabaseError, isDatabaseError, poolWaitTimeoutError } from "@nextlyhq/adapter-drizzle/types";
5
5
  import { checkDialectVersion } from "@nextlyhq/adapter-drizzle/version-check";
6
6
  import { drizzle } from "drizzle-orm/node-postgres";
7
7
  import { getTableConfig } from "drizzle-orm/pg-core";
@@ -227,11 +227,73 @@ const PG_ERROR_CODES = {
227
227
  * and create objects in `public` but may not create schemas would fail to
228
228
  * connect over a schema that is already there. Reading `pg_namespace` needs no
229
229
  * privilege, so only a schema that is genuinely missing asks for one.
230
+ *
231
+ * Created inside a transaction holding an advisory lock on the schema's name,
232
+ * and looked up again once the lock is held. `IF NOT EXISTS` alone is not safe
233
+ * against itself: two processes connecting at the same moment can both pass its
234
+ * check, and the second to commit fails with a unique violation on
235
+ * `pg_namespace_nspname_index`, which fails its connect. The transaction-scoped
236
+ * lock makes the second wait for the first to commit, and its lookup, a new
237
+ * statement with a new snapshot, then finds the schema. The transaction is
238
+ * read committed whatever the database's or role's default: at repeatable
239
+ * read or serializable the snapshot is fixed by the first statement, the lock
240
+ * wait, so the lookup would miss the schema and the CREATE that followed would
241
+ * ask for the database privilege the first paragraph avoids. Released by the commit
242
+ * or rollback, so it never outlives this one connection's transaction, and a
243
+ * transaction-mode pooler keeps all of it on one server connection.
230
244
  */
231
245
  async function ensureSchemaExists(client, schema) {
232
246
  const name = assertSchemaName(schema);
233
- if ((await client.query("SELECT 1 FROM pg_namespace WHERE nspname = $1", [name])).rows.length > 0) return;
234
- await client.query(`CREATE SCHEMA IF NOT EXISTS ${name}`);
247
+ if (await schemaExists(client, name)) return;
248
+ await client.query("BEGIN ISOLATION LEVEL READ COMMITTED");
249
+ try {
250
+ await client.query("SELECT pg_advisory_xact_lock(hashtext('nextly:create-schema'), hashtext($1))", [name]);
251
+ if (!await schemaExists(client, name)) await client.query(`CREATE SCHEMA IF NOT EXISTS ${name}`);
252
+ await client.query("COMMIT");
253
+ } catch (error) {
254
+ await client.query("ROLLBACK").catch(() => {});
255
+ throw error;
256
+ }
257
+ }
258
+ /** PostgreSQL's code for a schema that does not exist. */
259
+ const INVALID_SCHEMA_NAME = "3F000";
260
+ /**
261
+ * Fails, without creating it, when the database has no schema of this name:
262
+ * a read-only connect must not change the database, and a `search_path` that
263
+ * names a missing schema would quietly fall through to `public`.
264
+ */
265
+ async function assertSchemaExists(client, schema) {
266
+ const name = assertSchemaName(schema);
267
+ if (await schemaExists(client, name)) return;
268
+ throw createDatabaseError({
269
+ kind: "connection",
270
+ message: `schema "${name}" does not exist`,
271
+ code: INVALID_SCHEMA_NAME
272
+ });
273
+ }
274
+ /** Whether the database has a schema of this name. Needs no privilege. */
275
+ async function schemaExists(client, name) {
276
+ return (await client.query("SELECT 1 FROM pg_namespace WHERE nspname = $1", [name])).rows.length > 0;
277
+ }
278
+ /**
279
+ * The SQLSTATE an error carries: its own, or that of the driver error it
280
+ * wraps, as a Drizzle query error does.
281
+ */
282
+ function sqlStateOf(error) {
283
+ for (let at = error, hops = 0; hops < 4; hops++) {
284
+ if (typeof at !== "object" || at === null) return void 0;
285
+ const code = Reflect.get(at, "code");
286
+ if (typeof code === "string" && /^[0-9A-Z]{5}$/.test(code)) return code;
287
+ at = Reflect.get(at, "cause");
288
+ }
289
+ }
290
+ /**
291
+ * A serialization failure or a deadlock: the transaction lost a race, and
292
+ * running it again may succeed.
293
+ */
294
+ function isSerializationFailure(error) {
295
+ const code = sqlStateOf(error);
296
+ return code === "40001" || code === "40P01";
235
297
  }
236
298
  /**
237
299
  * Delay helper for retry logic.
@@ -369,7 +431,8 @@ var PostgresAdapter = class extends DrizzleAdapter {
369
431
  const client = await this.pool.connect();
370
432
  try {
371
433
  await client.query("SELECT 1");
372
- if (this.config.schema) await ensureSchemaExists(client, this.config.schema);
434
+ if (this.config.schema && this.config.readOnly) await assertSchemaExists(client, this.config.schema);
435
+ else if (this.config.schema) await ensureSchemaExists(client, this.config.schema);
373
436
  await checkDialectVersion(client, "postgresql", { onWarning: (msg) => this.config.logger?.warn?.(msg) });
374
437
  this.connected = true;
375
438
  if (this.config.logger?.info) this.config.logger.info("PostgreSQL connection established", {
@@ -426,6 +489,41 @@ var PostgresAdapter = class extends DrizzleAdapter {
426
489
  return this.connected && this.pool !== null;
427
490
  }
428
491
  /**
492
+ * Runs `work` on one client taken from the pool, outside a transaction,
493
+ * each statement committing as it runs, so connection-scoped state a
494
+ * statement sets (a temporary table, a session setting, an advisory lock)
495
+ * is still there for the next. The client is closed afterwards, whether
496
+ * `work` finished or threw, never handed back to the pool: that state ends
497
+ * with it instead of reaching a later caller. No `SessionOptions` field
498
+ * changes anything on PostgreSQL: strict mode is MySQL's, and PostgreSQL
499
+ * refuses an overlong value already.
500
+ */
501
+ async withSession(work, _options) {
502
+ this.refuseSessionInTransaction();
503
+ const pool = this.ensurePool();
504
+ this.notePoolAccess();
505
+ let client;
506
+ try {
507
+ client = await pool.connect();
508
+ } catch (error) {
509
+ throw this.classifyError(error);
510
+ }
511
+ try {
512
+ return await work({ execute: async (statement, params = []) => {
513
+ const startTime = Date.now();
514
+ try {
515
+ const result = await client.query(statement, params);
516
+ if (this.config.logger?.query) this.config.logger.query(statement, params, Date.now() - startTime);
517
+ return result.rows;
518
+ } catch (error) {
519
+ throw this.classifyError(error, statement);
520
+ }
521
+ } });
522
+ } finally {
523
+ client.release(true);
524
+ }
525
+ }
526
+ /**
429
527
  * Executes a raw SQL query.
430
528
  *
431
529
  * @param sql - SQL statement with $1, $2, ... placeholders
@@ -473,12 +571,20 @@ var PostgresAdapter = class extends DrizzleAdapter {
473
571
  * Supports automatic retry for serialization failures (40001) and
474
572
  * deadlocks (40P01) when `retryCount` is specified in options.
475
573
  *
476
- * An error carrying the Nextly application brand is neither retried nor
477
- * classified: it is the application refusing the write, so it arrives at the
478
- * caller as it was thrown. Retrying it would repeat work whose verdict has
479
- * already been given. Every other error, including an unbranded one raised by
480
- * the callback, is retried when it is a serialization failure or deadlock and
481
- * classified on the way out.
574
+ * An error carrying the Nextly application brand is not classified: it is the
575
+ * application refusing the write, so it arrives at the caller as it was
576
+ * thrown. It is retried only when `retryWhen` accepts it, which is asked
577
+ * first, of every error; a refusal re-run is otherwise the same refusal.
578
+ * Every other error, including an unbranded one raised by the callback, is
579
+ * retried when it is a serialization failure or deadlock and classified on
580
+ * the way out.
581
+ *
582
+ * A call made inside another transaction's work joins it, on its client,
583
+ * as a savepoint: released when the callback resolves, rolled back to when
584
+ * it throws, so its failure undoes only its own part. A serialization
585
+ * failure or deadlock inside a joined part fails the whole transaction,
586
+ * which only a retry of the outermost one can answer. A joined call keeps
587
+ * the outer's options and is never retried itself.
482
588
  *
483
589
  * @param callback - Function to execute within the transaction
484
590
  * @param options - Transaction options (isolation level, timeout, retry)
@@ -488,56 +594,73 @@ var PostgresAdapter = class extends DrizzleAdapter {
488
594
  * or if the callback threw an error that does not carry the application brand
489
595
  * @throws The callback's own error, unchanged, when it carries that brand
490
596
  */
491
- async transaction(callback, options) {
492
- return this.runInFlowTransaction(() => this.runTransactionAttempts(callback, options));
597
+ transaction(callback, options) {
598
+ return this.openOrJoin(callback, options, {
599
+ run: (_attempt, openedAt) => this.runAttempt(callback, options, openedAt),
600
+ retryable: isSerializationFailure,
601
+ describe: (error) => {
602
+ const code = sqlStateOf(error);
603
+ return {
604
+ label: code ?? "a retryable error",
605
+ detail: { code }
606
+ };
607
+ },
608
+ logger: this.config.logger
609
+ });
493
610
  }
494
- /** The attempts `transaction` makes, each on a connection of its own. */
495
- async runTransactionAttempts(callback, options) {
611
+ /** One attempt at an outermost transaction, on a client of its own. */
612
+ async runAttempt(callback, options, openedAt) {
496
613
  const pool = this.ensurePool();
497
- const maxAttempts = (options?.retryCount ?? 0) + 1;
498
- const retryDelayMs = options?.retryDelayMs ?? 100;
499
- let lastError;
500
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
501
- const client = await this.connectFlowTransaction(() => pool.connect());
502
- const startTime = Date.now();
503
- let discard;
504
- try {
505
- await this.beginTransaction(client, options);
506
- const result = await callback(this.createTransactionContext(client));
614
+ this.notePoolAccess();
615
+ const client = await pool.connect();
616
+ let discard;
617
+ const settled = await this.settleOutermost({
618
+ context: this.createTransactionContext(client),
619
+ join: this.joinSteps(client),
620
+ openedAt,
621
+ begin: () => this.beginTransaction(client, options),
622
+ commit: async () => {
507
623
  if ((await client.query("COMMIT"))?.command === "ROLLBACK") throw createDatabaseError({
508
624
  kind: "query",
509
625
  code: "25P02",
510
626
  message: "The transaction was rolled back, not committed: a statement in it failed, and PostgreSQL ends such a transaction with a rollback when asked to commit."
511
627
  });
512
- if (this.config.logger?.debug) {
513
- const durationMs = Date.now() - startTime;
514
- this.config.logger.debug("Transaction committed", {
515
- attempt,
516
- durationMs
517
- });
518
- }
519
- return result;
520
- } catch (error) {
628
+ },
629
+ rollback: async () => {
521
630
  await client.query("ROLLBACK").catch((rollbackError) => {
522
631
  discard = rollbackError instanceof Error ? rollbackError : true;
632
+ throw rollbackError;
523
633
  });
524
- lastError = error;
525
- if (isApplicationError(error)) throw error;
526
- const pgError = error;
527
- if ((pgError.code === "40001" || pgError.code === "40P01") && attempt < maxAttempts) {
528
- if (this.config.logger?.warn) this.config.logger.warn(`Transaction failed with ${pgError.code}, retrying (${attempt}/${maxAttempts})`, {
529
- code: pgError.code,
530
- attempt
531
- });
532
- await delay(retryDelayMs * attempt);
533
- continue;
534
- }
535
- throw this.classifyError(error);
536
- } finally {
537
- client.release(discard);
538
634
  }
539
- }
540
- throw this.classifyError(lastError);
635
+ }, callback, options);
636
+ client.release(discard);
637
+ return settled;
638
+ }
639
+ /**
640
+ * How a call made inside a transaction on `client` joins it: a savepoint
641
+ * each, on `client`, named for its depth.
642
+ */
643
+ joinSteps(client) {
644
+ return this.joinStepsOn(() => this.createTransactionContext(client), (relations) => relations ? drizzle({
645
+ client,
646
+ relations
647
+ }) : drizzle({ client }), (context, depth) => {
648
+ const name = this.escapeIdentifier(`nextly_sp_${depth}`);
649
+ return {
650
+ context,
651
+ begin: async () => {
652
+ await client.query(`SAVEPOINT ${name}`);
653
+ },
654
+ commit: async () => {
655
+ await client.query(`RELEASE SAVEPOINT ${name}`);
656
+ },
657
+ rollback: async () => {
658
+ await client.query(`ROLLBACK TO SAVEPOINT ${name}`);
659
+ await client.query(`RELEASE SAVEPOINT ${name}`);
660
+ },
661
+ dooms: isSerializationFailure
662
+ };
663
+ });
541
664
  }
542
665
  /**
543
666
  * Returns the database capabilities for PostgreSQL.
@@ -600,6 +723,7 @@ var PostgresAdapter = class extends DrizzleAdapter {
600
723
  async insertMany(table, data, options) {
601
724
  if (data.length === 0) return [];
602
725
  if (data.length === 1) return [await this.insert(table, data[0], options)];
726
+ this.resolvedTableObject(table);
603
727
  const columns = Object.keys(data[0]);
604
728
  const params = [];
605
729
  const valuesClauses = [];
@@ -673,14 +797,15 @@ var PostgresAdapter = class extends DrizzleAdapter {
673
797
  relations
674
798
  }) : drizzle({ client });
675
799
  const reported = this.observedPool(pool, ["query"]);
676
- return this.trackFlowTransactions(this.pinDrizzleTransactions(onClient(reported), async () => {
677
- const client = await this.connectFlowTransaction(() => pool.connect());
800
+ return this.joiningHandle(onClient(reported), async () => {
801
+ const client = await pool.connect();
678
802
  return {
679
803
  drizzle: onClient(client),
680
804
  rollback: () => client.query("ROLLBACK"),
681
- release: (dirty) => client.release(dirty)
805
+ release: (dirty) => client.release(dirty),
806
+ join: this.joinSteps(client)
682
807
  };
683
- }));
808
+ }, relations);
684
809
  }
685
810
  /**
686
811
  * Builds pg Pool configuration from adapter config.
@@ -776,14 +901,14 @@ var PostgresAdapter = class extends DrizzleAdapter {
776
901
  await client.query(`SELECT ${idColumn} FROM ${this.escapeIdentifier(table)} WHERE ${idColumn} = $1 FOR UPDATE`, [id]);
777
902
  },
778
903
  insert: async (table, data, options) => {
779
- const mapped = this.mapRowToRawSql(this.getTableObject(table), data);
904
+ const tableObj = this.resolvedTableObject(table);
905
+ const mapped = this.mapRowToRawSql(tableObj, data);
780
906
  const columns = Object.keys(mapped);
781
907
  const values = Object.values(mapped);
782
908
  const placeholders = values.map((_, i) => `$${i + 1}`).join(", ");
783
909
  let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES (${placeholders})`;
784
910
  const ret = options?.returning;
785
911
  const returningEmpty = Array.isArray(ret) && ret.length === 0;
786
- const tableObj = this.getTableObject(table);
787
912
  const aliases = returningEmpty ? [] : this.dateWallClockAliases(tableObj, ret ?? "*");
788
913
  if (!returningEmpty) {
789
914
  const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(tableObj, ret).map((col) => this.escapeIdentifier(col)).join(", ");
@@ -795,7 +920,7 @@ var PostgresAdapter = class extends DrizzleAdapter {
795
920
  },
796
921
  insertMany: async (table, data, options) => {
797
922
  if (data.length === 0) return [];
798
- const tableObj = this.getTableObject(table);
923
+ const tableObj = this.resolvedTableObject(table);
799
924
  const mappedRecords = data.map((r) => this.mapRowToRawSql(tableObj, r));
800
925
  const columns = Object.keys(mappedRecords[0]);
801
926
  const params = [];