@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.cjs CHANGED
@@ -250,11 +250,73 @@ const PG_ERROR_CODES = {
250
250
  * and create objects in `public` but may not create schemas would fail to
251
251
  * connect over a schema that is already there. Reading `pg_namespace` needs no
252
252
  * privilege, so only a schema that is genuinely missing asks for one.
253
+ *
254
+ * Created inside a transaction holding an advisory lock on the schema's name,
255
+ * and looked up again once the lock is held. `IF NOT EXISTS` alone is not safe
256
+ * against itself: two processes connecting at the same moment can both pass its
257
+ * check, and the second to commit fails with a unique violation on
258
+ * `pg_namespace_nspname_index`, which fails its connect. The transaction-scoped
259
+ * lock makes the second wait for the first to commit, and its lookup, a new
260
+ * statement with a new snapshot, then finds the schema. The transaction is
261
+ * read committed whatever the database's or role's default: at repeatable
262
+ * read or serializable the snapshot is fixed by the first statement, the lock
263
+ * wait, so the lookup would miss the schema and the CREATE that followed would
264
+ * ask for the database privilege the first paragraph avoids. Released by the commit
265
+ * or rollback, so it never outlives this one connection's transaction, and a
266
+ * transaction-mode pooler keeps all of it on one server connection.
253
267
  */
254
268
  async function ensureSchemaExists(client, schema) {
255
269
  const name = (0, _nextlyhq_adapter_drizzle_schema_name.assertSchemaName)(schema);
256
- if ((await client.query("SELECT 1 FROM pg_namespace WHERE nspname = $1", [name])).rows.length > 0) return;
257
- await client.query(`CREATE SCHEMA IF NOT EXISTS ${name}`);
270
+ if (await schemaExists(client, name)) return;
271
+ await client.query("BEGIN ISOLATION LEVEL READ COMMITTED");
272
+ try {
273
+ await client.query("SELECT pg_advisory_xact_lock(hashtext('nextly:create-schema'), hashtext($1))", [name]);
274
+ if (!await schemaExists(client, name)) await client.query(`CREATE SCHEMA IF NOT EXISTS ${name}`);
275
+ await client.query("COMMIT");
276
+ } catch (error) {
277
+ await client.query("ROLLBACK").catch(() => {});
278
+ throw error;
279
+ }
280
+ }
281
+ /** PostgreSQL's code for a schema that does not exist. */
282
+ const INVALID_SCHEMA_NAME = "3F000";
283
+ /**
284
+ * Fails, without creating it, when the database has no schema of this name:
285
+ * a read-only connect must not change the database, and a `search_path` that
286
+ * names a missing schema would quietly fall through to `public`.
287
+ */
288
+ async function assertSchemaExists(client, schema) {
289
+ const name = (0, _nextlyhq_adapter_drizzle_schema_name.assertSchemaName)(schema);
290
+ if (await schemaExists(client, name)) return;
291
+ throw (0, _nextlyhq_adapter_drizzle_types.createDatabaseError)({
292
+ kind: "connection",
293
+ message: `schema "${name}" does not exist`,
294
+ code: INVALID_SCHEMA_NAME
295
+ });
296
+ }
297
+ /** Whether the database has a schema of this name. Needs no privilege. */
298
+ async function schemaExists(client, name) {
299
+ return (await client.query("SELECT 1 FROM pg_namespace WHERE nspname = $1", [name])).rows.length > 0;
300
+ }
301
+ /**
302
+ * The SQLSTATE an error carries: its own, or that of the driver error it
303
+ * wraps, as a Drizzle query error does.
304
+ */
305
+ function sqlStateOf(error) {
306
+ for (let at = error, hops = 0; hops < 4; hops++) {
307
+ if (typeof at !== "object" || at === null) return void 0;
308
+ const code = Reflect.get(at, "code");
309
+ if (typeof code === "string" && /^[0-9A-Z]{5}$/.test(code)) return code;
310
+ at = Reflect.get(at, "cause");
311
+ }
312
+ }
313
+ /**
314
+ * A serialization failure or a deadlock: the transaction lost a race, and
315
+ * running it again may succeed.
316
+ */
317
+ function isSerializationFailure(error) {
318
+ const code = sqlStateOf(error);
319
+ return code === "40001" || code === "40P01";
258
320
  }
259
321
  /**
260
322
  * Delay helper for retry logic.
@@ -392,7 +454,8 @@ var PostgresAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
392
454
  const client = await this.pool.connect();
393
455
  try {
394
456
  await client.query("SELECT 1");
395
- if (this.config.schema) await ensureSchemaExists(client, this.config.schema);
457
+ if (this.config.schema && this.config.readOnly) await assertSchemaExists(client, this.config.schema);
458
+ else if (this.config.schema) await ensureSchemaExists(client, this.config.schema);
396
459
  await (0, _nextlyhq_adapter_drizzle_version_check.checkDialectVersion)(client, "postgresql", { onWarning: (msg) => this.config.logger?.warn?.(msg) });
397
460
  this.connected = true;
398
461
  if (this.config.logger?.info) this.config.logger.info("PostgreSQL connection established", {
@@ -449,6 +512,41 @@ var PostgresAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
449
512
  return this.connected && this.pool !== null;
450
513
  }
451
514
  /**
515
+ * Runs `work` on one client taken from the pool, outside a transaction,
516
+ * each statement committing as it runs, so connection-scoped state a
517
+ * statement sets (a temporary table, a session setting, an advisory lock)
518
+ * is still there for the next. The client is closed afterwards, whether
519
+ * `work` finished or threw, never handed back to the pool: that state ends
520
+ * with it instead of reaching a later caller. No `SessionOptions` field
521
+ * changes anything on PostgreSQL: strict mode is MySQL's, and PostgreSQL
522
+ * refuses an overlong value already.
523
+ */
524
+ async withSession(work, _options) {
525
+ this.refuseSessionInTransaction();
526
+ const pool = this.ensurePool();
527
+ this.notePoolAccess();
528
+ let client;
529
+ try {
530
+ client = await pool.connect();
531
+ } catch (error) {
532
+ throw this.classifyError(error);
533
+ }
534
+ try {
535
+ return await work({ execute: async (statement, params = []) => {
536
+ const startTime = Date.now();
537
+ try {
538
+ const result = await client.query(statement, params);
539
+ if (this.config.logger?.query) this.config.logger.query(statement, params, Date.now() - startTime);
540
+ return result.rows;
541
+ } catch (error) {
542
+ throw this.classifyError(error, statement);
543
+ }
544
+ } });
545
+ } finally {
546
+ client.release(true);
547
+ }
548
+ }
549
+ /**
452
550
  * Executes a raw SQL query.
453
551
  *
454
552
  * @param sql - SQL statement with $1, $2, ... placeholders
@@ -496,12 +594,20 @@ var PostgresAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
496
594
  * Supports automatic retry for serialization failures (40001) and
497
595
  * deadlocks (40P01) when `retryCount` is specified in options.
498
596
  *
499
- * An error carrying the Nextly application brand is neither retried nor
500
- * classified: it is the application refusing the write, so it arrives at the
501
- * caller as it was thrown. Retrying it would repeat work whose verdict has
502
- * already been given. Every other error, including an unbranded one raised by
503
- * the callback, is retried when it is a serialization failure or deadlock and
504
- * classified on the way out.
597
+ * An error carrying the Nextly application brand is not classified: it is the
598
+ * application refusing the write, so it arrives at the caller as it was
599
+ * thrown. It is retried only when `retryWhen` accepts it, which is asked
600
+ * first, of every error; a refusal re-run is otherwise the same refusal.
601
+ * Every other error, including an unbranded one raised by the callback, is
602
+ * retried when it is a serialization failure or deadlock and classified on
603
+ * the way out.
604
+ *
605
+ * A call made inside another transaction's work joins it, on its client,
606
+ * as a savepoint: released when the callback resolves, rolled back to when
607
+ * it throws, so its failure undoes only its own part. A serialization
608
+ * failure or deadlock inside a joined part fails the whole transaction,
609
+ * which only a retry of the outermost one can answer. A joined call keeps
610
+ * the outer's options and is never retried itself.
505
611
  *
506
612
  * @param callback - Function to execute within the transaction
507
613
  * @param options - Transaction options (isolation level, timeout, retry)
@@ -511,56 +617,73 @@ var PostgresAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
511
617
  * or if the callback threw an error that does not carry the application brand
512
618
  * @throws The callback's own error, unchanged, when it carries that brand
513
619
  */
514
- async transaction(callback, options) {
515
- return this.runInFlowTransaction(() => this.runTransactionAttempts(callback, options));
620
+ transaction(callback, options) {
621
+ return this.openOrJoin(callback, options, {
622
+ run: (_attempt, openedAt) => this.runAttempt(callback, options, openedAt),
623
+ retryable: isSerializationFailure,
624
+ describe: (error) => {
625
+ const code = sqlStateOf(error);
626
+ return {
627
+ label: code ?? "a retryable error",
628
+ detail: { code }
629
+ };
630
+ },
631
+ logger: this.config.logger
632
+ });
516
633
  }
517
- /** The attempts `transaction` makes, each on a connection of its own. */
518
- async runTransactionAttempts(callback, options) {
634
+ /** One attempt at an outermost transaction, on a client of its own. */
635
+ async runAttempt(callback, options, openedAt) {
519
636
  const pool = this.ensurePool();
520
- const maxAttempts = (options?.retryCount ?? 0) + 1;
521
- const retryDelayMs = options?.retryDelayMs ?? 100;
522
- let lastError;
523
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
524
- const client = await this.connectFlowTransaction(() => pool.connect());
525
- const startTime = Date.now();
526
- let discard;
527
- try {
528
- await this.beginTransaction(client, options);
529
- const result = await callback(this.createTransactionContext(client));
637
+ this.notePoolAccess();
638
+ const client = await pool.connect();
639
+ let discard;
640
+ const settled = await this.settleOutermost({
641
+ context: this.createTransactionContext(client),
642
+ join: this.joinSteps(client),
643
+ openedAt,
644
+ begin: () => this.beginTransaction(client, options),
645
+ commit: async () => {
530
646
  if ((await client.query("COMMIT"))?.command === "ROLLBACK") throw (0, _nextlyhq_adapter_drizzle_types.createDatabaseError)({
531
647
  kind: "query",
532
648
  code: "25P02",
533
649
  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."
534
650
  });
535
- if (this.config.logger?.debug) {
536
- const durationMs = Date.now() - startTime;
537
- this.config.logger.debug("Transaction committed", {
538
- attempt,
539
- durationMs
540
- });
541
- }
542
- return result;
543
- } catch (error) {
651
+ },
652
+ rollback: async () => {
544
653
  await client.query("ROLLBACK").catch((rollbackError) => {
545
654
  discard = rollbackError instanceof Error ? rollbackError : true;
655
+ throw rollbackError;
546
656
  });
547
- lastError = error;
548
- if ((0, _nextlyhq_adapter_drizzle_types.isApplicationError)(error)) throw error;
549
- const pgError = error;
550
- if ((pgError.code === "40001" || pgError.code === "40P01") && attempt < maxAttempts) {
551
- if (this.config.logger?.warn) this.config.logger.warn(`Transaction failed with ${pgError.code}, retrying (${attempt}/${maxAttempts})`, {
552
- code: pgError.code,
553
- attempt
554
- });
555
- await delay(retryDelayMs * attempt);
556
- continue;
557
- }
558
- throw this.classifyError(error);
559
- } finally {
560
- client.release(discard);
561
657
  }
562
- }
563
- throw this.classifyError(lastError);
658
+ }, callback, options);
659
+ client.release(discard);
660
+ return settled;
661
+ }
662
+ /**
663
+ * How a call made inside a transaction on `client` joins it: a savepoint
664
+ * each, on `client`, named for its depth.
665
+ */
666
+ joinSteps(client) {
667
+ return this.joinStepsOn(() => this.createTransactionContext(client), (relations) => relations ? (0, drizzle_orm_node_postgres.drizzle)({
668
+ client,
669
+ relations
670
+ }) : (0, drizzle_orm_node_postgres.drizzle)({ client }), (context, depth) => {
671
+ const name = this.escapeIdentifier(`nextly_sp_${depth}`);
672
+ return {
673
+ context,
674
+ begin: async () => {
675
+ await client.query(`SAVEPOINT ${name}`);
676
+ },
677
+ commit: async () => {
678
+ await client.query(`RELEASE SAVEPOINT ${name}`);
679
+ },
680
+ rollback: async () => {
681
+ await client.query(`ROLLBACK TO SAVEPOINT ${name}`);
682
+ await client.query(`RELEASE SAVEPOINT ${name}`);
683
+ },
684
+ dooms: isSerializationFailure
685
+ };
686
+ });
564
687
  }
565
688
  /**
566
689
  * Returns the database capabilities for PostgreSQL.
@@ -623,6 +746,7 @@ var PostgresAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
623
746
  async insertMany(table, data, options) {
624
747
  if (data.length === 0) return [];
625
748
  if (data.length === 1) return [await this.insert(table, data[0], options)];
749
+ this.resolvedTableObject(table);
626
750
  const columns = Object.keys(data[0]);
627
751
  const params = [];
628
752
  const valuesClauses = [];
@@ -696,14 +820,15 @@ var PostgresAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
696
820
  relations
697
821
  }) : (0, drizzle_orm_node_postgres.drizzle)({ client });
698
822
  const reported = this.observedPool(pool, ["query"]);
699
- return this.trackFlowTransactions(this.pinDrizzleTransactions(onClient(reported), async () => {
700
- const client = await this.connectFlowTransaction(() => pool.connect());
823
+ return this.joiningHandle(onClient(reported), async () => {
824
+ const client = await pool.connect();
701
825
  return {
702
826
  drizzle: onClient(client),
703
827
  rollback: () => client.query("ROLLBACK"),
704
- release: (dirty) => client.release(dirty)
828
+ release: (dirty) => client.release(dirty),
829
+ join: this.joinSteps(client)
705
830
  };
706
- }));
831
+ }, relations);
707
832
  }
708
833
  /**
709
834
  * Builds pg Pool configuration from adapter config.
@@ -799,14 +924,14 @@ var PostgresAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
799
924
  await client.query(`SELECT ${idColumn} FROM ${this.escapeIdentifier(table)} WHERE ${idColumn} = $1 FOR UPDATE`, [id]);
800
925
  },
801
926
  insert: async (table, data, options) => {
802
- const mapped = this.mapRowToRawSql(this.getTableObject(table), data);
927
+ const tableObj = this.resolvedTableObject(table);
928
+ const mapped = this.mapRowToRawSql(tableObj, data);
803
929
  const columns = Object.keys(mapped);
804
930
  const values = Object.values(mapped);
805
931
  const placeholders = values.map((_, i) => `$${i + 1}`).join(", ");
806
932
  let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES (${placeholders})`;
807
933
  const ret = options?.returning;
808
934
  const returningEmpty = Array.isArray(ret) && ret.length === 0;
809
- const tableObj = this.getTableObject(table);
810
935
  const aliases = returningEmpty ? [] : this.dateWallClockAliases(tableObj, ret ?? "*");
811
936
  if (!returningEmpty) {
812
937
  const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(tableObj, ret).map((col) => this.escapeIdentifier(col)).join(", ");
@@ -818,7 +943,7 @@ var PostgresAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
818
943
  },
819
944
  insertMany: async (table, data, options) => {
820
945
  if (data.length === 0) return [];
821
- const tableObj = this.getTableObject(table);
946
+ const tableObj = this.resolvedTableObject(table);
822
947
  const mappedRecords = data.map((r) => this.mapRowToRawSql(tableObj, r));
823
948
  const columns = Object.keys(mappedRecords[0]);
824
949
  const params = [];