@nextlyhq/adapter-postgres 0.0.2-alpha.73 → 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.d.cts CHANGED
@@ -134,12 +134,20 @@ export declare class PostgresAdapter extends DrizzleAdapter {
134
134
  * Supports automatic retry for serialization failures (40001) and
135
135
  * deadlocks (40P01) when `retryCount` is specified in options.
136
136
  *
137
- * An error carrying the Nextly application brand is neither retried nor
138
- * classified: it is the application refusing the write, so it arrives at the
139
- * caller as it was thrown. Retrying it would repeat work whose verdict has
140
- * already been given. Every other error, including an unbranded one raised by
141
- * the callback, is retried when it is a serialization failure or deadlock and
142
- * classified on the way out.
137
+ * An error carrying the Nextly application brand is not classified: it is the
138
+ * application refusing the write, so it arrives at the caller as it was
139
+ * thrown. It is retried only when `retryWhen` accepts it, which is asked
140
+ * first, of every error; a refusal re-run is otherwise the same refusal.
141
+ * Every other error, including an unbranded one raised by the callback, is
142
+ * retried when it is a serialization failure or deadlock and classified on
143
+ * the way out.
144
+ *
145
+ * A call made inside another transaction's work joins it, on its client,
146
+ * as a savepoint: released when the callback resolves, rolled back to when
147
+ * it throws, so its failure undoes only its own part. A serialization
148
+ * failure or deadlock inside a joined part fails the whole transaction,
149
+ * which only a retry of the outermost one can answer. A joined call keeps
150
+ * the outer's options and is never retried itself.
143
151
  *
144
152
  * @param callback - Function to execute within the transaction
145
153
  * @param options - Transaction options (isolation level, timeout, retry)
@@ -150,8 +158,13 @@ export declare class PostgresAdapter extends DrizzleAdapter {
150
158
  * @throws The callback's own error, unchanged, when it carries that brand
151
159
  */
152
160
  transaction<T>(callback: (ctx: TransactionContext$1) => Promise<T>, options?: TransactionOptions$1): Promise<T>;
153
- /** The attempts `transaction` makes, each on a connection of its own. */
154
- private runTransactionAttempts;
161
+ /** One attempt at an outermost transaction, on a client of its own. */
162
+ private runAttempt;
163
+ /**
164
+ * How a call made inside a transaction on `client` joins it: a savepoint
165
+ * each, on `client`, named for its depth.
166
+ */
167
+ private joinSteps;
155
168
  /**
156
169
  * Returns the database capabilities for PostgreSQL.
157
170
  *
package/dist/index.d.ts CHANGED
@@ -134,12 +134,20 @@ export declare class PostgresAdapter extends DrizzleAdapter {
134
134
  * Supports automatic retry for serialization failures (40001) and
135
135
  * deadlocks (40P01) when `retryCount` is specified in options.
136
136
  *
137
- * An error carrying the Nextly application brand is neither retried nor
138
- * classified: it is the application refusing the write, so it arrives at the
139
- * caller as it was thrown. Retrying it would repeat work whose verdict has
140
- * already been given. Every other error, including an unbranded one raised by
141
- * the callback, is retried when it is a serialization failure or deadlock and
142
- * classified on the way out.
137
+ * An error carrying the Nextly application brand is not classified: it is the
138
+ * application refusing the write, so it arrives at the caller as it was
139
+ * thrown. It is retried only when `retryWhen` accepts it, which is asked
140
+ * first, of every error; a refusal re-run is otherwise the same refusal.
141
+ * Every other error, including an unbranded one raised by the callback, is
142
+ * retried when it is a serialization failure or deadlock and classified on
143
+ * the way out.
144
+ *
145
+ * A call made inside another transaction's work joins it, on its client,
146
+ * as a savepoint: released when the callback resolves, rolled back to when
147
+ * it throws, so its failure undoes only its own part. A serialization
148
+ * failure or deadlock inside a joined part fails the whole transaction,
149
+ * which only a retry of the outermost one can answer. A joined call keeps
150
+ * the outer's options and is never retried itself.
143
151
  *
144
152
  * @param callback - Function to execute within the transaction
145
153
  * @param options - Transaction options (isolation level, timeout, retry)
@@ -150,8 +158,13 @@ export declare class PostgresAdapter extends DrizzleAdapter {
150
158
  * @throws The callback's own error, unchanged, when it carries that brand
151
159
  */
152
160
  transaction<T>(callback: (ctx: TransactionContext$1) => Promise<T>, options?: TransactionOptions$1): Promise<T>;
153
- /** The attempts `transaction` makes, each on a connection of its own. */
154
- private runTransactionAttempts;
161
+ /** One attempt at an outermost transaction, on a client of its own. */
162
+ private runAttempt;
163
+ /**
164
+ * How a call made inside a transaction on `client` joins it: a savepoint
165
+ * each, on `client`, named for its depth.
166
+ */
167
+ private joinSteps;
155
168
  /**
156
169
  * Returns the database capabilities for PostgreSQL.
157
170
  *
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";
@@ -255,11 +255,47 @@ async function ensureSchemaExists(client, schema) {
255
255
  throw error;
256
256
  }
257
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
+ }
258
274
  /** Whether the database has a schema of this name. Needs no privilege. */
259
275
  async function schemaExists(client, name) {
260
276
  return (await client.query("SELECT 1 FROM pg_namespace WHERE nspname = $1", [name])).rows.length > 0;
261
277
  }
262
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";
297
+ }
298
+ /**
263
299
  * Delay helper for retry logic.
264
300
  */
265
301
  function delay(ms) {
@@ -395,7 +431,8 @@ var PostgresAdapter = class extends DrizzleAdapter {
395
431
  const client = await this.pool.connect();
396
432
  try {
397
433
  await client.query("SELECT 1");
398
- 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);
399
436
  await checkDialectVersion(client, "postgresql", { onWarning: (msg) => this.config.logger?.warn?.(msg) });
400
437
  this.connected = true;
401
438
  if (this.config.logger?.info) this.config.logger.info("PostgreSQL connection established", {
@@ -534,12 +571,20 @@ var PostgresAdapter = class extends DrizzleAdapter {
534
571
  * Supports automatic retry for serialization failures (40001) and
535
572
  * deadlocks (40P01) when `retryCount` is specified in options.
536
573
  *
537
- * An error carrying the Nextly application brand is neither retried nor
538
- * classified: it is the application refusing the write, so it arrives at the
539
- * caller as it was thrown. Retrying it would repeat work whose verdict has
540
- * already been given. Every other error, including an unbranded one raised by
541
- * the callback, is retried when it is a serialization failure or deadlock and
542
- * 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.
543
588
  *
544
589
  * @param callback - Function to execute within the transaction
545
590
  * @param options - Transaction options (isolation level, timeout, retry)
@@ -549,56 +594,73 @@ var PostgresAdapter = class extends DrizzleAdapter {
549
594
  * or if the callback threw an error that does not carry the application brand
550
595
  * @throws The callback's own error, unchanged, when it carries that brand
551
596
  */
552
- async transaction(callback, options) {
553
- 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
+ });
554
610
  }
555
- /** The attempts `transaction` makes, each on a connection of its own. */
556
- async runTransactionAttempts(callback, options) {
611
+ /** One attempt at an outermost transaction, on a client of its own. */
612
+ async runAttempt(callback, options, openedAt) {
557
613
  const pool = this.ensurePool();
558
- const maxAttempts = (options?.retryCount ?? 0) + 1;
559
- const retryDelayMs = options?.retryDelayMs ?? 100;
560
- let lastError;
561
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
562
- const client = await this.connectFlowTransaction(() => pool.connect());
563
- const startTime = Date.now();
564
- let discard;
565
- try {
566
- await this.beginTransaction(client, options);
567
- 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 () => {
568
623
  if ((await client.query("COMMIT"))?.command === "ROLLBACK") throw createDatabaseError({
569
624
  kind: "query",
570
625
  code: "25P02",
571
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."
572
627
  });
573
- if (this.config.logger?.debug) {
574
- const durationMs = Date.now() - startTime;
575
- this.config.logger.debug("Transaction committed", {
576
- attempt,
577
- durationMs
578
- });
579
- }
580
- return result;
581
- } catch (error) {
628
+ },
629
+ rollback: async () => {
582
630
  await client.query("ROLLBACK").catch((rollbackError) => {
583
631
  discard = rollbackError instanceof Error ? rollbackError : true;
632
+ throw rollbackError;
584
633
  });
585
- lastError = error;
586
- if (isApplicationError(error)) throw error;
587
- const pgError = error;
588
- if ((pgError.code === "40001" || pgError.code === "40P01") && attempt < maxAttempts) {
589
- if (this.config.logger?.warn) this.config.logger.warn(`Transaction failed with ${pgError.code}, retrying (${attempt}/${maxAttempts})`, {
590
- code: pgError.code,
591
- attempt
592
- });
593
- await delay(retryDelayMs * attempt);
594
- continue;
595
- }
596
- throw this.classifyError(error);
597
- } finally {
598
- client.release(discard);
599
634
  }
600
- }
601
- 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
+ });
602
664
  }
603
665
  /**
604
666
  * Returns the database capabilities for PostgreSQL.
@@ -661,6 +723,7 @@ var PostgresAdapter = class extends DrizzleAdapter {
661
723
  async insertMany(table, data, options) {
662
724
  if (data.length === 0) return [];
663
725
  if (data.length === 1) return [await this.insert(table, data[0], options)];
726
+ this.resolvedTableObject(table);
664
727
  const columns = Object.keys(data[0]);
665
728
  const params = [];
666
729
  const valuesClauses = [];
@@ -734,14 +797,15 @@ var PostgresAdapter = class extends DrizzleAdapter {
734
797
  relations
735
798
  }) : drizzle({ client });
736
799
  const reported = this.observedPool(pool, ["query"]);
737
- return this.trackFlowTransactions(this.pinDrizzleTransactions(onClient(reported), async () => {
738
- const client = await this.connectFlowTransaction(() => pool.connect());
800
+ return this.joiningHandle(onClient(reported), async () => {
801
+ const client = await pool.connect();
739
802
  return {
740
803
  drizzle: onClient(client),
741
804
  rollback: () => client.query("ROLLBACK"),
742
- release: (dirty) => client.release(dirty)
805
+ release: (dirty) => client.release(dirty),
806
+ join: this.joinSteps(client)
743
807
  };
744
- }));
808
+ }, relations);
745
809
  }
746
810
  /**
747
811
  * Builds pg Pool configuration from adapter config.
@@ -837,14 +901,14 @@ var PostgresAdapter = class extends DrizzleAdapter {
837
901
  await client.query(`SELECT ${idColumn} FROM ${this.escapeIdentifier(table)} WHERE ${idColumn} = $1 FOR UPDATE`, [id]);
838
902
  },
839
903
  insert: async (table, data, options) => {
840
- const mapped = this.mapRowToRawSql(this.getTableObject(table), data);
904
+ const tableObj = this.resolvedTableObject(table);
905
+ const mapped = this.mapRowToRawSql(tableObj, data);
841
906
  const columns = Object.keys(mapped);
842
907
  const values = Object.values(mapped);
843
908
  const placeholders = values.map((_, i) => `$${i + 1}`).join(", ");
844
909
  let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES (${placeholders})`;
845
910
  const ret = options?.returning;
846
911
  const returningEmpty = Array.isArray(ret) && ret.length === 0;
847
- const tableObj = this.getTableObject(table);
848
912
  const aliases = returningEmpty ? [] : this.dateWallClockAliases(tableObj, ret ?? "*");
849
913
  if (!returningEmpty) {
850
914
  const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(tableObj, ret).map((col) => this.escapeIdentifier(col)).join(", ");
@@ -856,7 +920,7 @@ var PostgresAdapter = class extends DrizzleAdapter {
856
920
  },
857
921
  insertMany: async (table, data, options) => {
858
922
  if (data.length === 0) return [];
859
- const tableObj = this.getTableObject(table);
923
+ const tableObj = this.resolvedTableObject(table);
860
924
  const mappedRecords = data.map((r) => this.mapRowToRawSql(tableObj, r));
861
925
  const columns = Object.keys(mappedRecords[0]);
862
926
  const params = [];