@nextlyhq/adapter-postgres 0.0.2-alpha.73 → 0.0.2-alpha.75

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
@@ -278,11 +278,47 @@ async function ensureSchemaExists(client, schema) {
278
278
  throw error;
279
279
  }
280
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
+ }
281
297
  /** Whether the database has a schema of this name. Needs no privilege. */
282
298
  async function schemaExists(client, name) {
283
299
  return (await client.query("SELECT 1 FROM pg_namespace WHERE nspname = $1", [name])).rows.length > 0;
284
300
  }
285
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";
320
+ }
321
+ /**
286
322
  * Delay helper for retry logic.
287
323
  */
288
324
  function delay(ms) {
@@ -304,6 +340,14 @@ function applyHappyEyeballsTimeoutOnce() {
304
340
  */
305
341
  const PG_WALL_CLOCK_FORMAT = "YYYY-MM-DD\"T\"HH24:MI:SS.MS";
306
342
  /**
343
+ * The host a pooled client connected to, as node-postgres resolved it from its
344
+ * options, the connection string, `PGHOST` and its default; `undefined` when
345
+ * the client does not hold one.
346
+ */
347
+ function resolvedHost(client) {
348
+ return "host" in client && typeof client.host === "string" && client.host !== "" ? client.host : void 0;
349
+ }
350
+ /**
307
351
  * PostgreSQL database adapter for Nextly.
308
352
  *
309
353
  * @remarks
@@ -418,7 +462,8 @@ var PostgresAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
418
462
  const client = await this.pool.connect();
419
463
  try {
420
464
  await client.query("SELECT 1");
421
- if (this.config.schema) await ensureSchemaExists(client, this.config.schema);
465
+ if (this.config.schema && this.config.readOnly) await assertSchemaExists(client, this.config.schema);
466
+ else if (this.config.schema) await ensureSchemaExists(client, this.config.schema);
422
467
  await (0, _nextlyhq_adapter_drizzle_version_check.checkDialectVersion)(client, "postgresql", { onWarning: (msg) => this.config.logger?.warn?.(msg) });
423
468
  this.connected = true;
424
469
  if (this.config.logger?.info) this.config.logger.info("PostgreSQL connection established", {
@@ -557,12 +602,20 @@ var PostgresAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
557
602
  * Supports automatic retry for serialization failures (40001) and
558
603
  * deadlocks (40P01) when `retryCount` is specified in options.
559
604
  *
560
- * An error carrying the Nextly application brand is neither retried nor
561
- * classified: it is the application refusing the write, so it arrives at the
562
- * caller as it was thrown. Retrying it would repeat work whose verdict has
563
- * already been given. Every other error, including an unbranded one raised by
564
- * the callback, is retried when it is a serialization failure or deadlock and
565
- * classified on the way out.
605
+ * An error carrying the Nextly application brand is not classified: it is the
606
+ * application refusing the write, so it arrives at the caller as it was
607
+ * thrown. It is retried only when `retryWhen` accepts it, which is asked
608
+ * first, of every error; a refusal re-run is otherwise the same refusal.
609
+ * Every other error, including an unbranded one raised by the callback, is
610
+ * retried when it is a serialization failure or deadlock and classified on
611
+ * the way out.
612
+ *
613
+ * A call made inside another transaction's work joins it, on its client,
614
+ * as a savepoint: released when the callback resolves, rolled back to when
615
+ * it throws, so its failure undoes only its own part. A serialization
616
+ * failure or deadlock inside a joined part fails the whole transaction,
617
+ * which only a retry of the outermost one can answer. A joined call keeps
618
+ * the outer's options and is never retried itself.
566
619
  *
567
620
  * @param callback - Function to execute within the transaction
568
621
  * @param options - Transaction options (isolation level, timeout, retry)
@@ -572,56 +625,73 @@ var PostgresAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
572
625
  * or if the callback threw an error that does not carry the application brand
573
626
  * @throws The callback's own error, unchanged, when it carries that brand
574
627
  */
575
- async transaction(callback, options) {
576
- return this.runInFlowTransaction(() => this.runTransactionAttempts(callback, options));
628
+ transaction(callback, options) {
629
+ return this.openOrJoin(callback, options, {
630
+ run: (_attempt, openedAt) => this.runAttempt(callback, options, openedAt),
631
+ retryable: isSerializationFailure,
632
+ describe: (error) => {
633
+ const code = sqlStateOf(error);
634
+ return {
635
+ label: code ?? "a retryable error",
636
+ detail: { code }
637
+ };
638
+ },
639
+ logger: this.config.logger
640
+ });
577
641
  }
578
- /** The attempts `transaction` makes, each on a connection of its own. */
579
- async runTransactionAttempts(callback, options) {
642
+ /** One attempt at an outermost transaction, on a client of its own. */
643
+ async runAttempt(callback, options, openedAt) {
580
644
  const pool = this.ensurePool();
581
- const maxAttempts = (options?.retryCount ?? 0) + 1;
582
- const retryDelayMs = options?.retryDelayMs ?? 100;
583
- let lastError;
584
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
585
- const client = await this.connectFlowTransaction(() => pool.connect());
586
- const startTime = Date.now();
587
- let discard;
588
- try {
589
- await this.beginTransaction(client, options);
590
- const result = await callback(this.createTransactionContext(client));
645
+ this.notePoolAccess();
646
+ const client = await pool.connect();
647
+ let discard;
648
+ const settled = await this.settleOutermost({
649
+ context: this.createTransactionContext(client),
650
+ join: this.joinSteps(client),
651
+ openedAt,
652
+ begin: () => this.beginTransaction(client, options),
653
+ commit: async () => {
591
654
  if ((await client.query("COMMIT"))?.command === "ROLLBACK") throw (0, _nextlyhq_adapter_drizzle_types.createDatabaseError)({
592
655
  kind: "query",
593
656
  code: "25P02",
594
657
  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."
595
658
  });
596
- if (this.config.logger?.debug) {
597
- const durationMs = Date.now() - startTime;
598
- this.config.logger.debug("Transaction committed", {
599
- attempt,
600
- durationMs
601
- });
602
- }
603
- return result;
604
- } catch (error) {
659
+ },
660
+ rollback: async () => {
605
661
  await client.query("ROLLBACK").catch((rollbackError) => {
606
662
  discard = rollbackError instanceof Error ? rollbackError : true;
663
+ throw rollbackError;
607
664
  });
608
- lastError = error;
609
- if ((0, _nextlyhq_adapter_drizzle_types.isApplicationError)(error)) throw error;
610
- const pgError = error;
611
- if ((pgError.code === "40001" || pgError.code === "40P01") && attempt < maxAttempts) {
612
- if (this.config.logger?.warn) this.config.logger.warn(`Transaction failed with ${pgError.code}, retrying (${attempt}/${maxAttempts})`, {
613
- code: pgError.code,
614
- attempt
615
- });
616
- await delay(retryDelayMs * attempt);
617
- continue;
618
- }
619
- throw this.classifyError(error);
620
- } finally {
621
- client.release(discard);
622
665
  }
623
- }
624
- throw this.classifyError(lastError);
666
+ }, callback, options);
667
+ client.release(discard);
668
+ return settled;
669
+ }
670
+ /**
671
+ * How a call made inside a transaction on `client` joins it: a savepoint
672
+ * each, on `client`, named for its depth.
673
+ */
674
+ joinSteps(client) {
675
+ return this.joinStepsOn(() => this.createTransactionContext(client), (relations) => relations ? (0, drizzle_orm_node_postgres.drizzle)({
676
+ client,
677
+ relations
678
+ }) : (0, drizzle_orm_node_postgres.drizzle)({ client }), (context, depth) => {
679
+ const name = this.escapeIdentifier(`nextly_sp_${depth}`);
680
+ return {
681
+ context,
682
+ begin: async () => {
683
+ await client.query(`SAVEPOINT ${name}`);
684
+ },
685
+ commit: async () => {
686
+ await client.query(`RELEASE SAVEPOINT ${name}`);
687
+ },
688
+ rollback: async () => {
689
+ await client.query(`ROLLBACK TO SAVEPOINT ${name}`);
690
+ await client.query(`RELEASE SAVEPOINT ${name}`);
691
+ },
692
+ dooms: isSerializationFailure
693
+ };
694
+ });
625
695
  }
626
696
  /**
627
697
  * Returns the database capabilities for PostgreSQL.
@@ -675,6 +745,63 @@ var PostgresAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
675
745
  };
676
746
  }
677
747
  /**
748
+ * The connection as a health check reads it, on one pooled client: the
749
+ * server's version, and that client's own row in `pg_stat_ssl`, which says
750
+ * whether the session's connection is encrypted. The query is timed for the
751
+ * round trip.
752
+ *
753
+ * @remarks
754
+ * The row and the client's own socket are weighed by `encryptionOf`: behind
755
+ * a connection pooler such as PgBouncer the row describes the pooler's own
756
+ * connection to the server, which can be plain inside the provider's
757
+ * network while this client's socket is TLS. The socket is read as it is,
758
+ * never inferred from the `ssl` setting.
759
+ *
760
+ * Whether the database is on this machine is judged from the host the
761
+ * client connected to, as node-postgres resolved it (its options, the
762
+ * connection string, `PGHOST`, its default); before a client is had, from
763
+ * the configured address alone. The address never leaves this method. Any
764
+ * failure answers `"unknown"`.
765
+ */
766
+ async inspectConnection() {
767
+ let local = this.isLocalHost(this.configuredHost());
768
+ let client;
769
+ try {
770
+ client = await this.ensurePool().connect();
771
+ local = this.isLocalHost(resolvedHost(client) ?? this.configuredHost());
772
+ const started = performance.now();
773
+ const result = await client.query("SELECT current_setting('server_version') AS version, (SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()) AS ssl");
774
+ const roundTripMs = Math.max(0, Math.round(performance.now() - started));
775
+ const row = result.rows[0];
776
+ const version = row?.version?.split(" ")[0];
777
+ return {
778
+ encryption: this.encryptionOf({
779
+ session: typeof row?.ssl === "boolean" ? row.ssl : void 0,
780
+ ownSocketTls: this.ownSocketIsTls(client)
781
+ }),
782
+ local,
783
+ roundTripMs,
784
+ ...version ? { serverVersion: version } : {}
785
+ };
786
+ } catch {
787
+ return {
788
+ encryption: "unknown",
789
+ local
790
+ };
791
+ } finally {
792
+ client?.release();
793
+ }
794
+ }
795
+ /**
796
+ * The host this adapter is configured with: the connection string's when one
797
+ * is set, else the `host` option. `undefined` when it names none, which is
798
+ * judged remote, or when the connection string cannot be read.
799
+ */
800
+ configuredHost() {
801
+ const configured = this.config.url ? this.hostOfUrl(this.config.url) : this.config.host ?? "";
802
+ return configured === "" ? void 0 : configured;
803
+ }
804
+ /**
678
805
  * Override insertMany for bulk insert optimization.
679
806
  *
680
807
  * @remarks
@@ -684,6 +811,7 @@ var PostgresAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
684
811
  async insertMany(table, data, options) {
685
812
  if (data.length === 0) return [];
686
813
  if (data.length === 1) return [await this.insert(table, data[0], options)];
814
+ this.resolvedTableObject(table);
687
815
  const columns = Object.keys(data[0]);
688
816
  const params = [];
689
817
  const valuesClauses = [];
@@ -757,14 +885,15 @@ var PostgresAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
757
885
  relations
758
886
  }) : (0, drizzle_orm_node_postgres.drizzle)({ client });
759
887
  const reported = this.observedPool(pool, ["query"]);
760
- return this.trackFlowTransactions(this.pinDrizzleTransactions(onClient(reported), async () => {
761
- const client = await this.connectFlowTransaction(() => pool.connect());
888
+ return this.joiningHandle(onClient(reported), async () => {
889
+ const client = await pool.connect();
762
890
  return {
763
891
  drizzle: onClient(client),
764
892
  rollback: () => client.query("ROLLBACK"),
765
- release: (dirty) => client.release(dirty)
893
+ release: (dirty) => client.release(dirty),
894
+ join: this.joinSteps(client)
766
895
  };
767
- }));
896
+ }, relations);
768
897
  }
769
898
  /**
770
899
  * Builds pg Pool configuration from adapter config.
@@ -860,14 +989,14 @@ var PostgresAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
860
989
  await client.query(`SELECT ${idColumn} FROM ${this.escapeIdentifier(table)} WHERE ${idColumn} = $1 FOR UPDATE`, [id]);
861
990
  },
862
991
  insert: async (table, data, options) => {
863
- const mapped = this.mapRowToRawSql(this.getTableObject(table), data);
992
+ const tableObj = this.resolvedTableObject(table);
993
+ const mapped = this.mapRowToRawSql(tableObj, data);
864
994
  const columns = Object.keys(mapped);
865
995
  const values = Object.values(mapped);
866
996
  const placeholders = values.map((_, i) => `$${i + 1}`).join(", ");
867
997
  let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES (${placeholders})`;
868
998
  const ret = options?.returning;
869
999
  const returningEmpty = Array.isArray(ret) && ret.length === 0;
870
- const tableObj = this.getTableObject(table);
871
1000
  const aliases = returningEmpty ? [] : this.dateWallClockAliases(tableObj, ret ?? "*");
872
1001
  if (!returningEmpty) {
873
1002
  const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(tableObj, ret).map((col) => this.escapeIdentifier(col)).join(", ");
@@ -879,7 +1008,7 @@ var PostgresAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
879
1008
  },
880
1009
  insertMany: async (table, data, options) => {
881
1010
  if (data.length === 0) return [];
882
- const tableObj = this.getTableObject(table);
1011
+ const tableObj = this.resolvedTableObject(table);
883
1012
  const mappedRecords = data.map((r) => this.mapRowToRawSql(tableObj, r));
884
1013
  const columns = Object.keys(mappedRecords[0]);
885
1014
  const params = [];