@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 +182 -53
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +48 -9
- package/dist/index.d.ts +48 -9
- package/dist/index.mjs +183 -54
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
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,
|
|
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) {
|
|
@@ -281,6 +317,14 @@ function applyHappyEyeballsTimeoutOnce() {
|
|
|
281
317
|
*/
|
|
282
318
|
const PG_WALL_CLOCK_FORMAT = "YYYY-MM-DD\"T\"HH24:MI:SS.MS";
|
|
283
319
|
/**
|
|
320
|
+
* The host a pooled client connected to, as node-postgres resolved it from its
|
|
321
|
+
* options, the connection string, `PGHOST` and its default; `undefined` when
|
|
322
|
+
* the client does not hold one.
|
|
323
|
+
*/
|
|
324
|
+
function resolvedHost(client) {
|
|
325
|
+
return "host" in client && typeof client.host === "string" && client.host !== "" ? client.host : void 0;
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
284
328
|
* PostgreSQL database adapter for Nextly.
|
|
285
329
|
*
|
|
286
330
|
* @remarks
|
|
@@ -395,7 +439,8 @@ var PostgresAdapter = class extends DrizzleAdapter {
|
|
|
395
439
|
const client = await this.pool.connect();
|
|
396
440
|
try {
|
|
397
441
|
await client.query("SELECT 1");
|
|
398
|
-
if (this.config.schema) await
|
|
442
|
+
if (this.config.schema && this.config.readOnly) await assertSchemaExists(client, this.config.schema);
|
|
443
|
+
else if (this.config.schema) await ensureSchemaExists(client, this.config.schema);
|
|
399
444
|
await checkDialectVersion(client, "postgresql", { onWarning: (msg) => this.config.logger?.warn?.(msg) });
|
|
400
445
|
this.connected = true;
|
|
401
446
|
if (this.config.logger?.info) this.config.logger.info("PostgreSQL connection established", {
|
|
@@ -534,12 +579,20 @@ var PostgresAdapter = class extends DrizzleAdapter {
|
|
|
534
579
|
* Supports automatic retry for serialization failures (40001) and
|
|
535
580
|
* deadlocks (40P01) when `retryCount` is specified in options.
|
|
536
581
|
*
|
|
537
|
-
* An error carrying the Nextly application brand is
|
|
538
|
-
*
|
|
539
|
-
*
|
|
540
|
-
*
|
|
541
|
-
*
|
|
542
|
-
*
|
|
582
|
+
* An error carrying the Nextly application brand is not classified: it is the
|
|
583
|
+
* application refusing the write, so it arrives at the caller as it was
|
|
584
|
+
* thrown. It is retried only when `retryWhen` accepts it, which is asked
|
|
585
|
+
* first, of every error; a refusal re-run is otherwise the same refusal.
|
|
586
|
+
* Every other error, including an unbranded one raised by the callback, is
|
|
587
|
+
* retried when it is a serialization failure or deadlock and classified on
|
|
588
|
+
* the way out.
|
|
589
|
+
*
|
|
590
|
+
* A call made inside another transaction's work joins it, on its client,
|
|
591
|
+
* as a savepoint: released when the callback resolves, rolled back to when
|
|
592
|
+
* it throws, so its failure undoes only its own part. A serialization
|
|
593
|
+
* failure or deadlock inside a joined part fails the whole transaction,
|
|
594
|
+
* which only a retry of the outermost one can answer. A joined call keeps
|
|
595
|
+
* the outer's options and is never retried itself.
|
|
543
596
|
*
|
|
544
597
|
* @param callback - Function to execute within the transaction
|
|
545
598
|
* @param options - Transaction options (isolation level, timeout, retry)
|
|
@@ -549,56 +602,73 @@ var PostgresAdapter = class extends DrizzleAdapter {
|
|
|
549
602
|
* or if the callback threw an error that does not carry the application brand
|
|
550
603
|
* @throws The callback's own error, unchanged, when it carries that brand
|
|
551
604
|
*/
|
|
552
|
-
|
|
553
|
-
return this.
|
|
605
|
+
transaction(callback, options) {
|
|
606
|
+
return this.openOrJoin(callback, options, {
|
|
607
|
+
run: (_attempt, openedAt) => this.runAttempt(callback, options, openedAt),
|
|
608
|
+
retryable: isSerializationFailure,
|
|
609
|
+
describe: (error) => {
|
|
610
|
+
const code = sqlStateOf(error);
|
|
611
|
+
return {
|
|
612
|
+
label: code ?? "a retryable error",
|
|
613
|
+
detail: { code }
|
|
614
|
+
};
|
|
615
|
+
},
|
|
616
|
+
logger: this.config.logger
|
|
617
|
+
});
|
|
554
618
|
}
|
|
555
|
-
/**
|
|
556
|
-
async
|
|
619
|
+
/** One attempt at an outermost transaction, on a client of its own. */
|
|
620
|
+
async runAttempt(callback, options, openedAt) {
|
|
557
621
|
const pool = this.ensurePool();
|
|
558
|
-
|
|
559
|
-
const
|
|
560
|
-
let
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
const result = await callback(this.createTransactionContext(client));
|
|
622
|
+
this.notePoolAccess();
|
|
623
|
+
const client = await pool.connect();
|
|
624
|
+
let discard;
|
|
625
|
+
const settled = await this.settleOutermost({
|
|
626
|
+
context: this.createTransactionContext(client),
|
|
627
|
+
join: this.joinSteps(client),
|
|
628
|
+
openedAt,
|
|
629
|
+
begin: () => this.beginTransaction(client, options),
|
|
630
|
+
commit: async () => {
|
|
568
631
|
if ((await client.query("COMMIT"))?.command === "ROLLBACK") throw createDatabaseError({
|
|
569
632
|
kind: "query",
|
|
570
633
|
code: "25P02",
|
|
571
634
|
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
635
|
});
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
this.config.logger.debug("Transaction committed", {
|
|
576
|
-
attempt,
|
|
577
|
-
durationMs
|
|
578
|
-
});
|
|
579
|
-
}
|
|
580
|
-
return result;
|
|
581
|
-
} catch (error) {
|
|
636
|
+
},
|
|
637
|
+
rollback: async () => {
|
|
582
638
|
await client.query("ROLLBACK").catch((rollbackError) => {
|
|
583
639
|
discard = rollbackError instanceof Error ? rollbackError : true;
|
|
640
|
+
throw rollbackError;
|
|
584
641
|
});
|
|
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
642
|
}
|
|
600
|
-
}
|
|
601
|
-
|
|
643
|
+
}, callback, options);
|
|
644
|
+
client.release(discard);
|
|
645
|
+
return settled;
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* How a call made inside a transaction on `client` joins it: a savepoint
|
|
649
|
+
* each, on `client`, named for its depth.
|
|
650
|
+
*/
|
|
651
|
+
joinSteps(client) {
|
|
652
|
+
return this.joinStepsOn(() => this.createTransactionContext(client), (relations) => relations ? drizzle({
|
|
653
|
+
client,
|
|
654
|
+
relations
|
|
655
|
+
}) : drizzle({ client }), (context, depth) => {
|
|
656
|
+
const name = this.escapeIdentifier(`nextly_sp_${depth}`);
|
|
657
|
+
return {
|
|
658
|
+
context,
|
|
659
|
+
begin: async () => {
|
|
660
|
+
await client.query(`SAVEPOINT ${name}`);
|
|
661
|
+
},
|
|
662
|
+
commit: async () => {
|
|
663
|
+
await client.query(`RELEASE SAVEPOINT ${name}`);
|
|
664
|
+
},
|
|
665
|
+
rollback: async () => {
|
|
666
|
+
await client.query(`ROLLBACK TO SAVEPOINT ${name}`);
|
|
667
|
+
await client.query(`RELEASE SAVEPOINT ${name}`);
|
|
668
|
+
},
|
|
669
|
+
dooms: isSerializationFailure
|
|
670
|
+
};
|
|
671
|
+
});
|
|
602
672
|
}
|
|
603
673
|
/**
|
|
604
674
|
* Returns the database capabilities for PostgreSQL.
|
|
@@ -652,6 +722,63 @@ var PostgresAdapter = class extends DrizzleAdapter {
|
|
|
652
722
|
};
|
|
653
723
|
}
|
|
654
724
|
/**
|
|
725
|
+
* The connection as a health check reads it, on one pooled client: the
|
|
726
|
+
* server's version, and that client's own row in `pg_stat_ssl`, which says
|
|
727
|
+
* whether the session's connection is encrypted. The query is timed for the
|
|
728
|
+
* round trip.
|
|
729
|
+
*
|
|
730
|
+
* @remarks
|
|
731
|
+
* The row and the client's own socket are weighed by `encryptionOf`: behind
|
|
732
|
+
* a connection pooler such as PgBouncer the row describes the pooler's own
|
|
733
|
+
* connection to the server, which can be plain inside the provider's
|
|
734
|
+
* network while this client's socket is TLS. The socket is read as it is,
|
|
735
|
+
* never inferred from the `ssl` setting.
|
|
736
|
+
*
|
|
737
|
+
* Whether the database is on this machine is judged from the host the
|
|
738
|
+
* client connected to, as node-postgres resolved it (its options, the
|
|
739
|
+
* connection string, `PGHOST`, its default); before a client is had, from
|
|
740
|
+
* the configured address alone. The address never leaves this method. Any
|
|
741
|
+
* failure answers `"unknown"`.
|
|
742
|
+
*/
|
|
743
|
+
async inspectConnection() {
|
|
744
|
+
let local = this.isLocalHost(this.configuredHost());
|
|
745
|
+
let client;
|
|
746
|
+
try {
|
|
747
|
+
client = await this.ensurePool().connect();
|
|
748
|
+
local = this.isLocalHost(resolvedHost(client) ?? this.configuredHost());
|
|
749
|
+
const started = performance.now();
|
|
750
|
+
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");
|
|
751
|
+
const roundTripMs = Math.max(0, Math.round(performance.now() - started));
|
|
752
|
+
const row = result.rows[0];
|
|
753
|
+
const version = row?.version?.split(" ")[0];
|
|
754
|
+
return {
|
|
755
|
+
encryption: this.encryptionOf({
|
|
756
|
+
session: typeof row?.ssl === "boolean" ? row.ssl : void 0,
|
|
757
|
+
ownSocketTls: this.ownSocketIsTls(client)
|
|
758
|
+
}),
|
|
759
|
+
local,
|
|
760
|
+
roundTripMs,
|
|
761
|
+
...version ? { serverVersion: version } : {}
|
|
762
|
+
};
|
|
763
|
+
} catch {
|
|
764
|
+
return {
|
|
765
|
+
encryption: "unknown",
|
|
766
|
+
local
|
|
767
|
+
};
|
|
768
|
+
} finally {
|
|
769
|
+
client?.release();
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
/**
|
|
773
|
+
* The host this adapter is configured with: the connection string's when one
|
|
774
|
+
* is set, else the `host` option. `undefined` when it names none, which is
|
|
775
|
+
* judged remote, or when the connection string cannot be read.
|
|
776
|
+
*/
|
|
777
|
+
configuredHost() {
|
|
778
|
+
const configured = this.config.url ? this.hostOfUrl(this.config.url) : this.config.host ?? "";
|
|
779
|
+
return configured === "" ? void 0 : configured;
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
655
782
|
* Override insertMany for bulk insert optimization.
|
|
656
783
|
*
|
|
657
784
|
* @remarks
|
|
@@ -661,6 +788,7 @@ var PostgresAdapter = class extends DrizzleAdapter {
|
|
|
661
788
|
async insertMany(table, data, options) {
|
|
662
789
|
if (data.length === 0) return [];
|
|
663
790
|
if (data.length === 1) return [await this.insert(table, data[0], options)];
|
|
791
|
+
this.resolvedTableObject(table);
|
|
664
792
|
const columns = Object.keys(data[0]);
|
|
665
793
|
const params = [];
|
|
666
794
|
const valuesClauses = [];
|
|
@@ -734,14 +862,15 @@ var PostgresAdapter = class extends DrizzleAdapter {
|
|
|
734
862
|
relations
|
|
735
863
|
}) : drizzle({ client });
|
|
736
864
|
const reported = this.observedPool(pool, ["query"]);
|
|
737
|
-
return this.
|
|
738
|
-
const client = await
|
|
865
|
+
return this.joiningHandle(onClient(reported), async () => {
|
|
866
|
+
const client = await pool.connect();
|
|
739
867
|
return {
|
|
740
868
|
drizzle: onClient(client),
|
|
741
869
|
rollback: () => client.query("ROLLBACK"),
|
|
742
|
-
release: (dirty) => client.release(dirty)
|
|
870
|
+
release: (dirty) => client.release(dirty),
|
|
871
|
+
join: this.joinSteps(client)
|
|
743
872
|
};
|
|
744
|
-
})
|
|
873
|
+
}, relations);
|
|
745
874
|
}
|
|
746
875
|
/**
|
|
747
876
|
* Builds pg Pool configuration from adapter config.
|
|
@@ -837,14 +966,14 @@ var PostgresAdapter = class extends DrizzleAdapter {
|
|
|
837
966
|
await client.query(`SELECT ${idColumn} FROM ${this.escapeIdentifier(table)} WHERE ${idColumn} = $1 FOR UPDATE`, [id]);
|
|
838
967
|
},
|
|
839
968
|
insert: async (table, data, options) => {
|
|
840
|
-
const
|
|
969
|
+
const tableObj = this.resolvedTableObject(table);
|
|
970
|
+
const mapped = this.mapRowToRawSql(tableObj, data);
|
|
841
971
|
const columns = Object.keys(mapped);
|
|
842
972
|
const values = Object.values(mapped);
|
|
843
973
|
const placeholders = values.map((_, i) => `$${i + 1}`).join(", ");
|
|
844
974
|
let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES (${placeholders})`;
|
|
845
975
|
const ret = options?.returning;
|
|
846
976
|
const returningEmpty = Array.isArray(ret) && ret.length === 0;
|
|
847
|
-
const tableObj = this.getTableObject(table);
|
|
848
977
|
const aliases = returningEmpty ? [] : this.dateWallClockAliases(tableObj, ret ?? "*");
|
|
849
978
|
if (!returningEmpty) {
|
|
850
979
|
const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(tableObj, ret).map((col) => this.escapeIdentifier(col)).join(", ");
|
|
@@ -856,7 +985,7 @@ var PostgresAdapter = class extends DrizzleAdapter {
|
|
|
856
985
|
},
|
|
857
986
|
insertMany: async (table, data, options) => {
|
|
858
987
|
if (data.length === 0) return [];
|
|
859
|
-
const tableObj = this.
|
|
988
|
+
const tableObj = this.resolvedTableObject(table);
|
|
860
989
|
const mappedRecords = data.map((r) => this.mapRowToRawSql(tableObj, r));
|
|
861
990
|
const columns = Object.keys(mappedRecords[0]);
|
|
862
991
|
const params = [];
|