viborm 1.3.2 → 1.4.0
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/{adapter-internals-AGgQRu5t.mjs → adapter-internals-Cy2QEBnH.mjs} +1 -1
- package/dist/{adapter-internals-AGgQRu5t.mjs.map → adapter-internals-Cy2QEBnH.mjs.map} +1 -1
- package/dist/{adapter-namespace-B8XWzCev.mjs → adapter-namespace-BLejG8FA.mjs} +2 -2
- package/dist/{adapter-namespace-B8XWzCev.mjs.map → adapter-namespace-BLejG8FA.mjs.map} +1 -1
- package/dist/adapter-result-parser-D6lluSMi.mjs +2 -0
- package/dist/adapter-result-parser-D6lluSMi.mjs.map +1 -0
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-BKdLfNzM.mjs → array-literal-BsbbSLw3.mjs} +1 -1
- package/dist/{array-literal-BKdLfNzM.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
- package/dist/{batch-refs-DoWlPD2h.mjs → batch-refs-BYCu1JnQ.mjs} +2 -2
- package/dist/{batch-refs-DoWlPD2h.mjs.map → batch-refs-BYCu1JnQ.mjs.map} +1 -1
- package/dist/bind-parameter-capacity-D6p9HrbB.mjs +2 -0
- package/dist/bind-parameter-capacity-D6p9HrbB.mjs.map +1 -0
- package/dist/builder-BS8EW4BQ.mjs +2 -0
- package/dist/builder-BS8EW4BQ.mjs.map +1 -0
- package/dist/bun-sql.d.mts +3 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/{canonical-json-BReb5nFO.mjs → canonical-json-acY4dQNQ.mjs} +2 -2
- package/dist/canonical-json-acY4dQNQ.mjs.map +1 -0
- package/dist/chain-D5J9hIw-.mjs +2 -0
- package/dist/chain-D5J9hIw-.mjs.map +1 -0
- package/dist/cli.mjs +1 -1
- package/dist/client-Bhl2mWam.mjs +2 -0
- package/dist/client-Bhl2mWam.mjs.map +1 -0
- package/dist/{client-Df81J4oB.d.mts → client-BzgBm_86.d.mts} +4 -2
- package/dist/{client-q6ccRgdO.mjs → client-aU3YhZ6G.mjs} +16 -16
- package/dist/client-aU3YhZ6G.mjs.map +1 -0
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-YTLtjLFS.mjs → clock-CJotKAxc.mjs} +1 -1
- package/dist/{clock-YTLtjLFS.mjs.map → clock-CJotKAxc.mjs.map} +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/datetime-physical-codec-lX7IJBlz.mjs +2 -0
- package/dist/datetime-physical-codec-lX7IJBlz.mjs.map +1 -0
- package/dist/driver-CQQbCQh9.mjs +2 -0
- package/dist/{driver-Ddt147dK.mjs.map → driver-CQQbCQh9.mjs.map} +1 -1
- package/dist/{driver-D6_Ik58x.mjs → driver-u2qJicrE.mjs} +2 -2
- package/dist/{driver-D6_Ik58x.mjs.map → driver-u2qJicrE.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/{error-mapping-C9WgitPi.mjs → error-mapping-6op318w6.mjs} +2 -2
- package/dist/error-mapping-6op318w6.mjs.map +1 -0
- package/dist/every-CzF00eDV.mjs +2 -0
- package/dist/{every-dpzVDwzu.mjs.map → every-CzF00eDV.mjs.map} +1 -1
- package/dist/{fs-estate-azK36i9V.mjs → fs-estate-N_F2YqYa.mjs} +2 -2
- package/dist/{fs-estate-azK36i9V.mjs.map → fs-estate-N_F2YqYa.mjs.map} +1 -1
- package/dist/{geo-area-codec-CbkmFArQ.mjs → geo-area-codec-BmMmWgU_.mjs} +2 -2
- package/dist/{geo-area-codec-CbkmFArQ.mjs.map → geo-area-codec-BmMmWgU_.mjs.map} +1 -1
- package/dist/{geo-point-codec-DyEHMdJg.mjs → geo-point-codec-D95uXgDF.mjs} +2 -2
- package/dist/{geo-point-codec-DyEHMdJg.mjs.map → geo-point-codec-D95uXgDF.mjs.map} +1 -1
- package/dist/{hydration-C2uXmJy6.mjs → hydration-BflrXEIQ.mjs} +2 -2
- package/dist/{hydration-C2uXmJy6.mjs.map → hydration-BflrXEIQ.mjs.map} +1 -1
- package/dist/{identifier-conversion-C2pwwFOS.mjs → identifier-conversion-Dc0Rf4Gi.mjs} +2 -2
- package/dist/{identifier-conversion-C2pwwFOS.mjs.map → identifier-conversion-Dc0Rf4Gi.mjs.map} +1 -1
- package/dist/identity-CmRos0Yf.mjs +2 -0
- package/dist/identity-CmRos0Yf.mjs.map +1 -0
- package/dist/{index-D4O0Twvs.d.mts → index-B4IWFJfv.d.mts} +1304 -1056
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{invariant-D57gi_yW.mjs → invariant-D_fIjY_z.mjs} +1 -1
- package/dist/{invariant-D57gi_yW.mjs.map → invariant-D_fIjY_z.mjs.map} +1 -1
- package/dist/{json-number-DvmiNx0n.mjs → json-number-CGXpPu4D.mjs} +1 -1
- package/dist/{json-number-DvmiNx0n.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
- package/dist/{key-B7vuAYPG.mjs → key-B89Z4vxn.mjs} +2 -2
- package/dist/{key-B7vuAYPG.mjs.map → key-B89Z4vxn.mjs.map} +1 -1
- package/dist/{libsql-DUO6vHad.mjs → libsql-CrDXsfpL.mjs} +2 -2
- package/dist/{libsql-DUO6vHad.mjs.map → libsql-CrDXsfpL.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/{memory-BApsTkt1.mjs → memory-TXO4KgBy.mjs} +2 -2
- package/dist/{memory-BApsTkt1.mjs.map → memory-TXO4KgBy.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-D1GlcktG.mjs → mysql-C2vOPcuA.mjs} +2 -2
- package/dist/{mysql-D1GlcktG.mjs.map → mysql-C2vOPcuA.mjs.map} +1 -1
- package/dist/mysql-adapter-C5CMIYRS.mjs +2 -0
- package/dist/mysql-adapter-C5CMIYRS.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/neon-http.d.mts +3 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/normalized-result-BF7gr4_b.mjs +2 -0
- package/dist/normalized-result-BF7gr4_b.mjs.map +1 -0
- package/dist/{object-store-CZADAv4c.mjs → object-store-WjVilDvN.mjs} +2 -2
- package/dist/{object-store-CZADAv4c.mjs.map → object-store-WjVilDvN.mjs.map} +1 -1
- package/dist/{object-store-BN64q8Zn.d.mts → object-store-uRqi0URP.d.mts} +3 -3
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/permissions.mjs.map +1 -1
- package/dist/pg.d.mts +26 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/{physical-CAOaNM4R.mjs → physical-uJfmo4-Z.mjs} +2 -2
- package/dist/{physical-CAOaNM4R.mjs.map → physical-uJfmo4-Z.mjs.map} +1 -1
- package/dist/{pinned-session-CjvR0Ge2.mjs → pinned-session-FYOFV_gB.mjs} +2 -2
- package/dist/{pinned-session-CjvR0Ge2.mjs.map → pinned-session-FYOFV_gB.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-8smxUOt9.d.mts → planner-SzkGh-3T.d.mts} +1 -1
- package/dist/{postgres-Be0jMJWI.mjs → postgres-BSmy1PYR.mjs} +2 -2
- package/dist/{postgres-Be0jMJWI.mjs.map → postgres-BSmy1PYR.mjs.map} +1 -1
- package/dist/postgres-adapter-B1RyJlWL.mjs +2 -0
- package/dist/postgres-adapter-B1RyJlWL.mjs.map +1 -0
- package/dist/postgres-adapter-BAqRfWl1.mjs +2 -0
- package/dist/postgres-adapter-BAqRfWl1.mjs.map +1 -0
- package/dist/postgres-result-BCUQf8b_.mjs +2 -0
- package/dist/{postgres-result-CYu1dyI_.mjs.map → postgres-result-BCUQf8b_.mjs.map} +1 -1
- package/dist/postgres.d.mts +3 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-Da00ilvv.mjs → provider-limits-V09frtmK.mjs} +2 -2
- package/dist/{provider-limits-Da00ilvv.mjs.map → provider-limits-V09frtmK.mjs.map} +1 -1
- package/dist/relation-bound-BrZLsSke.mjs +2 -0
- package/dist/relation-bound-BrZLsSke.mjs.map +1 -0
- package/dist/{result-parsing-8wEK3GY1.mjs → result-parsing-CQf_eCl8.mjs} +1 -1
- package/dist/{result-parsing-8wEK3GY1.mjs.map → result-parsing-CQf_eCl8.mjs.map} +1 -1
- package/dist/result-shape-Fi1-Fvri.mjs +2 -0
- package/dist/result-shape-Fi1-Fvri.mjs.map +1 -0
- package/dist/{rows-JXjhWwyb.mjs → rows-BiaiswSV.mjs} +2 -2
- package/dist/{rows-JXjhWwyb.mjs.map → rows-BiaiswSV.mjs.map} +1 -1
- package/dist/{scalar-CqqZ6jWd.mjs → scalar-Cm7nMFmO.mjs} +2 -2
- package/dist/{scalar-CqqZ6jWd.mjs.map → scalar-Cm7nMFmO.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/{schema-introspection-B2Rvqgut.mjs → schema-introspection-C1-XrQP4.mjs} +2 -2
- package/dist/{schema-introspection-B2Rvqgut.mjs.map → schema-introspection-C1-XrQP4.mjs.map} +1 -1
- package/dist/{schema-Cv-hhpl5.mjs → schema-tGtziyCJ.mjs} +2 -2
- package/dist/{schema-Cv-hhpl5.mjs.map → schema-tGtziyCJ.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/select-assembly-BjT_fDbu.mjs +2 -0
- package/dist/select-assembly-BjT_fDbu.mjs.map +1 -0
- package/dist/{settle-etgtP1WM.mjs → settle-C4w1GfTU.mjs} +2 -2
- package/dist/{settle-etgtP1WM.mjs.map → settle-C4w1GfTU.mjs.map} +1 -1
- package/dist/{sha256-CEYo7k7R.mjs → sha256-_Nu4s32f.mjs} +1 -1
- package/dist/{sha256-CEYo7k7R.mjs.map → sha256-_Nu4s32f.mjs.map} +1 -1
- package/dist/soft-delete.d.mts +3 -3
- package/dist/sql-BvHwL73I.mjs +2 -0
- package/dist/sql-BvHwL73I.mjs.map +1 -0
- package/dist/{sql-EsoN_7Et.d.mts → sql-Q_twK-wW.d.mts} +5 -0
- package/dist/{sql-statement-tokens-BW7Q-rF-.mjs → sql-statement-tokens-4J5l5Lyt.mjs} +1 -1
- package/dist/{sql-statement-tokens-BW7Q-rF-.mjs.map → sql-statement-tokens-4J5l5Lyt.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-CoDeF2h2.mjs +2 -0
- package/dist/sqlite-adapter-CoDeF2h2.mjs.map +1 -0
- package/dist/{sqlite-utils-DIOll4P7.mjs → sqlite-utils-C0TyzOys.mjs} +2 -2
- package/dist/{sqlite-utils-DIOll4P7.mjs.map → sqlite-utils-C0TyzOys.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/{standard-sql-mJt0RHHE.mjs → standard-sql-DmKF8msN.mjs} +2 -2
- package/dist/standard-sql-DmKF8msN.mjs.map +1 -0
- package/dist/{to-many-BSipkSbK.mjs → to-many-Btc9X5Ga.mjs} +2 -2
- package/dist/{to-many-BSipkSbK.mjs.map → to-many-Btc9X5Ga.mjs.map} +1 -1
- package/dist/transaction-operation-CU1zlxiG.mjs.map +1 -1
- package/dist/{utils-DjXObbUK.mjs → utils-DkAxKcDD.mjs} +2 -2
- package/dist/{utils-DjXObbUK.mjs.map → utils-DkAxKcDD.mjs.map} +1 -1
- package/dist/{v-CrJYqdzu.mjs → v-514RME2X.mjs} +2 -2
- package/dist/{v-CrJYqdzu.mjs.map → v-514RME2X.mjs.map} +1 -1
- package/dist/{validation-BQtO6srU.mjs → validation-C7Z6wTJa.mjs} +2 -2
- package/dist/{validation-BQtO6srU.mjs.map → validation-C7Z6wTJa.mjs.map} +1 -1
- package/dist/validation-gwZYm3Yn.mjs +2 -0
- package/dist/validation-gwZYm3Yn.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-BqzpyNmt.mjs → validator-CQOw7G3q.mjs} +2 -2
- package/dist/{validator-BqzpyNmt.mjs.map → validator-CQOw7G3q.mjs.map} +1 -1
- package/dist/version-n393hhwM.mjs +2 -0
- package/dist/{version-Dus3if78.mjs.map → version-n393hhwM.mjs.map} +1 -1
- package/package.json +14 -14
- package/dist/bind-parameter-capacity-qfEejeOX.mjs +0 -2
- package/dist/bind-parameter-capacity-qfEejeOX.mjs.map +0 -1
- package/dist/builder-DhxaVYP2.mjs +0 -2
- package/dist/builder-DhxaVYP2.mjs.map +0 -1
- package/dist/canonical-json-BReb5nFO.mjs.map +0 -1
- package/dist/chain-BjJ_M7EE.mjs +0 -2
- package/dist/chain-BjJ_M7EE.mjs.map +0 -1
- package/dist/client-BCgMXn6N.mjs +0 -2
- package/dist/client-BCgMXn6N.mjs.map +0 -1
- package/dist/client-q6ccRgdO.mjs.map +0 -1
- package/dist/datetime-physical-codec-BEqQbIP_.mjs +0 -2
- package/dist/datetime-physical-codec-BEqQbIP_.mjs.map +0 -1
- package/dist/driver-Ddt147dK.mjs +0 -2
- package/dist/error-mapping-C9WgitPi.mjs.map +0 -1
- package/dist/every-dpzVDwzu.mjs +0 -2
- package/dist/identity-Bj2EN6Ss.mjs +0 -2
- package/dist/identity-Bj2EN6Ss.mjs.map +0 -1
- package/dist/mysql-adapter-ClOoHKpn.mjs +0 -2
- package/dist/mysql-adapter-ClOoHKpn.mjs.map +0 -1
- package/dist/postgres-adapter-BoQ4RRwr.mjs +0 -2
- package/dist/postgres-adapter-BoQ4RRwr.mjs.map +0 -1
- package/dist/postgres-adapter-C_Mt8lVC.mjs +0 -2
- package/dist/postgres-adapter-C_Mt8lVC.mjs.map +0 -1
- package/dist/postgres-result-CYu1dyI_.mjs +0 -2
- package/dist/result-shape-DQc-tDJ5.mjs +0 -2
- package/dist/result-shape-DQc-tDJ5.mjs.map +0 -1
- package/dist/select-assembly-BxtETbG9.mjs +0 -2
- package/dist/select-assembly-BxtETbG9.mjs.map +0 -1
- package/dist/sql-Bhxq9arK.mjs +0 -2
- package/dist/sql-Bhxq9arK.mjs.map +0 -1
- package/dist/sqlite-adapter-B_LNxPA0.mjs +0 -2
- package/dist/sqlite-adapter-B_LNxPA0.mjs.map +0 -1
- package/dist/standard-sql-mJt0RHHE.mjs.map +0 -1
- package/dist/validation-BamBwne9.mjs +0 -2
- package/dist/validation-BamBwne9.mjs.map +0 -1
- package/dist/version-Dus3if78.mjs +0 -2
package/dist/pg.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, d as MigrationSessionAttestation, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-
|
|
1
|
+
import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, d as MigrationSessionAttestation, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-B4IWFJfv.mjs";
|
|
2
2
|
import { Pool, PoolClient, PoolConfig, PoolConfig as PgOptions } from "pg";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/pg/index.d.ts
|
|
@@ -35,6 +35,17 @@ interface PgDriverOptions {
|
|
|
35
35
|
* `false` keeps every body inline.
|
|
36
36
|
*/
|
|
37
37
|
sharedRelationBodies?: boolean;
|
|
38
|
+
/**
|
|
39
|
+
* The most relations (`FROM` items) one statement may reference. Past it, a
|
|
40
|
+
* statement states the recursive filters it repeats as key sets, and then
|
|
41
|
+
* joins the key sets a row tests, as far as it needs to fit: the answers are
|
|
42
|
+
* the same, some plans slower. PlanetScale Neki refuses a statement over
|
|
43
|
+
* 256: absent, a pool this driver makes reads each connection's startup,
|
|
44
|
+
* 256 on Neki and before the first connection, none on plain PostgreSQL (a
|
|
45
|
+
* supplied pool learns from Neki's first refusal). A stated bound always
|
|
46
|
+
* wins. Only where relation bodies are shared.
|
|
47
|
+
*/
|
|
48
|
+
relationsPerStatement?: number;
|
|
38
49
|
/**
|
|
39
50
|
* Your claim, at your risk, that every connection this pool opens is one
|
|
40
51
|
* server session for its whole life. It lifts migrations' refusal of
|
|
@@ -73,6 +84,13 @@ declare class PgDriver extends Driver<PgPool, PgPoolClient> {
|
|
|
73
84
|
* transport until a proven successful end.
|
|
74
85
|
*/
|
|
75
86
|
private readonly ownedPoolErrors;
|
|
87
|
+
/**
|
|
88
|
+
* The `server_version` the last connection this driver's own pool opened
|
|
89
|
+
* received at startup, read for the relation bound (`boundByServer`); a
|
|
90
|
+
* pool given its own `Client` class, or supplied, is not read.
|
|
91
|
+
*/
|
|
92
|
+
private serverVersion;
|
|
93
|
+
private readonly readsServer;
|
|
76
94
|
constructor(options?: PgDriverOptions);
|
|
77
95
|
/** Every host or URL this driver's pool connects through, for migration admission. */
|
|
78
96
|
protected migrationSessionEndpoints(): readonly unknown[];
|
|
@@ -92,6 +110,13 @@ declare class PgDriver extends Driver<PgPool, PgPoolClient> {
|
|
|
92
110
|
* two estates share. This driver listens only on the pool it made.
|
|
93
111
|
*/
|
|
94
112
|
protected initClient(): Promise<PgPool>;
|
|
113
|
+
/**
|
|
114
|
+
* node-postgres's `Client`, reading each connection's startup: it keeps no
|
|
115
|
+
* parameter status, so the `server_version` that names Neki is read as it
|
|
116
|
+
* arrives, before the connection is handed out (to a statement, or to a
|
|
117
|
+
* transaction before its callback builds any).
|
|
118
|
+
*/
|
|
119
|
+
private readingClient;
|
|
95
120
|
private readBackgroundPoolFailure;
|
|
96
121
|
/** Clear exactly the failure observed before an operation started. */
|
|
97
122
|
private clearBackgroundPoolFailure;
|
package/dist/pg.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{l as t,n,p as r,r as i}from"./error-mapping-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{l as t,n,p as r,r as i}from"./error-mapping-6op318w6.mjs";import{r as a}from"./validation-gwZYm3Yn.mjs";import{n as o}from"./transaction-4dfqals6.mjs";import{n as s}from"./suppressed-failure-Bdo2aK81.mjs";import{s as c}from"./execution-context-rJXTRVrJ.mjs";import{n as l}from"./client-Bhl2mWam.mjs";import{c as u,d,f,i as p,o as m,s as h,t as g,u as _}from"./driver-CQQbCQh9.mjs";import{t as v}from"./postgres-result-BCUQf8b_.mjs";import{t as y}from"./postgres-adapter-BAqRfWl1.mjs";import{n as b,t as x}from"./relation-bound-BrZLsSke.mjs";import{Client as S,Pool as C,types as w}from"pg";const identityParser=e=>e,T={getTypeParser:(e,t)=>[1082,1114,1184,1115,1182,1185].includes(e)&&t!==`binary`?identityParser:w.getTypeParser(e,t)};function createOwnedPoolErrorState(){let e=0,t={retain(n){e+=1,t.backgroundFailure={error:n,generation:e,isAvailable:!0}}};return t}function holdClientErrors(e){let t,retain=e=>{t??=e};return e.on(`error`,retain),{failure:()=>t,stop:()=>{e.off(`error`,retain)}}}const E=new Set([`user`,`password`,`host`,`port`]),D=[`sslmode`,`sslcert`,`sslkey`,`sslrootcert`];function connectionRecord(e,t){let n=e.connectionString??t;if(!n)return e;if(typeof e.password==`function`)throw new a('Driver "pg" cannot keep a password callback beside a connection URL: node-postgres reads the password from the URL. Pass `host`, `user` and `database` in `options` instead.',{meta:{driver:`pg`,operation:`configuration`}});let r=f(n),i;try{i=new URL(r)}catch{i=void 0}let o=Object.entries(e).filter(([e,t])=>t!==void 0&&(E.has(e)||e===`database`||e===`ssl`||e!==`connectionString`&&i?.searchParams.has(e)));if(o.length===0)return{...e,connectionString:r};if(i===void 0)throw new a(`Driver "pg" could not read its connection URL to apply the connection options beside it.`,{meta:{driver:`pg`,operation:`configuration`}});for(let[e,t]of o)if(i.searchParams.delete(e),e===`ssl`)for(let e of D)i.searchParams.delete(e);else e===`database`?i.pathname=`/${String(t)}`:E.has(e)&&(typeof t==`string`||typeof t==`number`)&&i.searchParams.set(e,String(t));return{...e,connectionString:i.href}}const O={pool:!0,options:!0,pgvector:!0,postgis:!0,databaseUrl:!0,namespace:!0,sharedRelationBodies:!0,relationsPerStatement:!0,migrationSessionAttestation:!0};var PgDriver=class extends g{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;ownedPoolErrors=new WeakMap;serverVersion;readsServer;constructor(e={}){super(`postgresql`,`pg`);let t=d(e);this.suppliedPool=e.pool;let n={...e.options};h(`pg`,e,!!(this.suppliedPool||n.host||n.connectionString)),this.connectionOptions=connectionRecord(n,e.databaseUrl),this.suppliedPool&&(this.client=this.suppliedPool),y(this,t,e),this.readsServer=this.suppliedPool===void 0&&n.Client===void 0&&x(this.adapter,()=>this.serverVersion),m(this,`migrationSessionAttestation`,_(e))}migrationSessionEndpoints(){let e=this.suppliedPool?Reflect.get(this.suppliedPool,`options`):void 0,t=typeof e==`object`&&e?e:{};return[this.connectionOptions.host,this.connectionOptions.connectionString,Reflect.get(t,`host`),Reflect.get(t,`connectionString`)]}initClient(){if(this.suppliedPool!==void 0)return Promise.resolve(this.suppliedPool);let e=new C({types:T,...this.connectionOptions,...this.readsServer?{Client:this.readingClient()}:{}}),t=createOwnedPoolErrorState();return this.ownedPoolErrors.set(e,t),e.on(`error`,t.retain),Promise.resolve(e)}readingClient(){let read=e=>{this.serverVersion=e};return class extends S{constructor(e){super(e),this.connection.on(`parameterStatus`,e=>{e.parameterName===`server_version`&&read(e.parameterValue)})}}}readBackgroundPoolFailure(e){return this.ownedPoolErrors.get(e)?.backgroundFailure}clearBackgroundPoolFailure(e,t){if(t===void 0||!t.isAvailable)return!1;t.isAvailable=!1;let n=this.ownedPoolErrors.get(e);return n?.backgroundFailure?.generation===t.generation&&(n.backgroundFailure=void 0),!0}consumeBackgroundPoolFailure(e,t){if(this.clearBackgroundPoolFailure(e,t))return t?.error}throwPoolQueryFailure(e,t,n,r,a,o){let c=this.consumeBackgroundPoolFailure(e,t);throw c===void 0?n:s(i(n,{driverName:this.driverName,dialect:this.dialect,model:o?.model,operation:o?.operation,correlationId:o?.correlationId,query:r,params:this.getDiagnosticParameters(a??[],o),diagnostics:this.getErrorDisclosure(o),forceContext:!0}),c)}async acquirePooledClient(e,t={},r){let i=this.readBackgroundPoolFailure(e),a=!1;try{return await p(async()=>{try{let t=await e.connect();return this.clearBackgroundPoolFailure(e,i),t}finally{a=!0}},e=>e.release(),r,{driverName:this.driverName,form:`callback`})}catch(r){if(!a)throw r;let o=this.consumeBackgroundPoolFailure(e,i);throw o===void 0?r:s(n(r,{driverName:this.driverName,model:t.model,operation:t.operation,correlationId:t.correlationId,diagnostics:this.getErrorDisclosure(t)},`Database connection failed after the pool reported a background failure`),o)}}async closeClient(e){if(e===this.suppliedPool)return;let t=this.ownedPoolErrors.get(e);try{await e.end()}catch(r){let i=this.consumeBackgroundPoolFailure(e,t?.backgroundFailure);throw i===void 0?r:s(n(r,{driverName:this.driverName},`Database disconnection failed`),i)}t!==void 0&&(e.off(`error`,t.retain),t.backgroundFailure=void 0,this.ownedPoolErrors.delete(e))}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,t,n,r,i){let a=r?.operation??i,o=this.readBackgroundPoolFailure(e),s=await e.query({text:t,values:n,types:T}).catch(i=>(b(this.adapter,i),this.throwPoolQueryFailure(e,o,i,t,n,r)));return this.clearBackgroundPoolFailure(e,o),{rows:s.rows,rowCount:v(s.rowCount,s.command,s.rows,{provider:`pg`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,n,i,a){if(`release`in e)throw t(this.driverName);let l=await this.acquirePooledClient(e,i,a?.maxWaitMs),u=holdClientErrors(l),withClientFailure=e=>{let t=u.failure();return t===void 0||t===e?e:s(e,t)},d,queryOrDiscard=async e=>{try{await l.query(e)}catch(e){throw d??=e instanceof Error?e:!0,withClientFailure(e)}};return r({begin:()=>queryOrDiscard(`BEGIN`),callback:async()=>{try{return await n(l)}catch(e){throw withClientFailure(e)}},commit:()=>{let e=u.failure();if(e!==void 0)throw e;return queryOrDiscard(`COMMIT`)},rollback:()=>u.failure()===void 0?queryOrDiscard(`ROLLBACK`):void 0,phases:c(i),close:()=>{try{let e=d??u.failure();if(e){l.release(e);return}l.release()}catch(e){throw super.transactionCleanupFailed(new o(`Driver "pg" could not release an unsafe transaction connection.`,{meta:{driver:`pg`,method:`$transaction`}})),e}finally{u.stop()}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(`release`in e)throw t(this.driverName);let n=await this.acquirePooledClient(e,{operation:`pinnedSession`}),r=holdClientErrors(n);return{session:n,lost:r.failure,release:e=>{try{n.release(r.failure()??(e?!0:void 0))}finally{r.stop()}return Promise.resolve()}}}};function createClient(e){u(e,`pg`,O);let{pool:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e;return l(e,new PgDriver({namespace:d(e),migrationSessionAttestation:_(e),pool:t||void 0,options:n,...Object.hasOwn(e,`databaseUrl`)?{databaseUrl:a}:{},pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement}))}export{PgDriver,createClient};
|
|
2
2
|
//# sourceMappingURL=pg.mjs.map
|
package/dist/pg.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pg.mjs","names":["pgTypes"],"sources":["../src/drivers/pg/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (node-postgres)\n *\n * Driver implementation for pg (node-postgres) with connection pooling.\n *\n * No statement pipelining. node-postgres has no pipeline mode: a `Client` holds\n * one query active at a time and drains the rest from an internal queue, so the\n * statements of a transaction always cost one round trip each no matter how\n * they are issued. Nothing here can change that, and nothing here tries to —\n * see the Phase 9 disposition in `docs/architecture/query-performance-plan.md`,\n * which measured the same limit on the postgres.js driver for different\n * reasons.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, TransactionError } from \"@errors\";\nimport { Pool, type PoolClient, type PoolConfig, types as pgTypes } from \"pg\";\nimport {\n Driver,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n normalizeDriverConnectionError,\n normalizeDriverError,\n} from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport {\n refuseEmptyDatabaseUrl,\n refuseUnknownDriverConfigKeys,\n systemRootAsVerifyFull,\n} from \"../shared/driver-options\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type { QueryResult } from \"../types\";\n\n// DATE (1082) and TIMESTAMP WITHOUT TIME ZONE (1114): pg's default parsers\n// build process-local Dates, shifting the stored value by the process\n// timezone. Return the raw strings instead — the shared result parser builds\n// UTC Dates from them, matching every other driver.\nconst DATE_OID = 1082;\nconst TIMESTAMP_OID = 1114;\nconst identityParser = (value: string) => value;\nconst utcSafeTypes: PoolConfig[\"types\"] = {\n getTypeParser: (oid: number, format?: string) => {\n if (\n [DATE_OID, TIMESTAMP_OID, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return pgTypes.getTypeParser(oid as never, format as never);\n },\n};\n\ninterface BackgroundPoolFailure {\n readonly error: Error;\n readonly generation: number;\n isAvailable: boolean;\n}\n\ninterface OwnedPoolErrorState {\n backgroundFailure?: BackgroundPoolFailure;\n readonly retain: (error: Error) => void;\n}\n\nfunction createOwnedPoolErrorState(): OwnedPoolErrorState {\n let generation = 0;\n const state: OwnedPoolErrorState = {\n retain(error) {\n generation += 1;\n state.backgroundFailure = { error, generation, isAvailable: true };\n },\n };\n return state;\n}\n\n/**\n * The `error` channel of one checked-out client, owned for as long as VibORM\n * holds that client.\n *\n * pg-pool removes its idle listener on checkout and puts it back on release,\n * so a connection that drops in between (a restart, a failover, a terminated\n * backend) would otherwise emit an unhandled `error` and end the process. The\n * first failure is kept: its holder refuses to commit after it and releases the\n * client with it, so the pool destroys that connection instead of reusing it.\n *\n * This holds for a supplied pool too. Its `error` event stays the caller's, but\n * a checked-out client is the holder's to answer for until it is released.\n */\ninterface HeldClientErrors {\n readonly failure: () => Error | undefined;\n readonly stop: () => void;\n}\n\nfunction holdClientErrors(client: PgPoolClient): HeldClientErrors {\n let failure: Error | undefined;\n const retain = (error: Error) => {\n failure ??= error;\n };\n client.on(\"error\", retain);\n return {\n failure: () => failure,\n stop: () => {\n client.off(\"error\", retain);\n },\n };\n}\n\n/** The keys node-postgres's URL parser reads from the query before the authority. */\nconst URL_QUERY_KEYS = new Set([\"user\", \"password\", \"host\", \"port\"]);\n/** The query parameters node-postgres derives `ssl` from. */\nconst URL_SSL_KEYS = [\"sslmode\", \"sslcert\", \"sslkey\", \"sslrootcert\"];\n\n/**\n * The pool's connection record: the caller's options, with `databaseUrl` as\n * the connection string unless `options.connectionString` names one, and each\n * connection option they set written into that URL so that it wins.\n *\n * node-postgres parses the connection string over the options beside it and\n * fills the connection keys the URL lacks with empty values, so a per-tenant\n * URL without a password lost `options.password` from a secret, and the URL's\n * port replaced `options.port`. Its parser prefers `user`, `password`, `host`\n * and `port` from the query and reads the database from the path, so an\n * explicit key is written there; any other option the query also names is\n * dropped from it, and an explicit `ssl` drops the parameters that derive one.\n * A password callback cannot be written into a URL, and node-postgres would\n * replace it with the URL's password, so one beside a URL is refused.\n */\nfunction connectionRecord(\n options: PoolConfig,\n databaseUrl: string | undefined\n): PoolConfig {\n const given = options.connectionString ?? databaseUrl;\n if (!given) return options;\n if (typeof options.password === \"function\") {\n throw new ClientInitializationError(\n 'Driver \"pg\" cannot keep a password callback beside a connection URL: node-postgres reads the password from the URL. Pass `host`, `user` and `database` in `options` instead.',\n { meta: { driver: \"pg\", operation: \"configuration\" } }\n );\n }\n const connectionString = systemRootAsVerifyFull(given);\n let url: URL | undefined;\n try {\n url = new URL(connectionString);\n } catch {\n url = undefined;\n }\n const entries: [string, unknown][] = Object.entries(options);\n const overrides = entries.filter(\n ([key, value]) =>\n value !== undefined &&\n (URL_QUERY_KEYS.has(key) ||\n key === \"database\" ||\n key === \"ssl\" ||\n (key !== \"connectionString\" && url?.searchParams.has(key)))\n );\n if (overrides.length === 0) return { ...options, connectionString };\n if (url === undefined) {\n throw new ClientInitializationError(\n 'Driver \"pg\" could not read its connection URL to apply the connection options beside it.',\n { meta: { driver: \"pg\", operation: \"configuration\" } }\n );\n }\n for (const [key, value] of overrides) {\n url.searchParams.delete(key);\n if (key === \"ssl\") {\n for (const sslKey of URL_SSL_KEYS) url.searchParams.delete(sslKey);\n } else if (key === \"database\") {\n url.pathname = `/${String(value)}`;\n } else if (\n URL_QUERY_KEYS.has(key) &&\n (typeof value === \"string\" || typeof value === \"number\")\n ) {\n url.searchParams.set(key, String(value));\n }\n }\n return { ...options, connectionString: url.href };\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PoolConfig as PgOptions } from \"pg\";\n\ninterface PgErrorEvents {\n on(event: \"error\", listener: (error: Error) => void): unknown;\n off(event: \"error\", listener: (error: Error) => void): unknown;\n}\n\n/** The part of a node-postgres `PoolClient` this driver uses. */\ninterface PgPoolClient\n extends Pick<PoolClient, \"query\" | \"release\">,\n PgErrorEvents {}\n\n/**\n * The part of a node-postgres `Pool` this driver uses, so any pool with that\n * shape is accepted. A Neon WebSocket `Pool` (`@neondatabase/serverless`) is\n * node-postgres's pool over a WebSocket and runs here unchanged, but its\n * bundled copy of the pg declarations lags `@types/pg`: in 8.23 a\n * `PoolClient` is a whole `Client`, and the full `Pool` type refused Neon's.\n */\ninterface PgPool extends Pick<Pool, \"query\" | \"end\">, PgErrorEvents {\n connect(): Promise<PgPoolClient>;\n}\n\nexport interface PgDriverOptions {\n pool?: PgPool;\n options?: PoolConfig;\n pgvector?: boolean;\n postgis?: boolean;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Each relation filter body a statement repeats is stated once, in a\n * `WITH`, as the key set its arms test: the answers are the same, the\n * statement smaller, and a server that bounds the relations one statement\n * references (PlanetScale's Neki: 256) accepts it. Defaults to `true`;\n * `false` keeps every body inline.\n */\n sharedRelationBodies?: boolean;\n /**\n * Your claim, at your risk, that every connection this pool opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport type PgClientConfig<C extends DriverConfig> = PgDriverOptions & C;\n\nconst PG_CONFIG_KEYS: Record<keyof PgDriverOptions, true> = {\n pool: true,\n options: true,\n pgvector: true,\n postgis: true,\n databaseUrl: true,\n namespace: true,\n sharedRelationBodies: true,\n migrationSessionAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PgDriver extends Driver<PgPool, PgPoolClient> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled here, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed\n * and may be sharing with the caller's own code.\n */\n private readonly suppliedPool: PgPool | undefined;\n /**\n * The caller's connection record, copied once.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database, connectionString — all live here,\n * with the caller's `databaseUrl` merged in (see `connectionRecord`).\n */\n private readonly connectionOptions: PoolConfig;\n /**\n * The listener and latest idle failure for each pool this driver created.\n *\n * Pool identity matters after a failed `end()`: the base lifecycle\n * quarantines that exact pool for a later disconnect retry, while this state\n * keeps its error listener and retained evidence attached to the same\n * transport until a proven successful end.\n */\n private readonly ownedPoolErrors = new WeakMap<object, OwnedPoolErrorState>();\n\n constructor(options: PgDriverOptions = {}) {\n super(\"postgresql\", \"pg\");\n const namespace = resolveNamespaceOption(options);\n this.suppliedPool = options.pool;\n const connection = { ...options.options };\n refuseEmptyDatabaseUrl(\n \"pg\",\n options,\n Boolean(\n this.suppliedPool || connection.host || connection.connectionString\n )\n );\n this.connectionOptions = connectionRecord(connection, options.databaseUrl);\n\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n\n installPostgresAdapter(this, namespace, options);\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's pool connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const supplied: unknown = this.suppliedPool\n ? Reflect.get(this.suppliedPool, \"options\")\n : undefined;\n const pool =\n typeof supplied === \"object\" && supplied !== null ? supplied : {};\n return [\n this.connectionOptions.host,\n this.connectionOptions.connectionString,\n Reflect.get(pool, \"host\"),\n Reflect.get(pool, \"connectionString\"),\n ];\n }\n\n /**\n * The pool this driver connects through.\n *\n * A caller's pool is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second pool behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n *\n * It is also returned UNSUBSCRIBED. A supplied pool is borrowed transport and\n * its events belong to its owner: an 'error' listener added here is the very\n * thing that stops Node from throwing, so VibORM would be silencing a crash\n * for a caller who never asked it to — and for the other consumers of a pool\n * two estates share. This driver listens only on the pool it made.\n */\n protected initClient(): Promise<PgPool> {\n if (this.suppliedPool !== undefined) {\n return Promise.resolve(this.suppliedPool);\n }\n const pool = new Pool({ types: utcSafeTypes, ...this.connectionOptions });\n const errorState = createOwnedPoolErrorState();\n this.ownedPoolErrors.set(pool, errorState);\n pool.on(\"error\", errorState.retain);\n return Promise.resolve(pool);\n }\n\n private readBackgroundPoolFailure(\n pool: PgPool | PgPoolClient\n ): BackgroundPoolFailure | undefined {\n return this.ownedPoolErrors.get(pool)?.backgroundFailure;\n }\n\n /** Clear exactly the failure observed before an operation started. */\n private clearBackgroundPoolFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n ): boolean {\n if (observed === undefined || !observed.isAvailable) return false;\n observed.isAvailable = false;\n const state = this.ownedPoolErrors.get(pool);\n if (state?.backgroundFailure?.generation === observed.generation) {\n state.backgroundFailure = undefined;\n }\n return true;\n }\n\n /** Claim one retained failure for one failed acquisition, at most once. */\n private consumeBackgroundPoolFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n ): Error | undefined {\n if (!this.clearBackgroundPoolFailure(pool, observed)) return undefined;\n return observed?.error;\n }\n\n /** Surface one pool-owned idle failure beside one pool query failure. */\n private throwPoolQueryFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined,\n error: unknown,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined\n ): never {\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const queryFailure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n model: context?.model,\n operation: context?.operation,\n correlationId: context?.correlationId,\n query: sql,\n params: this.getDiagnosticParameters(params ?? [], context),\n diagnostics: this.getErrorDisclosure(context),\n forceContext: true,\n });\n throw withSuppressedFailure(queryFailure, background);\n }\n\n /**\n * One pooled connection, and — when there is none to be had — the current\n * acquisition failure as primary, with the pool's last background failure\n * retained beside it.\n *\n * The acquisition rejection is the failure of the requested action, so it\n * stays primary. The background report arrived outside every request and is\n * retained through the shared suppressed-failure record. Reported once and\n * released, so the next failure speaks for itself rather than inheriting an\n * explanation that has already been given. An acquisition that fails with\n * nothing retained is left exactly as it was.\n */\n private async acquirePooledClient(\n pool: PgPool,\n context: QueryExecutionContext = {},\n maxWaitMs?: number\n ): Promise<PgPoolClient> {\n const observed = this.readBackgroundPoolFailure(pool);\n let acquisitionSettled = false;\n try {\n const client = await acquireWithMaxWait(\n async () => {\n try {\n const acquired = await pool.connect();\n // This runs even when maxWait has already rejected the caller: a\n // late success healed the pre-start failure before the abandoned\n // client goes straight back to the pool.\n this.clearBackgroundPoolFailure(pool, observed);\n return acquired;\n } finally {\n acquisitionSettled = true;\n }\n },\n (acquired) => acquired.release(),\n maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n return client;\n } catch (error) {\n // A maxWait winner abandons the acquisition. Its eventual rejection is\n // observed by acquireWithMaxWait, but it must not consume evidence into\n // a promise whose result no caller will ever inspect.\n if (!acquisitionSettled) throw error;\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const acquisitionFailure = normalizeDriverConnectionError(\n error,\n {\n driverName: this.driverName,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n diagnostics: this.getErrorDisclosure(context),\n },\n \"Database connection failed after the pool reported a background failure\"\n );\n throw withSuppressedFailure(acquisitionFailure, background);\n }\n }\n\n /**\n * A supplied pool belongs to the caller, who may be sharing it with other\n * clients — two schema-scoped estates over one pool is the documented shape\n * — and §5.3's rule is that VibORM never changes a caller's connection\n * state. `$disconnect()` used to end it regardless, so disconnecting one\n * client tore down every other consumer of that pool.\n *\n * The test is on the pool's IDENTITY against what construction captured, so\n * it answers for the pool actually being closed rather than for whatever the\n * caller's record says now: every pool this driver made is ended, and the one\n * it was handed never is.\n */\n protected async closeClient(pool: PgPool): Promise<void> {\n if (pool === this.suppliedPool) {\n return;\n }\n const errorState = this.ownedPoolErrors.get(pool);\n try {\n await pool.end();\n } catch (error) {\n const background = this.consumeBackgroundPoolFailure(\n pool,\n errorState?.backgroundFailure\n );\n if (background === undefined) throw error;\n const disconnectFailure = normalizeDriverConnectionError(\n error,\n { driverName: this.driverName },\n \"Database disconnection failed\"\n );\n throw withSuppressedFailure(disconnectFailure, background);\n }\n // AFTER a proven end, not before it: `end()` disposes idle clients whose\n // own listeners can still re-emit on the pool. If end rejects, the still\n // live pool keeps containment; its pre-start evidence travels on the public\n // disconnect failure, exactly once.\n if (errorState !== undefined) {\n pool.off(\"error\", errorState.retain);\n errorState.backgroundFailure = undefined;\n this.ownedPoolErrors.delete(pool);\n }\n }\n\n protected async execute<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"execute\");\n }\n\n protected async executeRaw<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const observed = this.readBackgroundPoolFailure(client);\n const result = await client\n .query({ text: sql, values: params, types: utcSafeTypes })\n .catch((error: unknown) =>\n this.throwPoolQueryFailure(\n client,\n observed,\n error,\n sql,\n params,\n context\n )\n );\n // `Pool.query` includes an acquisition. Its success proves transport\n // recovery, but only for evidence that predates this exact operation.\n this.clearBackgroundPoolFailure(client, observed);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n { provider: \"pg\", operation }\n ),\n };\n }\n\n /**\n * PostgreSQL takes the isolation level as the first statement inside the\n * transaction, and node-postgres hands out a pooled client we can wait for\n * with a bound (and release if we stop waiting).\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: PgPool | PgPoolClient,\n fn: (tx: PgPoolClient) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction\n const poolClient = await this.acquirePooledClient(\n client,\n context,\n options?.maxWaitMs\n );\n const clientErrors = holdClientErrors(poolClient);\n // A step's own failure stays primary; a different client failure travels\n // beside it through the shared evidence owner instead of being lost.\n const withClientFailure = (error: unknown): unknown => {\n const failure = clientErrors.failure();\n return failure === undefined || failure === error\n ? error\n : withSuppressedFailure(error, failure);\n };\n let releaseError: Error | boolean | undefined;\n const queryOrDiscard = async (statement: string) => {\n try {\n await poolClient.query(statement);\n } catch (error) {\n releaseError ??= error instanceof Error ? error : true;\n throw withClientFailure(error);\n }\n };\n return runTransactionLifecycle({\n begin: () => queryOrDiscard(\"BEGIN\"),\n callback: async () => {\n try {\n return await fn(poolClient);\n } catch (error) {\n throw withClientFailure(error);\n }\n },\n commit: () => {\n // A callback that settles after its connection failed must not commit:\n // whatever it awaited meanwhile never reached the database.\n const failure = clientErrors.failure();\n if (failure !== undefined) throw failure;\n return queryOrDiscard(\"COMMIT\");\n },\n // The server ends a transaction with its session; a ROLLBACK sent on a\n // client that is no longer queryable would only add a second failure.\n rollback: () =>\n clientErrors.failure() === undefined\n ? queryOrDiscard(\"ROLLBACK\")\n : undefined,\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n const discard = releaseError ?? clientErrors.failure();\n if (discard) {\n poolClient.release(discard);\n return;\n }\n poolClient.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"pg\" could not release an unsafe transaction connection.',\n { meta: { driver: \"pg\", method: \"$transaction\" } }\n )\n );\n throw error;\n } finally {\n clientErrors.stop();\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // The failed PoolClient was discarded with release(error); the pool stays usable.\n }\n\n /**\n * One `PoolClient` from `pool.connect()` — plan §3.5's pinned producer for\n * `pg`. `release(true)` destroys the connection instead of returning it, so a\n * session whose advisory-lock state is unknown never re-enters the pool.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PgPool | PgPoolClient>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const poolClient = await this.acquirePooledClient(client, {\n operation: \"pinnedSession\",\n });\n const clientErrors = holdClientErrors(poolClient);\n return {\n session: poolClient,\n // The client's own `error` event is how pg reports a socket that died\n // between or under statements; the pinned session then sends nothing\n // more on it (plan S2). Release destroys it either way.\n lost: clientErrors.failure,\n release: (discard) => {\n try {\n poolClient.release(\n clientErrors.failure() ?? (discard ? true : undefined)\n );\n } finally {\n clientErrors.stop();\n }\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PgClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PgDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: PgDriver }>]: LinkedClientConfig<\n C & { driver: PgDriver }\n >[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pg\", PG_CONFIG_KEYS);\n const { pool, options = {}, pgvector, postgis, databaseUrl } = config;\n const driver = new PgDriver({\n // Namespace, then attestation: the order a refusal reports in.\n namespace: resolveNamespaceOption(config),\n migrationSessionAttestation:\n resolveMigrationSessionAttestationOption(config),\n // Only a supplied pool counts: a falsy one leaves the driver to build its own.\n pool: pool || undefined,\n options,\n // Present even when undefined: the driver refuses an empty one (parity-18).\n ...(Object.hasOwn(config, \"databaseUrl\") ? { databaseUrl } : {}),\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n });\n\n return createClientFromDriverConfig<S, C, PgD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AAI,EACF,kEACA,CAAE,KAAM,CAAE,OAAQ,KAAM,OAAQ,eAAgB,CAAE,CACnD,CACF,CACK,SACE,CACR,EAAa,MAAM,GAGxB,CAAC,CAGJ,yBAA4C,EAAqB,EASjE,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,YAAa,EACf,MAAM,EAA+B,KAAK,WAAW,CAEvD,IAAM,EAAa,MAAM,KAAK,oBAAoB,EAAQ,CACxD,UAAW,gBACZ,CAAC,CACI,EAAe,iBAAiB,EAAW,CACjD,MAAO,CACL,QAAS,EAIT,KAAM,EAAa,QACnB,QAAU,GAAY,CACpB,GAAI,CACF,EAAW,QACT,EAAa,SAAS,GAAK,EAAU,GAAO,IAAA,IAC7C,QACO,CACR,EAAa,MAAM,CAErB,OAAO,QAAQ,SAAS,EAE3B,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,KAAM,EAAe,CAC3D,GAAM,CAAE,OAAM,UAAU,EAAE,CAAE,WAAU,UAAS,eAAgB,EAgB/D,OAAO,EAA6C,EAfrC,IAAI,SAAS,CAE1B,UAAW,EAAuB,EAAO,CACzC,4BACE,EAAyC,EAAO,CAElD,KAAM,GAAQ,IAAA,GACd,UAEA,GAAI,OAAO,OAAO,EAAQ,cAAc,CAAG,CAAE,cAAa,CAAG,EAAE,CAC/D,WACA,UACA,qBAAsB,EAAO,qBAC9B,CAAC,CAEiE"}
|
|
1
|
+
{"version":3,"file":"pg.mjs","names":["pgTypes"],"sources":["../src/drivers/pg/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (node-postgres)\n *\n * Driver implementation for pg (node-postgres) with connection pooling.\n *\n * No statement pipelining. node-postgres has no pipeline mode: a `Client` holds\n * one query active at a time and drains the rest from an internal queue, so the\n * statements of a transaction always cost one round trip each no matter how\n * they are issued. Nothing here can change that, and nothing here tries to —\n * see the Phase 9 disposition in `docs/architecture/query-performance-plan.md`,\n * which measured the same limit on the postgres.js driver for different\n * reasons.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, TransactionError } from \"@errors\";\nimport {\n Client,\n type ClientConfig,\n Pool,\n type PoolClient,\n type PoolConfig,\n types as pgTypes,\n} from \"pg\";\nimport {\n Driver,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n normalizeDriverConnectionError,\n normalizeDriverError,\n} from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport {\n refuseEmptyDatabaseUrl,\n refuseUnknownDriverConfigKeys,\n systemRootAsVerifyFull,\n} from \"../shared/driver-options\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport { boundByServer, learnRelationLimit } from \"../shared/relation-bound\";\nimport type { QueryResult } from \"../types\";\n\n// DATE (1082) and TIMESTAMP WITHOUT TIME ZONE (1114): pg's default parsers\n// build process-local Dates, shifting the stored value by the process\n// timezone. Return the raw strings instead — the shared result parser builds\n// UTC Dates from them, matching every other driver.\nconst DATE_OID = 1082;\nconst TIMESTAMP_OID = 1114;\nconst identityParser = (value: string) => value;\nconst utcSafeTypes: PoolConfig[\"types\"] = {\n getTypeParser: (oid: number, format?: string) => {\n if (\n [DATE_OID, TIMESTAMP_OID, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return pgTypes.getTypeParser(oid as never, format as never);\n },\n};\n\ninterface BackgroundPoolFailure {\n readonly error: Error;\n readonly generation: number;\n isAvailable: boolean;\n}\n\ninterface OwnedPoolErrorState {\n backgroundFailure?: BackgroundPoolFailure;\n readonly retain: (error: Error) => void;\n}\n\nfunction createOwnedPoolErrorState(): OwnedPoolErrorState {\n let generation = 0;\n const state: OwnedPoolErrorState = {\n retain(error) {\n generation += 1;\n state.backgroundFailure = { error, generation, isAvailable: true };\n },\n };\n return state;\n}\n\n/**\n * The `error` channel of one checked-out client, owned for as long as VibORM\n * holds that client.\n *\n * pg-pool removes its idle listener on checkout and puts it back on release,\n * so a connection that drops in between (a restart, a failover, a terminated\n * backend) would otherwise emit an unhandled `error` and end the process. The\n * first failure is kept: its holder refuses to commit after it and releases the\n * client with it, so the pool destroys that connection instead of reusing it.\n *\n * This holds for a supplied pool too. Its `error` event stays the caller's, but\n * a checked-out client is the holder's to answer for until it is released.\n */\ninterface HeldClientErrors {\n readonly failure: () => Error | undefined;\n readonly stop: () => void;\n}\n\nfunction holdClientErrors(client: PgPoolClient): HeldClientErrors {\n let failure: Error | undefined;\n const retain = (error: Error) => {\n failure ??= error;\n };\n client.on(\"error\", retain);\n return {\n failure: () => failure,\n stop: () => {\n client.off(\"error\", retain);\n },\n };\n}\n\n/** The keys node-postgres's URL parser reads from the query before the authority. */\nconst URL_QUERY_KEYS = new Set([\"user\", \"password\", \"host\", \"port\"]);\n/** The query parameters node-postgres derives `ssl` from. */\nconst URL_SSL_KEYS = [\"sslmode\", \"sslcert\", \"sslkey\", \"sslrootcert\"];\n\n/**\n * The pool's connection record: the caller's options, with `databaseUrl` as\n * the connection string unless `options.connectionString` names one, and each\n * connection option they set written into that URL so that it wins.\n *\n * node-postgres parses the connection string over the options beside it and\n * fills the connection keys the URL lacks with empty values, so a per-tenant\n * URL without a password lost `options.password` from a secret, and the URL's\n * port replaced `options.port`. Its parser prefers `user`, `password`, `host`\n * and `port` from the query and reads the database from the path, so an\n * explicit key is written there; any other option the query also names is\n * dropped from it, and an explicit `ssl` drops the parameters that derive one.\n * A password callback cannot be written into a URL, and node-postgres would\n * replace it with the URL's password, so one beside a URL is refused.\n */\nfunction connectionRecord(\n options: PoolConfig,\n databaseUrl: string | undefined\n): PoolConfig {\n const given = options.connectionString ?? databaseUrl;\n if (!given) return options;\n if (typeof options.password === \"function\") {\n throw new ClientInitializationError(\n 'Driver \"pg\" cannot keep a password callback beside a connection URL: node-postgres reads the password from the URL. Pass `host`, `user` and `database` in `options` instead.',\n { meta: { driver: \"pg\", operation: \"configuration\" } }\n );\n }\n const connectionString = systemRootAsVerifyFull(given);\n let url: URL | undefined;\n try {\n url = new URL(connectionString);\n } catch {\n url = undefined;\n }\n const entries: [string, unknown][] = Object.entries(options);\n const overrides = entries.filter(\n ([key, value]) =>\n value !== undefined &&\n (URL_QUERY_KEYS.has(key) ||\n key === \"database\" ||\n key === \"ssl\" ||\n (key !== \"connectionString\" && url?.searchParams.has(key)))\n );\n if (overrides.length === 0) return { ...options, connectionString };\n if (url === undefined) {\n throw new ClientInitializationError(\n 'Driver \"pg\" could not read its connection URL to apply the connection options beside it.',\n { meta: { driver: \"pg\", operation: \"configuration\" } }\n );\n }\n for (const [key, value] of overrides) {\n url.searchParams.delete(key);\n if (key === \"ssl\") {\n for (const sslKey of URL_SSL_KEYS) url.searchParams.delete(sslKey);\n } else if (key === \"database\") {\n url.pathname = `/${String(value)}`;\n } else if (\n URL_QUERY_KEYS.has(key) &&\n (typeof value === \"string\" || typeof value === \"number\")\n ) {\n url.searchParams.set(key, String(value));\n }\n }\n return { ...options, connectionString: url.href };\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PoolConfig as PgOptions } from \"pg\";\n\ninterface PgErrorEvents {\n on(event: \"error\", listener: (error: Error) => void): unknown;\n off(event: \"error\", listener: (error: Error) => void): unknown;\n}\n\n/** The part of a node-postgres `PoolClient` this driver uses. */\ninterface PgPoolClient\n extends Pick<PoolClient, \"query\" | \"release\">,\n PgErrorEvents {}\n\n/**\n * The part of a node-postgres `Pool` this driver uses, so any pool with that\n * shape is accepted. A Neon WebSocket `Pool` (`@neondatabase/serverless`) is\n * node-postgres's pool over a WebSocket and runs here unchanged, but its\n * bundled copy of the pg declarations lags `@types/pg`: in 8.23 a\n * `PoolClient` is a whole `Client`, and the full `Pool` type refused Neon's.\n */\ninterface PgPool extends Pick<Pool, \"query\" | \"end\">, PgErrorEvents {\n connect(): Promise<PgPoolClient>;\n}\n\nexport interface PgDriverOptions {\n pool?: PgPool;\n options?: PoolConfig;\n pgvector?: boolean;\n postgis?: boolean;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Each relation filter body a statement repeats is stated once, in a\n * `WITH`, as the key set its arms test: the answers are the same, the\n * statement smaller, and a server that bounds the relations one statement\n * references (PlanetScale's Neki: 256) accepts it. Defaults to `true`;\n * `false` keeps every body inline.\n */\n sharedRelationBodies?: boolean;\n /**\n * The most relations (`FROM` items) one statement may reference. Past it, a\n * statement states the recursive filters it repeats as key sets, and then\n * joins the key sets a row tests, as far as it needs to fit: the answers are\n * the same, some plans slower. PlanetScale Neki refuses a statement over\n * 256: absent, a pool this driver makes reads each connection's startup,\n * 256 on Neki and before the first connection, none on plain PostgreSQL (a\n * supplied pool learns from Neki's first refusal). A stated bound always\n * wins. Only where relation bodies are shared.\n */\n relationsPerStatement?: number;\n /**\n * Your claim, at your risk, that every connection this pool opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport type PgClientConfig<C extends DriverConfig> = PgDriverOptions & C;\n\nconst PG_CONFIG_KEYS: Record<keyof PgDriverOptions, true> = {\n pool: true,\n options: true,\n pgvector: true,\n postgis: true,\n databaseUrl: true,\n namespace: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n migrationSessionAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PgDriver extends Driver<PgPool, PgPoolClient> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled here, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed\n * and may be sharing with the caller's own code.\n */\n private readonly suppliedPool: PgPool | undefined;\n /**\n * The caller's connection record, copied once.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database, connectionString — all live here,\n * with the caller's `databaseUrl` merged in (see `connectionRecord`).\n */\n private readonly connectionOptions: PoolConfig;\n /**\n * The listener and latest idle failure for each pool this driver created.\n *\n * Pool identity matters after a failed `end()`: the base lifecycle\n * quarantines that exact pool for a later disconnect retry, while this state\n * keeps its error listener and retained evidence attached to the same\n * transport until a proven successful end.\n */\n private readonly ownedPoolErrors = new WeakMap<object, OwnedPoolErrorState>();\n /**\n * The `server_version` the last connection this driver's own pool opened\n * received at startup, read for the relation bound (`boundByServer`); a\n * pool given its own `Client` class, or supplied, is not read.\n */\n private serverVersion: string | undefined;\n private readonly readsServer: boolean;\n\n constructor(options: PgDriverOptions = {}) {\n super(\"postgresql\", \"pg\");\n const namespace = resolveNamespaceOption(options);\n this.suppliedPool = options.pool;\n const connection = { ...options.options };\n refuseEmptyDatabaseUrl(\n \"pg\",\n options,\n Boolean(\n this.suppliedPool || connection.host || connection.connectionString\n )\n );\n this.connectionOptions = connectionRecord(connection, options.databaseUrl);\n\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n\n installPostgresAdapter(this, namespace, options);\n this.readsServer =\n this.suppliedPool === undefined &&\n connection.Client === undefined &&\n boundByServer(this.adapter, () => this.serverVersion);\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's pool connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const supplied: unknown = this.suppliedPool\n ? Reflect.get(this.suppliedPool, \"options\")\n : undefined;\n const pool =\n typeof supplied === \"object\" && supplied !== null ? supplied : {};\n return [\n this.connectionOptions.host,\n this.connectionOptions.connectionString,\n Reflect.get(pool, \"host\"),\n Reflect.get(pool, \"connectionString\"),\n ];\n }\n\n /**\n * The pool this driver connects through.\n *\n * A caller's pool is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second pool behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n *\n * It is also returned UNSUBSCRIBED. A supplied pool is borrowed transport and\n * its events belong to its owner: an 'error' listener added here is the very\n * thing that stops Node from throwing, so VibORM would be silencing a crash\n * for a caller who never asked it to — and for the other consumers of a pool\n * two estates share. This driver listens only on the pool it made.\n */\n protected initClient(): Promise<PgPool> {\n if (this.suppliedPool !== undefined) {\n return Promise.resolve(this.suppliedPool);\n }\n const pool = new Pool({\n types: utcSafeTypes,\n ...this.connectionOptions,\n ...(this.readsServer ? { Client: this.readingClient() } : {}),\n });\n const errorState = createOwnedPoolErrorState();\n this.ownedPoolErrors.set(pool, errorState);\n pool.on(\"error\", errorState.retain);\n return Promise.resolve(pool);\n }\n\n /**\n * node-postgres's `Client`, reading each connection's startup: it keeps no\n * parameter status, so the `server_version` that names Neki is read as it\n * arrives, before the connection is handed out (to a statement, or to a\n * transaction before its callback builds any).\n */\n private readingClient(): typeof Client {\n const read = (version: string) => {\n this.serverVersion = version;\n };\n return class extends Client {\n constructor(config?: string | ClientConfig) {\n super(config);\n this.connection.on(\n \"parameterStatus\",\n (status: { parameterName: string; parameterValue: string }) => {\n if (status.parameterName === \"server_version\")\n read(status.parameterValue);\n }\n );\n }\n };\n }\n\n private readBackgroundPoolFailure(\n pool: PgPool | PgPoolClient\n ): BackgroundPoolFailure | undefined {\n return this.ownedPoolErrors.get(pool)?.backgroundFailure;\n }\n\n /** Clear exactly the failure observed before an operation started. */\n private clearBackgroundPoolFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n ): boolean {\n if (observed === undefined || !observed.isAvailable) return false;\n observed.isAvailable = false;\n const state = this.ownedPoolErrors.get(pool);\n if (state?.backgroundFailure?.generation === observed.generation) {\n state.backgroundFailure = undefined;\n }\n return true;\n }\n\n /** Claim one retained failure for one failed acquisition, at most once. */\n private consumeBackgroundPoolFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n ): Error | undefined {\n if (!this.clearBackgroundPoolFailure(pool, observed)) return undefined;\n return observed?.error;\n }\n\n /** Surface one pool-owned idle failure beside one pool query failure. */\n private throwPoolQueryFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined,\n error: unknown,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined\n ): never {\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const queryFailure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n model: context?.model,\n operation: context?.operation,\n correlationId: context?.correlationId,\n query: sql,\n params: this.getDiagnosticParameters(params ?? [], context),\n diagnostics: this.getErrorDisclosure(context),\n forceContext: true,\n });\n throw withSuppressedFailure(queryFailure, background);\n }\n\n /**\n * One pooled connection, and — when there is none to be had — the current\n * acquisition failure as primary, with the pool's last background failure\n * retained beside it.\n *\n * The acquisition rejection is the failure of the requested action, so it\n * stays primary. The background report arrived outside every request and is\n * retained through the shared suppressed-failure record. Reported once and\n * released, so the next failure speaks for itself rather than inheriting an\n * explanation that has already been given. An acquisition that fails with\n * nothing retained is left exactly as it was.\n */\n private async acquirePooledClient(\n pool: PgPool,\n context: QueryExecutionContext = {},\n maxWaitMs?: number\n ): Promise<PgPoolClient> {\n const observed = this.readBackgroundPoolFailure(pool);\n let acquisitionSettled = false;\n try {\n const client = await acquireWithMaxWait(\n async () => {\n try {\n const acquired = await pool.connect();\n // This runs even when maxWait has already rejected the caller: a\n // late success healed the pre-start failure before the abandoned\n // client goes straight back to the pool.\n this.clearBackgroundPoolFailure(pool, observed);\n return acquired;\n } finally {\n acquisitionSettled = true;\n }\n },\n (acquired) => acquired.release(),\n maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n return client;\n } catch (error) {\n // A maxWait winner abandons the acquisition. Its eventual rejection is\n // observed by acquireWithMaxWait, but it must not consume evidence into\n // a promise whose result no caller will ever inspect.\n if (!acquisitionSettled) throw error;\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const acquisitionFailure = normalizeDriverConnectionError(\n error,\n {\n driverName: this.driverName,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n diagnostics: this.getErrorDisclosure(context),\n },\n \"Database connection failed after the pool reported a background failure\"\n );\n throw withSuppressedFailure(acquisitionFailure, background);\n }\n }\n\n /**\n * A supplied pool belongs to the caller, who may be sharing it with other\n * clients — two schema-scoped estates over one pool is the documented shape\n * — and §5.3's rule is that VibORM never changes a caller's connection\n * state. `$disconnect()` used to end it regardless, so disconnecting one\n * client tore down every other consumer of that pool.\n *\n * The test is on the pool's IDENTITY against what construction captured, so\n * it answers for the pool actually being closed rather than for whatever the\n * caller's record says now: every pool this driver made is ended, and the one\n * it was handed never is.\n */\n protected async closeClient(pool: PgPool): Promise<void> {\n if (pool === this.suppliedPool) {\n return;\n }\n const errorState = this.ownedPoolErrors.get(pool);\n try {\n await pool.end();\n } catch (error) {\n const background = this.consumeBackgroundPoolFailure(\n pool,\n errorState?.backgroundFailure\n );\n if (background === undefined) throw error;\n const disconnectFailure = normalizeDriverConnectionError(\n error,\n { driverName: this.driverName },\n \"Database disconnection failed\"\n );\n throw withSuppressedFailure(disconnectFailure, background);\n }\n // AFTER a proven end, not before it: `end()` disposes idle clients whose\n // own listeners can still re-emit on the pool. If end rejects, the still\n // live pool keeps containment; its pre-start evidence travels on the public\n // disconnect failure, exactly once.\n if (errorState !== undefined) {\n pool.off(\"error\", errorState.retain);\n errorState.backgroundFailure = undefined;\n this.ownedPoolErrors.delete(pool);\n }\n }\n\n protected async execute<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"execute\");\n }\n\n protected async executeRaw<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const observed = this.readBackgroundPoolFailure(client);\n const result = await client\n .query({ text: sql, values: params, types: utcSafeTypes })\n .catch((error: unknown) => {\n learnRelationLimit(this.adapter, error);\n return this.throwPoolQueryFailure(\n client,\n observed,\n error,\n sql,\n params,\n context\n );\n });\n // `Pool.query` includes an acquisition. Its success proves transport\n // recovery, but only for evidence that predates this exact operation.\n this.clearBackgroundPoolFailure(client, observed);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n { provider: \"pg\", operation }\n ),\n };\n }\n\n /**\n * PostgreSQL takes the isolation level as the first statement inside the\n * transaction, and node-postgres hands out a pooled client we can wait for\n * with a bound (and release if we stop waiting).\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: PgPool | PgPoolClient,\n fn: (tx: PgPoolClient) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction\n const poolClient = await this.acquirePooledClient(\n client,\n context,\n options?.maxWaitMs\n );\n const clientErrors = holdClientErrors(poolClient);\n // A step's own failure stays primary; a different client failure travels\n // beside it through the shared evidence owner instead of being lost.\n const withClientFailure = (error: unknown): unknown => {\n const failure = clientErrors.failure();\n return failure === undefined || failure === error\n ? error\n : withSuppressedFailure(error, failure);\n };\n let releaseError: Error | boolean | undefined;\n const queryOrDiscard = async (statement: string) => {\n try {\n await poolClient.query(statement);\n } catch (error) {\n releaseError ??= error instanceof Error ? error : true;\n throw withClientFailure(error);\n }\n };\n return runTransactionLifecycle({\n begin: () => queryOrDiscard(\"BEGIN\"),\n callback: async () => {\n try {\n return await fn(poolClient);\n } catch (error) {\n throw withClientFailure(error);\n }\n },\n commit: () => {\n // A callback that settles after its connection failed must not commit:\n // whatever it awaited meanwhile never reached the database.\n const failure = clientErrors.failure();\n if (failure !== undefined) throw failure;\n return queryOrDiscard(\"COMMIT\");\n },\n // The server ends a transaction with its session; a ROLLBACK sent on a\n // client that is no longer queryable would only add a second failure.\n rollback: () =>\n clientErrors.failure() === undefined\n ? queryOrDiscard(\"ROLLBACK\")\n : undefined,\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n const discard = releaseError ?? clientErrors.failure();\n if (discard) {\n poolClient.release(discard);\n return;\n }\n poolClient.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"pg\" could not release an unsafe transaction connection.',\n { meta: { driver: \"pg\", method: \"$transaction\" } }\n )\n );\n throw error;\n } finally {\n clientErrors.stop();\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // The failed PoolClient was discarded with release(error); the pool stays usable.\n }\n\n /**\n * One `PoolClient` from `pool.connect()` — plan §3.5's pinned producer for\n * `pg`. `release(true)` destroys the connection instead of returning it, so a\n * session whose advisory-lock state is unknown never re-enters the pool.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PgPool | PgPoolClient>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const poolClient = await this.acquirePooledClient(client, {\n operation: \"pinnedSession\",\n });\n const clientErrors = holdClientErrors(poolClient);\n return {\n session: poolClient,\n // The client's own `error` event is how pg reports a socket that died\n // between or under statements; the pinned session then sends nothing\n // more on it (plan S2). Release destroys it either way.\n lost: clientErrors.failure,\n release: (discard) => {\n try {\n poolClient.release(\n clientErrors.failure() ?? (discard ? true : undefined)\n );\n } finally {\n clientErrors.stop();\n }\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PgClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PgDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: PgDriver }>]: LinkedClientConfig<\n C & { driver: PgDriver }\n >[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pg\", PG_CONFIG_KEYS);\n const { pool, options = {}, pgvector, postgis, databaseUrl } = config;\n const driver = new PgDriver({\n // Namespace, then attestation: the order a refusal reports in.\n namespace: resolveNamespaceOption(config),\n migrationSessionAttestation:\n resolveMigrationSessionAttestationOption(config),\n // Only a supplied pool counts: a falsy one leaves the driver to build its own.\n pool: pool || undefined,\n options,\n // Present even when undefined: the driver refuses an empty one (parity-18).\n ...(Object.hasOwn(config, \"databaseUrl\") ? { databaseUrl } : {}),\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n });\n\n return createClientFromDriverConfig<S, C, PgDriver>(config, driver);\n}\n"],"mappings":"8nBAoEA,MAEM,eAAkB,GAAkB,EACpC,EAAoC,CACxC,eAAgB,EAAa,IAEzB,CAAC,KAAU,KAAe,KAAM,KAAM,KAAM,KA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"}
|
package/dist/pglite.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-
|
|
1
|
+
import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-B4IWFJfv.mjs";
|
|
2
2
|
import { PGlite, PGliteOptions, PGliteOptions as PGliteOptions$1, Transaction } from "@electric-sql/pglite";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/pglite/index.d.ts
|
|
@@ -11,6 +11,8 @@ interface PGliteDriverOptions {
|
|
|
11
11
|
postgis?: boolean;
|
|
12
12
|
/** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */
|
|
13
13
|
sharedRelationBodies?: boolean;
|
|
14
|
+
/** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. Set 256 for PlanetScale Neki, which refuses more. Absent: unbounded. Only where relation bodies are shared. */
|
|
15
|
+
relationsPerStatement?: number;
|
|
14
16
|
/** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */
|
|
15
17
|
namespace?: string;
|
|
16
18
|
}
|
package/dist/pglite.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./normalized-result-BF7gr4_b.mjs";import{d as n,l as r}from"./error-mapping-6op318w6.mjs";import{s as i}from"./execution-context-rJXTRVrJ.mjs";import{n as a}from"./client-Bhl2mWam.mjs";import{a as o,n as s}from"./pinned-session-FYOFV_gB.mjs";import{c,d as l,r as u,t as d}from"./driver-CQQbCQh9.mjs";import{t as f}from"./postgres-adapter-BAqRfWl1.mjs";import{PGlite as p}from"@electric-sql/pglite";const m=Object.fromEntries([1082,1114,1184,1115,1182,1185].map(e=>[e,e=>e])),h={client:!0,dataDir:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,namespace:!0};function isPGliteDatabase(e){return`transaction`in e}var PGliteDriver=class extends d{maxBindParametersPerStatement=32767;serializeTransactions=!0;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`pglite`);let t=l(e);this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient&&(this.client=this.suppliedClient,Object.defineProperty(this,`connectionQueue`,{value:u(this.suppliedClient)})),f(this,t,e)}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let e=this.driverOptions.dataDir,t=this.driverOptions.options??{},n={...t,parsers:{1114:e=>e,...t.parsers}};return e?await p.create(e,n):await p.create(n)}async closeClient(e){e!==this.suppliedClient&&await e.close()}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,n,r,i,a){let o=i?.operation??a,s=await e.query(n,r,{parsers:m}),c=t(s.affectedRows,{provider:`pglite`,operation:o});return{rows:s.rows,rowCount:s.rows.length>0?s.rows.length:c}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`queue`}}transaction(e,t,a){if(!isPGliteDatabase(e))throw r(this.driverName);return n({run:t=>e.transaction(t),callback:t,phases:i(a),close:async()=>void 0})}async physicalPinnedSession(){return await this.getClient({operation:`pinnedSession`})}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!isPGliteDatabase(e))throw r(this.driverName);return{session:e,release:async t=>{if(t)try{await e.query(`SELECT pg_advisory_unlock_all()`)}catch(t){throw s(e),o(this.driverName,`No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.`,t)}}}}};function createClient(e){c(e,`pglite`,h);let{client:t,dataDir:n,options:r,pgvector:i,postgis:o}=e,s=l(e);return a(e,new PGliteDriver({client:t,dataDir:n,options:r,pgvector:i,postgis:o,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:s}))}export{PGliteDriver,createClient};
|
|
2
2
|
//# sourceMappingURL=pglite.mjs.map
|
package/dist/pglite.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pglite.mjs","names":[],"sources":["../src/drivers/pglite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\n/**\n * PGlite Driver\n *\n * Driver implementation for PGlite (PostgreSQL in WebAssembly).\n * Supports optional pgvector and PostGIS extensions.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n PGlite,\n type PGliteOptions,\n type Transaction,\n} from \"@electric-sql/pglite\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport { normalizeProviderRowCount } from \"../normalized-result\";\nimport {\n nestedTransactionDispatchError,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport {\n condemnPhysicalSession,\n type PinnedSessionReservation,\n unprovenLockStateError,\n} from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type { QueryResult } from \"../types\";\n\nconst temporalParsers = Object.fromEntries(\n [1082, 1114, 1184, 1115, 1182, 1185].map((oid) => [\n oid,\n (value: string) => value,\n ])\n);\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PGliteOptions } from \"@electric-sql/pglite\";\n\nexport interface PGliteDriverOptions {\n client?: PGlite;\n dataDir?: string;\n options?: PGliteOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type PGliteConfig<C extends DriverConfig> = PGliteDriverOptions & C;\n\nconst PGLITE_CONFIG_KEYS: Record<keyof PGliteDriverOptions, true> = {\n client: true,\n dataDir: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n namespace: true,\n};\n\n/**\n * The database, as opposed to a transaction handle, which has no `transaction`\n * method. Not `instanceof PGlite`: a PGlite built by another copy of\n * `@electric-sql/pglite` (its CommonJS build beside the ESM one, or a second\n * installed version) has another class, and every transaction and pinned\n * command on it used to fail as \"nested provider state\".\n */\nfunction isPGliteDatabase(client: PGlite | Transaction): client is PGlite {\n return \"transaction\" in client;\n}\n\n// === ======================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PGliteDriver extends Driver<PGlite, Transaction> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 32_767;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: PGliteDriverOptions;\n /**\n * The EXACT database the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's database while believing it had made its own.\n */\n private readonly suppliedClient: PGlite | undefined;\n\n constructor(options: PGliteDriverOptions = {}) {\n super(\"postgresql\", \"pglite\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n\n installPostgresAdapter(this, namespace, options);\n }\n\n /**\n * The database this driver runs on.\n *\n * A caller's database is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second, EMPTY in-memory PGlite behind their\n * back — a database they never asked for, holding none of their data, while\n * the one they handed over stayed open and unused.\n */\n protected async initClient(): Promise<PGlite> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const dataDir = this.driverOptions.dataDir;\n const userOptions = this.driverOptions.options ?? {};\n const options: PGliteOptions = {\n ...userOptions,\n parsers: {\n // TIMESTAMP WITHOUT TIME ZONE: PGlite builds process-local Dates,\n // shifting the stored UTC wall clock. Keep the raw string — the\n // shared result parser builds a UTC Date, matching other drivers.\n 1114: (value: string) => value,\n ...userOptions.parsers,\n },\n };\n\n // PGlite.create accepts dataDir as first argument or in options\n return dataDir\n ? await PGlite.create(dataDir, options)\n : await PGlite.create(options);\n }\n\n /**\n * A supplied database belongs to the caller, who may be running two\n * schema-scoped estates over it — the documented shape — and closing it here\n * would take the sibling's data down with this one's `$disconnect()`, on an\n * in-memory database for good.\n *\n * The test is on the client's IDENTITY against what construction captured, so\n * it answers for the database actually being closed rather than for whatever\n * the caller's record says now.\n */\n protected async closeClient(client: PGlite): Promise<void> {\n if (client === this.suppliedClient) {\n return;\n }\n await client.close();\n }\n\n protected async execute<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"execute\");\n }\n\n protected async executeRaw<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const result = await client.query<T>(sql, params, {\n parsers: temporalParsers,\n });\n const affectedRows = normalizeProviderRowCount(result.affectedRows, {\n provider: \"pglite\",\n operation,\n });\n return {\n rows: result.rows,\n rowCount: result.rows.length > 0 ? result.rows.length : affectedRows,\n };\n }\n\n /**\n * PGlite is a full PostgreSQL, so the isolation level is a real post-BEGIN\n * statement. It is also single-connection, so top-level transactions queue —\n * and that queue wait is exactly what `maxWait` bounds.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"queue\",\n };\n }\n\n protected transaction<T>(\n client: PGlite | Transaction,\n fn: (tx: Transaction) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n if (!isPGliteDatabase(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return runProviderManagedTransaction({\n run: (callback) => client.transaction(callback),\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n /**\n * The PGlite instance itself — the physical session a pinned command runs on.\n *\n * A caller may hand ONE PGlite to several drivers (two schema-scoped estates\n * over one database is the documented shape), and each of those drivers owns\n * its own connection queue. The client is what they all agree on, so it is\n * what serializes their pinned commands; without it the second command\n * re-acquires the reentrant session advisory lock the first is holding and\n * runs inside the first command's session.\n */\n protected override async physicalPinnedSession(): Promise<object> {\n return await this.getClient({ operation: \"pinnedSession\" });\n }\n\n /**\n * PGlite's single client, under the queue it already owns — plan §3.5's\n * pinned producer here. There is nothing to reserve and nothing to return:\n * one connection IS the session, which is exactly what a session lock needs.\n *\n * A condemned session can be neither destroyed nor abandoned: closing this\n * client closes the DATABASE, which for an in-memory one takes the caller's\n * data with it and for a supplied one is not VibORM's to do at all. So the\n * session is reset with `pg_advisory_unlock_all()`, and when that reset FAILS\n * the CLIENT is condemned instead — the subject of an unknown lock state is\n * the session, so the condemnation is recorded on it and refuses the next\n * pinned command through every driver over it. Ordinary queries keep working\n * — the data was never in doubt. Swallowing that reset failure was the\n * alternative, and it left the next migration command running inside a\n * session that may still hold the lock, on the one transport where the lock\n * is reentrant and would not stop it.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PGlite | Transaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!isPGliteDatabase(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return {\n session: client,\n release: async (discard) => {\n if (!discard) {\n return;\n }\n try {\n await client.query(\"SELECT pg_advisory_unlock_all()\");\n } catch (resetFailure) {\n condemnPhysicalSession(client);\n throw unprovenLockStateError(\n this.driverName,\n \"No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.\",\n resetFailure\n );\n }\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PGliteConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PGliteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PGliteDriver }\n >]: LinkedClientConfig<C & { driver: PGliteDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pglite\", PGLITE_CONFIG_KEYS);\n const { client, dataDir, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new PGliteDriver({\n client,\n dataDir,\n options,\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, PGliteDriver>(config, driver);\n}\n"],"mappings":"gdAwCA,MAAM,EAAkB,OAAO,YAC7B,CAAC,KAAM,KAAM,KAAM,KAAM,KAAM,KAAK,CAAC,IAAK,GAAQ,CAChD,EACC,GAAkB,EACpB,CAAC,CACH,CAsBK,EAA8D,CAClE,OAAQ,GACR,QAAS,GACT,QAAS,GACT,SAAU,GACV,QAAS,GACT,qBAAsB,G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U,EAAO,KAAK,OAAS,EAAI,EAAO,KAAK,OAAS,EACzD,CAQH,0BAAwE,CACtE,MAAO,CACL,eAAgB,aAChB,QAAS,GACT,QAAS,QACV,CAGH,YACE,EACA,EACA,EACY,CACZ,GAAI,CAAC,iBAAiB,EAAO,CAC3B,MAAM,EAA+B,KAAK,WAAW,CAEvD,OAAO,EAA8B,CACnC,IAAM,GAAa,EAAO,YAAY,EAAS,CAC/C,SAAU,EACV,OAAQ,EAA8B,EAAQ,CAG9C,MAAO,SAAY,IAAA,GACpB,CAAC,CAaJ,MAAyB,uBAAyC,CAChE,OAAO,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CAoB7D,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,CAAC,iBAAiB,EAAO,CAC3B,MAAM,EAA+B,KAAK,WAAW,CAEvD,MAAO,CACL,QAAS,EACT,QAAS,KAAO,IAAY,CACrB,KAGL,GAAI,CACF,MAAM,EAAO,MAAM,kCAAkC,OAC9C,EAAc,CAErB,MADA,EAAuB,EAAO,CACxB,EACJ,KAAK,WACL,4KACA,EACD,GAGN,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,SAAU,EAAmB,CACnE,GAAM,CAAE,SAAQ,UAAS,UAAS,WAAU,WAAY,EAClD,EAAY,EAAuB,EAAO,CAYhD,OAAO,EAAiD,EAVzC,IAAI,aAAa,CAC9B,SACA,UACA,UACA,WACA,UACA,qBAAsB,EAAO,qBAC7B,YACD,CAAC,CAEqE"}
|
|
1
|
+
{"version":3,"file":"pglite.mjs","names":[],"sources":["../src/drivers/pglite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\n/**\n * PGlite Driver\n *\n * Driver implementation for PGlite (PostgreSQL in WebAssembly).\n * Supports optional pgvector and PostGIS extensions.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n PGlite,\n type PGliteOptions,\n type Transaction,\n} from \"@electric-sql/pglite\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport { normalizeProviderRowCount } from \"../normalized-result\";\nimport {\n nestedTransactionDispatchError,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport {\n condemnPhysicalSession,\n type PinnedSessionReservation,\n unprovenLockStateError,\n} from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type { QueryResult } from \"../types\";\n\nconst temporalParsers = Object.fromEntries(\n [1082, 1114, 1184, 1115, 1182, 1185].map((oid) => [\n oid,\n (value: string) => value,\n ])\n);\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PGliteOptions } from \"@electric-sql/pglite\";\n\nexport interface PGliteDriverOptions {\n client?: PGlite;\n dataDir?: string;\n options?: PGliteOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. Set 256 for PlanetScale Neki, which refuses more. Absent: unbounded. Only where relation bodies are shared. */\n relationsPerStatement?: number;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type PGliteConfig<C extends DriverConfig> = PGliteDriverOptions & C;\n\nconst PGLITE_CONFIG_KEYS: Record<keyof PGliteDriverOptions, true> = {\n client: true,\n dataDir: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n namespace: true,\n};\n\n/**\n * The database, as opposed to a transaction handle, which has no `transaction`\n * method. Not `instanceof PGlite`: a PGlite built by another copy of\n * `@electric-sql/pglite` (its CommonJS build beside the ESM one, or a second\n * installed version) has another class, and every transaction and pinned\n * command on it used to fail as \"nested provider state\".\n */\nfunction isPGliteDatabase(client: PGlite | Transaction): client is PGlite {\n return \"transaction\" in client;\n}\n\n// === ======================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PGliteDriver extends Driver<PGlite, Transaction> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 32_767;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: PGliteDriverOptions;\n /**\n * The EXACT database the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's database while believing it had made its own.\n */\n private readonly suppliedClient: PGlite | undefined;\n\n constructor(options: PGliteDriverOptions = {}) {\n super(\"postgresql\", \"pglite\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n\n installPostgresAdapter(this, namespace, options);\n }\n\n /**\n * The database this driver runs on.\n *\n * A caller's database is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second, EMPTY in-memory PGlite behind their\n * back — a database they never asked for, holding none of their data, while\n * the one they handed over stayed open and unused.\n */\n protected async initClient(): Promise<PGlite> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const dataDir = this.driverOptions.dataDir;\n const userOptions = this.driverOptions.options ?? {};\n const options: PGliteOptions = {\n ...userOptions,\n parsers: {\n // TIMESTAMP WITHOUT TIME ZONE: PGlite builds process-local Dates,\n // shifting the stored UTC wall clock. Keep the raw string — the\n // shared result parser builds a UTC Date, matching other drivers.\n 1114: (value: string) => value,\n ...userOptions.parsers,\n },\n };\n\n // PGlite.create accepts dataDir as first argument or in options\n return dataDir\n ? await PGlite.create(dataDir, options)\n : await PGlite.create(options);\n }\n\n /**\n * A supplied database belongs to the caller, who may be running two\n * schema-scoped estates over it — the documented shape — and closing it here\n * would take the sibling's data down with this one's `$disconnect()`, on an\n * in-memory database for good.\n *\n * The test is on the client's IDENTITY against what construction captured, so\n * it answers for the database actually being closed rather than for whatever\n * the caller's record says now.\n */\n protected async closeClient(client: PGlite): Promise<void> {\n if (client === this.suppliedClient) {\n return;\n }\n await client.close();\n }\n\n protected async execute<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"execute\");\n }\n\n protected async executeRaw<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const result = await client.query<T>(sql, params, {\n parsers: temporalParsers,\n });\n const affectedRows = normalizeProviderRowCount(result.affectedRows, {\n provider: \"pglite\",\n operation,\n });\n return {\n rows: result.rows,\n rowCount: result.rows.length > 0 ? result.rows.length : affectedRows,\n };\n }\n\n /**\n * PGlite is a full PostgreSQL, so the isolation level is a real post-BEGIN\n * statement. It is also single-connection, so top-level transactions queue —\n * and that queue wait is exactly what `maxWait` bounds.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"queue\",\n };\n }\n\n protected transaction<T>(\n client: PGlite | Transaction,\n fn: (tx: Transaction) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n if (!isPGliteDatabase(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return runProviderManagedTransaction({\n run: (callback) => client.transaction(callback),\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n /**\n * The PGlite instance itself — the physical session a pinned command runs on.\n *\n * A caller may hand ONE PGlite to several drivers (two schema-scoped estates\n * over one database is the documented shape), and each of those drivers owns\n * its own connection queue. The client is what they all agree on, so it is\n * what serializes their pinned commands; without it the second command\n * re-acquires the reentrant session advisory lock the first is holding and\n * runs inside the first command's session.\n */\n protected override async physicalPinnedSession(): Promise<object> {\n return await this.getClient({ operation: \"pinnedSession\" });\n }\n\n /**\n * PGlite's single client, under the queue it already owns — plan §3.5's\n * pinned producer here. There is nothing to reserve and nothing to return:\n * one connection IS the session, which is exactly what a session lock needs.\n *\n * A condemned session can be neither destroyed nor abandoned: closing this\n * client closes the DATABASE, which for an in-memory one takes the caller's\n * data with it and for a supplied one is not VibORM's to do at all. So the\n * session is reset with `pg_advisory_unlock_all()`, and when that reset FAILS\n * the CLIENT is condemned instead — the subject of an unknown lock state is\n * the session, so the condemnation is recorded on it and refuses the next\n * pinned command through every driver over it. Ordinary queries keep working\n * — the data was never in doubt. Swallowing that reset failure was the\n * alternative, and it left the next migration command running inside a\n * session that may still hold the lock, on the one transport where the lock\n * is reentrant and would not stop it.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PGlite | Transaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!isPGliteDatabase(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return {\n session: client,\n release: async (discard) => {\n if (!discard) {\n return;\n }\n try {\n await client.query(\"SELECT pg_advisory_unlock_all()\");\n } catch (resetFailure) {\n condemnPhysicalSession(client);\n throw unprovenLockStateError(\n this.driverName,\n \"No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.\",\n resetFailure\n );\n }\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PGliteConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PGliteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PGliteDriver }\n >]: LinkedClientConfig<C & { driver: PGliteDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pglite\", PGLITE_CONFIG_KEYS);\n const { client, dataDir, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new PGliteDriver({\n client,\n dataDir,\n options,\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, PGliteDriver>(config, driver);\n}\n"],"mappings":"0cAwCA,MAAM,EAAkB,OAAO,YAC7B,CAAC,KAAM,KAAM,KAAM,KAAM,KAAM,KAAK,CAAC,IAAK,GAAQ,CAChD,EACC,GAAkB,EACpB,CAAC,CACH,CAwBK,EAA8D,CAClE,OAAQ,GACR,QAAS,GACT,QAAS,GACT,SAAU,GACV,QAAS,GACT,qBAAsB,GACtB,sBAAuB,GACvB,UAAW,GACZ,CASD,SAAS,iBAAiB,EAAgD,CACxE,MAAO,gBAAiB,EAO1B,IAAa,aAAb,cAAkC,CAA4B,CAE5D,8BAA6D,MAC7D,sBAAoD,GAEpD,cAQA,eAEA,YAAY,EAA+B,EAAE,CAAE,CAC7C,MAAM,aAAc,SAAS,CAC7B,IAAM,EAAY,EAAuB,EAAQ,CACjD,KAAK,cAAgB,EACrB,KAAK,eAAiB,EAAQ,OAE1B,KAAK,iBACP,KAAK,OAAS,KAAK,eACnB,OAAO,eAAe,KAAM,kBAAmB,CAC7C,MAAO,EAAwB,KAAK,eAAe,C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KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CAoB7D,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,CAAC,iBAAiB,EAAO,CAC3B,MAAM,EAA+B,KAAK,WAAW,CAEvD,MAAO,CACL,QAAS,EACT,QAAS,KAAO,IAAY,CACrB,KAGL,GAAI,CACF,MAAM,EAAO,MAAM,kCAAkC,OAC9C,EAAc,CAErB,MADA,EAAuB,EAAO,CACxB,EACJ,KAAK,WACL,4KACA,EACD,GAGN,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,SAAU,EAAmB,CACnE,GAAM,CAAE,SAAQ,UAAS,UAAS,WAAU,WAAY,EAClD,EAAY,EAAuB,EAAO,CAahD,OAAO,EAAiD,EAXzC,IAAI,aAAa,CAC9B,SACA,UACA,UACA,WACA,UACA,qBAAsB,EAAO,qBAC7B,sBAAuB,EAAO,sBAC9B,YACD,CAAC,CAEqE"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{lt as t,st as n}from"./geo-point-codec-
|
|
2
|
-
//# sourceMappingURL=physical-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{lt as t,st as n}from"./geo-point-codec-D95uXgDF.mjs";import{i as r,o as i,r as a,t as o}from"./native-types-asNCr26n.mjs";const s=new WeakMap;function idDomainOfState(e){return e?.array===!0?void 0:idMemberDomainOfState(e)}function idMemberDomainOfState(e){if(e===void 0||e.type!==`string`)return;let n=s.get(e);if(n)return n;let r=e.autoGenerate;if(r===void 0||!t(r.kind)||r.implicit===!0)return;let i={format:r.kind,prefix:r.prefix,length:r.length};return s.set(e,i),i}const c=/^(?:text|citext|varchar\(\d+\))$/,l=/^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\(\d+\)|CHAR\(\d+\))$/,u=/^TEXT$/,d=/^(?:BINARY|VARBINARY)\((\d+)\)$/;function defaultIdStorage(e,t){let i=n(e);if(i===void 0)switch(t){case`pg`:return{representation:`text`,columnType:a.STRING.TEXT.type};case`mysql`:return{representation:`text`,columnType:`TEXT`};default:return{representation:`text`,columnType:r.STRING.TEXT.type}}switch(t){case`pg`:return e===`uuid`||e===`uuidv7`?{representation:`uuid`,columnType:a.STRING.UUID.type}:{representation:`bytes`,columnType:a.BLOB.BYTEA.type};case`mysql`:return{representation:`bytes`,columnType:o.BLOB.BINARY(i).type};default:return{representation:`bytes`,columnType:r.BLOB.BLOB.type}}}function isTextColumnType(e,t){switch(t){case`pg`:return c.test(e);case`mysql`:return l.test(e);default:return u.test(e)}}function binaryRepresentation(e,t,i){let s=n(t);if(s===void 0)return;if(i===`pg`)return e===a.BLOB.BYTEA.type?`bytes`:e===a.STRING.UUID.type&&(t===`uuid`||t===`uuidv7`)?`uuid`:void 0;if(i===`sqlite`)return e===r.BLOB.BLOB.type?`bytes`:void 0;if(e===o.BLOB.BLOB.type)return`bytes`;let c=d.exec(e);return c&&Number(c[1])===s?`bytes`:void 0}function idStorageOf(e,t,n){let r=i(t,n);if(r===void 0)return defaultIdStorage(e.format,n);let a=r.type;if(isTextColumnType(a,n))return{representation:`text`,columnType:a};let o=binaryRepresentation(a,e.format,n);return o===void 0?void 0:{representation:o,columnType:a}}function describeIdNativeTypes(e,t){let r=n(e),i=t===`pg`?`text, citext, varchar(n)`:t===`mysql`?`TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)`:`TEXT`;return r===void 0?i:`${t===`pg`?e===`uuid`||e===`uuidv7`?`uuid, bytea`:`bytea`:t===`mysql`?`BINARY(${r}), VARBINARY(${r}), BLOB`:`BLOB`}, ${i}`}function sqliteDateTimePhysicalForm(e){let t=i(e,`sqlite`);return t===void 0?`text`:t.type===`INTEGER`?`epochMillis`:t.type===`REAL`?`julianDay`:`text`}export{idStorageOf as a,idMemberDomainOfState as i,describeIdNativeTypes as n,idDomainOfState as r,sqliteDateTimePhysicalForm as t};
|
|
2
|
+
//# sourceMappingURL=physical-uJfmo4-Z.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"physical-CAOaNM4R.mjs","names":[],"sources":["../src/schema/scalars/string/id-domain.ts","../src/schema/scalars/datetime/physical.ts"],"sourcesContent":["/**\n * Where a DECLARED identifier domain is read from, and how it becomes a column.\n *\n * There is no second declaration: `ScalarState.autoGenerate` — the same record\n * `.uuid()`, `.ulid()`, `.ksuid()`, `.nanoid()` and `.cuid()` already write —\n * IS the domain. This module only projects it into the shape the codec takes,\n * and answers the one storage question the projection cannot: which physical\n * representation and which column spelling this domain has on a given dialect,\n * with a native type override taken into account.\n *\n * Storage lives HERE rather than in the codec because it is the only part of\n * the identifier language that speaks a dialect's vocabulary. The codec below\n * it stays pure — it takes a representation, never a provider — so the\n * validation schemas, which run long before any adapter exists, can use it.\n */\n\nimport {\n type IdDomain,\n type IdFormat,\n type IdRepresentation,\n idByteLength,\n isIdFormat,\n} from \"@validation/primitives/id-codec\";\nimport type { AutoGenerate, ScalarState } from \"../common\";\nimport {\n MYSQL,\n type NativeDialect,\n type NativeTypeDeclaration,\n nativeTypeFor,\n PG,\n SQLITE,\n} from \"../native-types\";\n\n// =============================================================================\n// THE DECLARED DOMAIN\n// =============================================================================\n\nconst DOMAINS = new WeakMap<ScalarState, IdDomain>();\n\n/**\n * The identifier domain a scalar state declares, or `undefined`.\n *\n * Only a NAMED format declares one. `.id()` installs a ULID generator without\n * naming a format (see {@link AutoGenerate.implicit}), so a `.id()` key has no\n * domain: nothing admits its values and nothing narrows its storage.\n *\n * A LIST answers `undefined` deliberately, exactly as the decimal descriptor\n * lookup does: physical parameter encoding, projection, decode and DDL must\n * not bind a whole container as one compact identifier. List admission reads\n * the same declaration through idMemberDomainOfState instead.\n *\n * The projection is memoized per state so the hot write path compares and\n * encodes against one object instead of allocating a domain per value.\n */\nexport function idDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n return state?.array === true ? undefined : idMemberDomainOfState(state);\n}\n\n/** The named member domain, also used by lists with plain string storage. */\nexport function idMemberDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n if (state === undefined || state.type !== \"string\") return undefined;\n const existing = DOMAINS.get(state);\n if (existing) return existing;\n const generate = state.autoGenerate;\n if (generate === undefined || !isIdFormat(generate.kind)) return undefined;\n // A format the caller did not NAME is not a domain the caller asserted:\n // `.id()` declares a key and carries a generator for convenience, and its\n // values stay whatever a string column holds. `.ulid().id()` names the\n // format and gets the domain, the admission and the compact column.\n if (generate.implicit === true) return undefined;\n const domain: IdDomain = {\n format: generate.kind,\n prefix: generate.prefix,\n length: generate.length,\n };\n DOMAINS.set(state, domain);\n return domain;\n}\n\n// =============================================================================\n// PHYSICAL STORAGE\n// =============================================================================\n\n/** The three dialects a column spelling is asked for. */\nexport type IdDialect = NativeDialect;\n\n/** What one domain is physically, on one dialect. */\nexport interface IdStorage {\n readonly representation: IdRepresentation;\n /** The column type this dialect spells it with. */\n readonly columnType: string;\n}\n\n// `char(n)` is absent deliberately. PostgreSQL BLANK-PADS `character(n)` to its\n// full width, so a 36-character uuid in a `char(40)` column reads back with four\n// trailing spaces and no value of the domain is ever returned — the column is\n// unusable from the moment it is created, for every n wider than the format's\n// own public spelling. MySQL's `CHAR(n)` pads on the way in and STRIPS on the\n// way out, so it keeps its place in that dialect's list.\nconst PG_TEXT_FAMILY = /^(?:text|citext|varchar\\(\\d+\\))$/;\nconst MYSQL_TEXT_FAMILY =\n /^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\\(\\d+\\)|CHAR\\(\\d+\\))$/;\nconst SQLITE_TEXT_FAMILY = /^TEXT$/;\nconst MYSQL_SIZED_BINARY = /^(?:BINARY|VARBINARY)\\((\\d+)\\)$/;\n\n/** The default column spelling and representation, before any override. */\nfunction defaultIdStorage(format: IdFormat, dialect: IdDialect): IdStorage {\n const width = idByteLength(format);\n if (width === undefined) {\n // `nanoid` and `cuid` keep the text column the dialect already gave them.\n switch (dialect) {\n case \"pg\":\n return { representation: \"text\", columnType: PG.STRING.TEXT.type };\n case \"mysql\":\n return { representation: \"text\", columnType: \"TEXT\" };\n default:\n return {\n representation: \"text\",\n columnType: SQLITE.STRING.TEXT.type,\n };\n }\n }\n switch (dialect) {\n case \"pg\":\n // A UUID gets PostgreSQL's own 16-byte type, which the wire spells as\n // canonical text. A ULID is never spelled `uuid`: its bytes are not a\n // UUID's and a database that formatted them as one would publish a\n // version nibble the value does not have.\n return format === \"uuid\" || format === \"uuidv7\"\n ? { representation: \"uuid\", columnType: PG.STRING.UUID.type }\n : { representation: \"bytes\", columnType: PG.BLOB.BYTEA.type };\n case \"mysql\":\n return {\n representation: \"bytes\",\n columnType: MYSQL.BLOB.BINARY(width).type,\n };\n default:\n return { representation: \"bytes\", columnType: SQLITE.BLOB.BLOB.type };\n }\n}\n\n/** Whether this dialect spells `type` as one of its text column types. */\nfunction isTextColumnType(type: string, dialect: IdDialect): boolean {\n switch (dialect) {\n case \"pg\":\n return PG_TEXT_FAMILY.test(type);\n case \"mysql\":\n return MYSQL_TEXT_FAMILY.test(type);\n default:\n return SQLITE_TEXT_FAMILY.test(type);\n }\n}\n\n/**\n * The representation a BINARY-family override names for this format, or\n * `undefined` when the override is not a binary column this domain fits.\n *\n * A sized MySQL column must be the format's exact width: `BINARY(16)` holds a\n * KSUID's first sixteen bytes and pads a ULID that was never short, and both\n * are silent corruptions rather than storage choices. `bytea` and `BLOB` carry\n * no declared width, so the codec's exact-width encoding is the only promise\n * they need.\n */\nfunction binaryRepresentation(\n type: string,\n format: IdFormat,\n dialect: IdDialect\n): IdRepresentation | undefined {\n const width = idByteLength(format);\n if (width === undefined) return undefined;\n if (dialect === \"pg\") {\n if (type === PG.BLOB.BYTEA.type) return \"bytes\";\n return type === PG.STRING.UUID.type &&\n (format === \"uuid\" || format === \"uuidv7\")\n ? \"uuid\"\n : undefined;\n }\n if (dialect === \"sqlite\") {\n return type === SQLITE.BLOB.BLOB.type ? \"bytes\" : undefined;\n }\n if (type === MYSQL.BLOB.BLOB.type) return \"bytes\";\n const sized = MYSQL_SIZED_BINARY.exec(type);\n return sized && Number(sized[1]) === width ? \"bytes\" : undefined;\n}\n\n/**\n * The column spelling and representation of one domain on one dialect.\n *\n * The ONE owner of that decision: the migration type mapping, the parameter\n * encoding, the read projection and the result decode all derive from this, so\n * a column cannot be created as one thing and written as another.\n *\n * The declaration is resolved for THIS dialect (`nativeTypeFor`): a tagged\n * native type for another dialect, or a map without this dialect's entry, is\n * not this dialect's column and is ignored exactly as every other scalar's\n * mapping ignores it. An override that IS this\n * dialect's and that this domain cannot live in returns `undefined` — the\n * schema boundary refuses it by name long before a query is built, and this\n * answering `undefined` rather than guessing is what keeps that refusal the\n * only place the question is decided.\n */\nexport function idStorageOf(\n domain: IdDomain,\n declaration: NativeTypeDeclaration | undefined,\n dialect: IdDialect\n): IdStorage | undefined {\n const nativeType = nativeTypeFor(declaration, dialect);\n if (nativeType === undefined) {\n return defaultIdStorage(domain.format, dialect);\n }\n const type = nativeType.type;\n if (isTextColumnType(type, dialect)) {\n // The opt-out for a column that already holds text: the domain is still\n // admitted and normalized, only its storage stays as it was.\n return { representation: \"text\", columnType: type };\n }\n const representation = binaryRepresentation(type, domain.format, dialect);\n return representation === undefined\n ? undefined\n : { representation, columnType: type };\n}\n\n/** The overrides this domain accepts on this dialect, for a refusal message. */\nexport function describeIdNativeTypes(\n format: IdFormat,\n dialect: IdDialect\n): string {\n const width = idByteLength(format);\n const text =\n dialect === \"pg\"\n ? \"text, citext, varchar(n)\"\n : dialect === \"mysql\"\n ? \"TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)\"\n : \"TEXT\";\n if (width === undefined) return text;\n const binary =\n dialect === \"pg\"\n ? format === \"uuid\" || format === \"uuidv7\"\n ? \"uuid, bytea\"\n : \"bytea\"\n : dialect === \"mysql\"\n ? `BINARY(${width}), VARBINARY(${width}), BLOB`\n : \"BLOB\";\n return `${binary}, ${text}`;\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport { type NativeTypeDeclaration, nativeTypeFor } from \"../native-types\";\n\n/**\n * The physical vocabulary SQLite assigns to one DateTime native declaration.\n *\n * A missing declaration, a declaration that selects nothing on SQLite, and\n * explicit TEXT all use SQLite's default timestamp text. INTEGER is epoch milliseconds and\n * REAL is a Julian day. Schema validation, query lowering, result parsing, and\n * migration defaults consume this same interpretation.\n */\nexport function sqliteDateTimePhysicalForm(\n declaration: NativeTypeDeclaration | undefined\n): DateTimePhysicalForm {\n const nativeType = nativeTypeFor(declaration, \"sqlite\");\n if (nativeType === undefined) return \"text\";\n if (nativeType.type === \"INTEGER\") return \"epochMillis\";\n return nativeType.type === \"REAL\" ? \"julianDay\" : \"text\";\n}\n"],"mappings":"0KAqCA,MAAM,EAAU,IAAI,QAiBpB,SAAgB,gBACd,EACsB,CACtB,OAAO,GAAO,QAAU,GAAO,IAAA,GAAY,sBAAsB,EAAM,CAIzE,SAAgB,sBACd,EACsB,CACtB,GAAI,IAAU,IAAA,IAAa,EAAM,OAAS,SAAU,OACpD,IAAM,EAAW,EAAQ,IAAI,EAAM,CACnC,GAAI,EAAU,OAAO,EACrB,IAAM,EAAW,EAAM,aAMvB,GALI,IAAa,IAAA,IAAa,CAAC,EAAW,EAAS,KAAK,EAKpD,EAAS,WAAa,GAAM,OAChC,IAAM,EAAmB,CACvB,OAAQ,EAAS,KACjB,OAAQ,EAAS,OACjB,OAAQ,EAAS,OAClB,CAED,OADA,EAAQ,IAAI,EAAO,EAAO,CACnB,EAuBT,MAAM,EAAiB,mCACjB,EACJ,qEACI,EAAqB,SACrB,EAAqB,kCAG3B,SAAS,iBAAiB,EAAkB,EAA+B,CACzE,IAAM,EAAQ,EAAa,EAAO,CAClC,GAAI,IAAU,IAAA,GAEZ,OAAQ,EAAR,CACE,IAAK,KACH,MAAO,CAAE,eAAgB,O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Q,EAAQ,CAEjD,IAAM,EAAO,EAAW,KACxB,GAAI,iBAAiB,EAAM,EAAQ,CAGjC,MAAO,CAAE,eAAgB,OAAQ,WAAY,EAAM,CAErD,IAAM,EAAiB,qBAAqB,EAAM,EAAO,OAAQ,EAAQ,CACzE,OAAO,IAAmB,IAAA,GACtB,IAAA,GACA,CAAE,iBAAgB,WAAY,EAAM,CAI1C,SAAgB,sBACd,EACA,EACQ,CACR,IAAM,EAAQ,EAAa,EAAO,CAC5B,EACJ,IAAY,KACR,2BACA,IAAY,QACV,4DACA,OAUR,OATI,IAAU,IAAA,GAAkB,EASzB,GAPL,IAAY,KACR,IAAW,QAAU,IAAW,SAC9B,cACA,QACF,IAAY,QACV,UAAU,EAAM,eAAe,EAAM,SACrC,OACS,IAAI,IC5OvB,SAAgB,2BACd,EACsB,CACtB,IAAM,EAAa,EAAc,EAAa,SAAS,CAGvD,OAFI,IAAe,IAAA,GAAkB,OACjC,EAAW,OAAS,UAAkB,cACnC,EAAW,OAAS,OAAS,YAAc"}
|
|
1
|
+
{"version":3,"file":"physical-uJfmo4-Z.mjs","names":[],"sources":["../src/schema/scalars/string/id-domain.ts","../src/schema/scalars/datetime/physical.ts"],"sourcesContent":["/**\n * Where a DECLARED identifier domain is read from, and how it becomes a column.\n *\n * There is no second declaration: `ScalarState.autoGenerate` — the same record\n * `.uuid()`, `.ulid()`, `.ksuid()`, `.nanoid()` and `.cuid()` already write —\n * IS the domain. This module only projects it into the shape the codec takes,\n * and answers the one storage question the projection cannot: which physical\n * representation and which column spelling this domain has on a given dialect,\n * with a native type override taken into account.\n *\n * Storage lives HERE rather than in the codec because it is the only part of\n * the identifier language that speaks a dialect's vocabulary. The codec below\n * it stays pure — it takes a representation, never a provider — so the\n * validation schemas, which run long before any adapter exists, can use it.\n */\n\nimport {\n type IdDomain,\n type IdFormat,\n type IdRepresentation,\n idByteLength,\n isIdFormat,\n} from \"@validation/primitives/id-codec\";\nimport type { AutoGenerate, ScalarState } from \"../common\";\nimport {\n MYSQL,\n type NativeDialect,\n type NativeTypeDeclaration,\n nativeTypeFor,\n PG,\n SQLITE,\n} from \"../native-types\";\n\n// =============================================================================\n// THE DECLARED DOMAIN\n// =============================================================================\n\nconst DOMAINS = new WeakMap<ScalarState, IdDomain>();\n\n/**\n * The identifier domain a scalar state declares, or `undefined`.\n *\n * Only a NAMED format declares one. `.id()` installs a ULID generator without\n * naming a format (see {@link AutoGenerate.implicit}), so a `.id()` key has no\n * domain: nothing admits its values and nothing narrows its storage.\n *\n * A LIST answers `undefined` deliberately, exactly as the decimal descriptor\n * lookup does: physical parameter encoding, projection, decode and DDL must\n * not bind a whole container as one compact identifier. List admission reads\n * the same declaration through idMemberDomainOfState instead.\n *\n * The projection is memoized per state so the hot write path compares and\n * encodes against one object instead of allocating a domain per value.\n */\nexport function idDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n return state?.array === true ? undefined : idMemberDomainOfState(state);\n}\n\n/** The named member domain, also used by lists with plain string storage. */\nexport function idMemberDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n if (state === undefined || state.type !== \"string\") return undefined;\n const existing = DOMAINS.get(state);\n if (existing) return existing;\n const generate = state.autoGenerate;\n if (generate === undefined || !isIdFormat(generate.kind)) return undefined;\n // A format the caller did not NAME is not a domain the caller asserted:\n // `.id()` declares a key and carries a generator for convenience, and its\n // values stay whatever a string column holds. `.ulid().id()` names the\n // format and gets the domain, the admission and the compact column.\n if (generate.implicit === true) return undefined;\n const domain: IdDomain = {\n format: generate.kind,\n prefix: generate.prefix,\n length: generate.length,\n };\n DOMAINS.set(state, domain);\n return domain;\n}\n\n// =============================================================================\n// PHYSICAL STORAGE\n// =============================================================================\n\n/** The three dialects a column spelling is asked for. */\nexport type IdDialect = NativeDialect;\n\n/** What one domain is physically, on one dialect. */\nexport interface IdStorage {\n readonly representation: IdRepresentation;\n /** The column type this dialect spells it with. */\n readonly columnType: string;\n}\n\n// `char(n)` is absent deliberately. PostgreSQL BLANK-PADS `character(n)` to its\n// full width, so a 36-character uuid in a `char(40)` column reads back with four\n// trailing spaces and no value of the domain is ever returned — the column is\n// unusable from the moment it is created, for every n wider than the format's\n// own public spelling. MySQL's `CHAR(n)` pads on the way in and STRIPS on the\n// way out, so it keeps its place in that dialect's list.\nconst PG_TEXT_FAMILY = /^(?:text|citext|varchar\\(\\d+\\))$/;\nconst MYSQL_TEXT_FAMILY =\n /^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\\(\\d+\\)|CHAR\\(\\d+\\))$/;\nconst SQLITE_TEXT_FAMILY = /^TEXT$/;\nconst MYSQL_SIZED_BINARY = /^(?:BINARY|VARBINARY)\\((\\d+)\\)$/;\n\n/** The default column spelling and representation, before any override. */\nfunction defaultIdStorage(format: IdFormat, dialect: IdDialect): IdStorage {\n const width = idByteLength(format);\n if (width === undefined) {\n // `nanoid` and `cuid` keep the text column the dialect already gave them.\n switch (dialect) {\n case \"pg\":\n return { representation: \"text\", columnType: PG.STRING.TEXT.type };\n case \"mysql\":\n return { representation: \"text\", columnType: \"TEXT\" };\n default:\n return {\n representation: \"text\",\n columnType: SQLITE.STRING.TEXT.type,\n };\n }\n }\n switch (dialect) {\n case \"pg\":\n // A UUID gets PostgreSQL's own 16-byte type, which the wire spells as\n // canonical text. A ULID is never spelled `uuid`: its bytes are not a\n // UUID's and a database that formatted them as one would publish a\n // version nibble the value does not have.\n return format === \"uuid\" || format === \"uuidv7\"\n ? { representation: \"uuid\", columnType: PG.STRING.UUID.type }\n : { representation: \"bytes\", columnType: PG.BLOB.BYTEA.type };\n case \"mysql\":\n return {\n representation: \"bytes\",\n columnType: MYSQL.BLOB.BINARY(width).type,\n };\n default:\n return { representation: \"bytes\", columnType: SQLITE.BLOB.BLOB.type };\n }\n}\n\n/** Whether this dialect spells `type` as one of its text column types. */\nfunction isTextColumnType(type: string, dialect: IdDialect): boolean {\n switch (dialect) {\n case \"pg\":\n return PG_TEXT_FAMILY.test(type);\n case \"mysql\":\n return MYSQL_TEXT_FAMILY.test(type);\n default:\n return SQLITE_TEXT_FAMILY.test(type);\n }\n}\n\n/**\n * The representation a BINARY-family override names for this format, or\n * `undefined` when the override is not a binary column this domain fits.\n *\n * A sized MySQL column must be the format's exact width: `BINARY(16)` holds a\n * KSUID's first sixteen bytes and pads a ULID that was never short, and both\n * are silent corruptions rather than storage choices. `bytea` and `BLOB` carry\n * no declared width, so the codec's exact-width encoding is the only promise\n * they need.\n */\nfunction binaryRepresentation(\n type: string,\n format: IdFormat,\n dialect: IdDialect\n): IdRepresentation | undefined {\n const width = idByteLength(format);\n if (width === undefined) return undefined;\n if (dialect === \"pg\") {\n if (type === PG.BLOB.BYTEA.type) return \"bytes\";\n return type === PG.STRING.UUID.type &&\n (format === \"uuid\" || format === \"uuidv7\")\n ? \"uuid\"\n : undefined;\n }\n if (dialect === \"sqlite\") {\n return type === SQLITE.BLOB.BLOB.type ? \"bytes\" : undefined;\n }\n if (type === MYSQL.BLOB.BLOB.type) return \"bytes\";\n const sized = MYSQL_SIZED_BINARY.exec(type);\n return sized && Number(sized[1]) === width ? \"bytes\" : undefined;\n}\n\n/**\n * The column spelling and representation of one domain on one dialect.\n *\n * The ONE owner of that decision: the migration type mapping, the parameter\n * encoding, the read projection and the result decode all derive from this, so\n * a column cannot be created as one thing and written as another.\n *\n * The declaration is resolved for THIS dialect (`nativeTypeFor`): a tagged\n * native type for another dialect, or a map without this dialect's entry, is\n * not this dialect's column and is ignored exactly as every other scalar's\n * mapping ignores it. An override that IS this\n * dialect's and that this domain cannot live in returns `undefined` — the\n * schema boundary refuses it by name long before a query is built, and this\n * answering `undefined` rather than guessing is what keeps that refusal the\n * only place the question is decided.\n */\nexport function idStorageOf(\n domain: IdDomain,\n declaration: NativeTypeDeclaration | undefined,\n dialect: IdDialect\n): IdStorage | undefined {\n const nativeType = nativeTypeFor(declaration, dialect);\n if (nativeType === undefined) {\n return defaultIdStorage(domain.format, dialect);\n }\n const type = nativeType.type;\n if (isTextColumnType(type, dialect)) {\n // The opt-out for a column that already holds text: the domain is still\n // admitted and normalized, only its storage stays as it was.\n return { representation: \"text\", columnType: type };\n }\n const representation = binaryRepresentation(type, domain.format, dialect);\n return representation === undefined\n ? undefined\n : { representation, columnType: type };\n}\n\n/** The overrides this domain accepts on this dialect, for a refusal message. */\nexport function describeIdNativeTypes(\n format: IdFormat,\n dialect: IdDialect\n): string {\n const width = idByteLength(format);\n const text =\n dialect === \"pg\"\n ? \"text, citext, varchar(n)\"\n : dialect === \"mysql\"\n ? \"TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)\"\n : \"TEXT\";\n if (width === undefined) return text;\n const binary =\n dialect === \"pg\"\n ? format === \"uuid\" || format === \"uuidv7\"\n ? \"uuid, bytea\"\n : \"bytea\"\n : dialect === \"mysql\"\n ? `BINARY(${width}), VARBINARY(${width}), BLOB`\n : \"BLOB\";\n return `${binary}, ${text}`;\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport { type NativeTypeDeclaration, nativeTypeFor } from \"../native-types\";\n\n/**\n * The physical vocabulary SQLite assigns to one DateTime native declaration.\n *\n * A missing declaration, a declaration that selects nothing on SQLite, and\n * explicit TEXT all use SQLite's default timestamp text. INTEGER is epoch milliseconds and\n * REAL is a Julian day. Schema validation, query lowering, result parsing, and\n * migration defaults consume this same interpretation.\n */\nexport function sqliteDateTimePhysicalForm(\n declaration: NativeTypeDeclaration | undefined\n): DateTimePhysicalForm {\n const nativeType = nativeTypeFor(declaration, \"sqlite\");\n if (nativeType === undefined) return \"text\";\n if (nativeType.type === \"INTEGER\") return \"epochMillis\";\n return nativeType.type === \"REAL\" ? \"julianDay\" : \"text\";\n}\n"],"mappings":"0KAqCA,MAAM,EAAU,IAAI,QAiBpB,SAAgB,gBACd,EACsB,CACtB,OAAO,GAAO,QAAU,GAAO,IAAA,GAAY,sBAAsB,EAAM,CAIzE,SAAgB,sBACd,EACsB,CACtB,GA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BuuaeEvq.mjs";import{b as t,n}from"./base-D3m1S7Uc.mjs";import{i as r}from"./validation-
|
|
2
|
-
//# sourceMappingURL=pinned-session-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,n}from"./base-D3m1S7Uc.mjs";import{i as r}from"./validation-gwZYm3Yn.mjs";import{n as i}from"./suppressed-failure-Bdo2aK81.mjs";import{t as a}from"./settle-C4w1GfTU.mjs";const o=`SELECT pg_advisory_unlock_all()`,s=`could not prove the advisory-lock state of a discarded migration session: its "${o}" reset failed.`,c=5e3;function unprovenLockStateError(e,n,r){return abandonedSessionError(e,s,n,t(r))}function abandonedSessionError(e,t,i,a){return new r(`Driver "${e}" ${t} ${i}`,{code:n.CONNECTION_CLOSED,cause:a,meta:{driver:e,operation:`pinnedSession`}})}function condemnedSessionError(e){return new r(`Driver "${e}" will pin no further migration session: an earlier session's "${o}" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,{code:n.CONNECTION_CLOSED,meta:{driver:e,operation:`pinnedSession`}})}const l=`The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.`;async function releaseReservedPostgresSession(e){if(e.lost===!0){let{closeOwnedTransport:t,driverName:n}=e;if(t===void 0)throw abandonedSessionError(n,`lost the connection of a reserved migration session and sent nothing more on it.`,l,void 0);t().catch(()=>void 0);return}if(!e.discard){e.release();return}try{await a(e.reset(),c,()=>Error(`The advisory-lock reset went unanswered for ${c} ms.`))}catch(t){await abandon(e,s,t)}e.release()}async function abandon(e,n,r){let{closeOwnedTransport:a,driverName:o}=e;if(a===void 0)throw abandonedSessionError(o,n,l,t(r));try{await a()}catch(e){throw i(abandonedSessionError(o,n,`The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.`,t(r)),e)}throw abandonedSessionError(o,n,`The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.`,t(r))}const u=new WeakMap;function refuseCondemnedSession(e,t){if(t.condemned)throw condemnedSessionError(e)}function leasePinnedCommand(e,t,n){let r=physicalSessionState(t);refuseCondemnedSession(e,r);let i=r.queued.then(()=>(refuseCondemnedSession(e,r),n()));return r.queued=i.then(()=>void 0,()=>void 0),i}function condemnPhysicalSession(e){physicalSessionState(e).condemned=!0}function physicalSessionState(e){let t=u.get(e);if(t)return t;let n={queued:Promise.resolve(),condemned:!1};return u.set(e,n),n}export{unprovenLockStateError as a,releaseReservedPostgresSession as i,condemnPhysicalSession as n,leasePinnedCommand as r,c as t};
|
|
2
|
+
//# sourceMappingURL=pinned-session-FYOFV_gB.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pinned-session-CjvR0Ge2.mjs","names":[],"sources":["../src/drivers/shared/pinned-session.ts"],"sourcesContent":["import { ConnectionError, VibORMErrorCode } from \"@errors\";\nimport { errorCause } from \"../../errors/diagnostic-safety\";\nimport { settleWithin } from \"./settle\";\nimport { withSuppressedFailure } from \"./suppressed-failure\";\n\n/** The PostgreSQL statement that resets a session's advisory-lock state. */\nconst ADVISORY_RESET = \"SELECT pg_advisory_unlock_all()\";\n\n/** Why a reserved session is abandoned, in the refusal's own words. */\nconst LOST_SESSION =\n \"lost the connection of a reserved migration session and sent nothing more on it.\";\nconst ADVISORY_RESET_FAILED = `could not prove the advisory-lock state of a discarded migration session: its \"${ADVISORY_RESET}\" reset failed.`;\n\n/**\n * How long one cleanup statement — `ROLLBACK`, the unlock, the limits reset,\n * the advisory reset — may take before its session is treated as lost.\n *\n * A healthy server answers each of them in milliseconds. A session that does\n * not answer one within this bound is a half-open socket or a dying backend,\n * and waiting on it longer only keeps the caller from the failure it already\n * has (plan S2: \"bound every cleanup statement\").\n */\nexport const CLEANUP_BOUND_MS = 5000;\n\n/**\n * One reserved physical session, as a provider hands it back.\n *\n * The plan's requirement (§3.5) is \"one physical producer across decisions and\n * commit boundaries\": a session lock is session-scoped, so acquiring it through\n * one pooled connection and running the protected work through another protects\n * nothing and can strand the lock. A reservation is therefore a connection the\n * provider has taken OUT of its pool, plus the exact way to give it back.\n */\nexport interface PinnedSessionReservation<TSession> {\n /** The reserved producer. Every statement of the session runs on it. */\n readonly session: TSession;\n /**\n * The failure the provider itself saw end this session's connection, or\n * `undefined` while it has seen none.\n *\n * Only a provider that observes its connection has one (`pg`, through the\n * client's `error` event). Elsewhere a lost connection is recognized by the\n * failure that reported it.\n */\n readonly lost?: () => unknown;\n /**\n * Returns the producer to the provider.\n *\n * `discard` is true when the session's state is unknown — a failed unlock, a\n * failed cleanup, or a thrown body — and the provider must then destroy the\n * connection rather than hand a session carrying unknown state back to a\n * pool. A provider whose session can never be made clean again (MySQL2, which\n * has executed `USE` and possibly author-owned statements) destroys\n * unconditionally and ignores the flag.\n *\n * `lost` is true when the connection itself is gone or stopped answering:\n * the provider must send nothing more on it — not even the reset a discard\n * otherwise runs — and abandon or destroy it.\n */\n release(discard: boolean, lost?: boolean): Promise<void>;\n}\n\n/**\n * The handle the pinned body uses to condemn its own producer.\n *\n * A thrown body already condemns the session. This exists for the case that\n * does not throw: an unlock statement that RETURNS a result proving the lock\n * was not released. That session is still usable in the provider's eyes and\n * would be returned to the pool holding a lock nobody owns.\n */\nexport interface PinnedSessionControl {\n /** Condemn this producer; it will be destroyed instead of released. */\n discard(): void;\n /**\n * Whether this session's connection is gone: the provider saw it end,\n * `failure` reports it, or a cleanup statement went unanswered. Once true it\n * stays true, and nothing more is sent on the session (plan S2).\n */\n lost(failure?: unknown): boolean;\n /** Runs one cleanup statement within `CLEANUP_BOUND_MS`; past it, the session is lost. */\n cleanup<T>(run: () => Promise<T>): Promise<T>;\n}\n\n/**\n * The refusal a discarded session whose reset FAILED raises.\n *\n * A session is discarded because its state is unknown, and the reset is what\n * makes it known again. When the reset fails too, the session may still hold\n * the migration lock every other command is excluded by — so it must not go\n * back to the provider, and saying nothing about that is not an option either:\n * a swallowed cleanup failure is how a pool ends up serving a connection that\n * blocks the next migration forever.\n *\n * The reset's own failure is the evidence, and it is the PROVIDER's value: it\n * goes through the one total normalizer rather than a bare `instanceof`, which\n * a rejection whose `getPrototypeOf` trap throws turns into a throw inside this\n * constructor — replacing the whole typed refusal with the trap's error.\n */\nexport function unprovenLockStateError(\n driverName: string,\n containment: string,\n cause: unknown\n): ConnectionError {\n return abandonedSessionError(\n driverName,\n ADVISORY_RESET_FAILED,\n containment,\n errorCause(cause)\n );\n}\n\nfunction abandonedSessionError(\n driverName: string,\n reason: string,\n containment: string,\n cause: Error | undefined\n): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" ${reason} ${containment}`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n cause,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * The refusal raised afterwards by EVERY driver whose one client was condemned.\n *\n * A transport that pools connections recovers by reserving a different one, so\n * this is only for the driver whose single client IS the session: there is no\n * other connection to reach for, and running the next migration command on a\n * session that may still hold the lock is precisely what the condemnation\n * exists to prevent. Two drivers over that one client are two callers of this\n * same refusal, because the session they would both pin is the same session.\n */\nexport function condemnedSessionError(driverName: string): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" will pin no further migration session: an earlier session's \"${ADVISORY_RESET}\" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * What was actually DONE about the abandoned connection, in the refusal's own\n * words.\n *\n * Three outcomes, three sentences, each chosen once the outcome is known\n * rather than once the ownership is known. A single sentence written before the\n * close was attempted claimed the backend had been ended even when ending it\n * threw — and the one thing a caller does with that claim is stop looking for a\n * connection that is still running, still holding the lock this refusal exists\n * to report.\n */\nconst CALLER_OWNED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.\";\nconst CLOSED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.\";\nconst CLOSE_FAILED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.\";\n\n/**\n * Returns a reserved PostgreSQL session to its pool, or condemns it — the ONE\n * rule for every provider that reserves a connection it cannot destroy.\n *\n * postgres.js and Bun SQL both expose `release()` and nothing else: there is no\n * destructive return to reach for, so a session whose reset failed is ABANDONED\n * — never released — which is the only way it stops being a connection the pool\n * will hand to the next caller.\n *\n * Abandoning it leaves the lock held until that backend goes away, so a\n * transport VibORM created is closed too: ending it terminates the backend, and\n * PostgreSQL frees every advisory lock the session held. A transport the CALLER\n * supplied is never closed for this — it is theirs, may be serving their own\n * code, and closing it to tidy up VibORM's cleanup failure would be a far\n * larger effect than the one being contained.\n *\n * A LOST session (plan S2) is abandoned the same way without the reset: its\n * connection is gone or stopped answering, and a statement written to it is,\n * on postgres.js, an uncaught crash from inside the provider's write loop. Its\n * owned transport is closed; a supplied one is reported, since abandoning is\n * all VibORM may do with it.\n */\nexport async function releaseReservedPostgresSession(reservation: {\n readonly driverName: string;\n readonly discard: boolean;\n readonly lost?: boolean | undefined;\n /** Runs `SELECT pg_advisory_unlock_all()` on the reserved session. */\n readonly reset: () => Promise<unknown>;\n /** Hands the reserved session back to the provider's pool. */\n readonly release: () => void;\n /** Closes the transport, or absent when the CALLER owns it. */\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n}): Promise<void> {\n if (reservation.lost === true) {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n LOST_SESSION,\n CALLER_OWNED_CONTAINMENT,\n undefined\n );\n }\n // Not awaited: the connection failure the caller holds is already the\n // answer, and the close lets the transport's other queries finish first\n // (postgres.js waits on the dead connection's unsettled query until its\n // bound). The transport is withdrawn before it closes, and a session the\n // close cannot end is ended by the server's idle limit.\n closeOwnedTransport().catch(() => undefined);\n return;\n }\n if (!reservation.discard) {\n reservation.release();\n return;\n }\n\n try {\n await settleWithin(\n reservation.reset(),\n CLEANUP_BOUND_MS,\n () =>\n new Error(\n `The advisory-lock reset went unanswered for ${CLEANUP_BOUND_MS} ms.`\n )\n );\n } catch (resetFailure) {\n await abandon(reservation, ADVISORY_RESET_FAILED, resetFailure);\n }\n reservation.release();\n}\n\n/**\n * Abandons a reserved session: never released, its owned transport closed,\n * and the refusal that says so thrown. A transport the caller supplied is only\n * abandoned.\n */\nasync function abandon(\n reservation: {\n readonly driverName: string;\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n },\n reason: string,\n cause: unknown\n): Promise<void> {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n reason,\n CALLER_OWNED_CONTAINMENT,\n errorCause(cause)\n );\n }\n try {\n await closeOwnedTransport();\n } catch (closeFailure) {\n // The reason stays primary — it is what the caller acts on — and the\n // close's own failure is cleanup evidence beside it.\n throw withSuppressedFailure(\n abandonedSessionError(\n driverName,\n reason,\n CLOSE_FAILED_CONTAINMENT,\n errorCause(cause)\n ),\n closeFailure\n );\n }\n throw abandonedSessionError(\n driverName,\n reason,\n CLOSED_CONTAINMENT,\n errorCause(cause)\n );\n}\n\n/** What VibORM knows about one PHYSICAL session it pins commands on. */\ninterface PhysicalSessionState {\n /**\n * The pinned commands already queued on this session. It never rejects, so\n * one command's failure cannot poison the queue — the next command runs\n * either way, exactly as it would after a success.\n */\n queued: Promise<void>;\n /**\n * Set when a discarded session's advisory-lock reset failed, and never\n * cleared: nothing that happens later can prove a lock was released.\n */\n condemned: boolean;\n}\n\n/**\n * What is known about each PHYSICAL session, keyed on the session itself.\n *\n * A driver's connection queue serializes the commands of THAT driver. Two\n * drivers built over one supplied client — the documented shape for two\n * schema-scoped estates over one PGlite — own two queues and one session, so\n * the queue arbitrates nothing between them, and a PostgreSQL session advisory\n * lock is REENTRANT: the second command re-acquires the lock the first is\n * holding instead of waiting for it, then reads and writes inside the first\n * command's session. The client is the only thing both drivers agree on, so it\n * is what this is keyed on.\n *\n * The condemnation shares that key because it answers for the same subject: a\n * failed reset leaves the CLIENT's lock state unknown, not the wrapper's. Kept\n * on the driver instead, it was a fact the other wrappers over that client\n * never consulted, and their next command ran inside the session it condemned.\n *\n * Weak by construction: the entry dies with the client, and a client nobody\n * holds keeps nothing alive here.\n */\nconst PHYSICAL_SESSIONS = new WeakMap<object, PhysicalSessionState>();\n\n/**\n * Refuses a command on a session whose advisory-lock state was condemned.\n *\n * One refusal, read at two moments, and each covers what the other cannot. At\n * ADMISSION, so a session condemned before this command arrived refuses now\n * rather than behind a queue whose head may itself be waiting on the very lock\n * nobody can account for. At the FRONT of the queue, because condemnation lands\n * BETWEEN the two: the command ahead of this one is the one whose reset fails,\n * and this one was admitted while that session still looked accountable.\n */\nfunction refuseCondemnedSession(\n driverName: string,\n state: PhysicalSessionState\n): void {\n if (state.condemned) {\n throw condemnedSessionError(driverName);\n }\n}\n\n/**\n * Runs `command` exclusively on this physical session, when it may still be\n * pinned at all.\n *\n * The refusal is here rather than beside it because this is the one path every\n * pinned command over a shared session takes, and it lands before `command` —\n * so no body and no statement of the refused command reaches the client.\n */\nexport function leasePinnedCommand<T>(\n driverName: string,\n session: object,\n command: () => Promise<T>\n): Promise<T> {\n const state = physicalSessionState(session);\n refuseCondemnedSession(driverName, state);\n const next = state.queued.then(() => {\n refuseCondemnedSession(driverName, state);\n return command();\n });\n state.queued = next.then(\n () => undefined,\n () => undefined\n );\n return next;\n}\n\n/**\n * Records that this physical session's advisory-lock state can no longer be\n * accounted for — for every driver that reaches it, not only the one whose\n * reset failed.\n */\nexport function condemnPhysicalSession(session: object): void {\n physicalSessionState(session).condemned = true;\n}\n\n/** This session's state, created on first use and mutated in place after. */\nfunction physicalSessionState(session: object): PhysicalSessionState {\n const existing = PHYSICAL_SESSIONS.get(session);\n if (existing) {\n return existing;\n }\n const created: PhysicalSessionState = {\n queued: Promise.resolve(),\n condemned: false,\n };\n PHYSICAL_SESSIONS.set(session, created);\n return created;\n}\n"],"mappings":"iOAMA,MAAM,EAAiB,kCAKjB,EAAwB,kFAAkF,EAAe,iBAWlH,EAAmB,IA4EhC,SAAgB,uBACd,EACA,EACA,EACiB,CACjB,OAAO,sBACL,EACA,EACA,EACA,EAAW,EAAM,CAClB,CAGH,SAAS,sBACP,EACA,EACA,EACA,EACiB,CACjB,OAAO,IAAI,EACT,WAAW,EAAW,IAAI,EAAO,GAAG,IACpC,CACE,KAAM,EAAgB,kBACtB,QACA,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAaH,SAAgB,sBAAsB,EAAqC,CACzE,OAAO,IAAI,EACT,WAAW,EAAW,iEAAiE,EAAe,4NACtG,CACE,KAAM,EAAgB,kBACtB,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAcH,MAAM,EACJ,yLA4BF,eAAsB,+BAA+B,EAUnC,CAChB,GAAI,EAAY,OAAS,GAAM,CAC7B,GAAM,CAAE,sBAAqB,cAAe,EAC5C,GAAI,IAAwB,IAAA,GAC1B,MAAM,sBACJ,EACA,mFACA,EACA,IAAA,GACD,CAOH,GAAqB,CAAC,UAAY,IAAA,GAAU,CAC5C,OAEF,GAAI,CAAC,EAAY,QAAS,CACxB,EAAY,SAAS,CACrB,OAGF,GAAI,CACF,MAAM,EACJ,EAAY,OAAO,CACnB,MAEM,MACF,+CAA+C,EAAiB,MACjE,CACJ,OACM,EAAc,CACrB,MAAM,QAAQ,EAAa,EAAuB,EAAa,CAEjE,EAAY,SAAS,CAQvB,eAAe,QACb,EAIA,EACA,EACe,CACf,GAAM,CAAE,sBAAqB,cAAe,EAC5C,GAAI,IAAwB,IAAA,GAC1B,MAAM,sBACJ,EACA,EACA,EACA,EAAW,EAAM,CAClB,CAEH,GAAI,CACF,MAAM,GAAqB,OACpB,EAAc,CAGrB,MAAM,EACJ,sBACE,EACA,EACA,8RACA,EAAW,EAAM,CAClB,CACD,EACD,CAEH,MAAM,sBACJ,EACA,EACA,iMACA,EAAW,EAAM,CAClB,CAsCH,MAAM,EAAoB,IAAI,QAY9B,SAAS,uBACP,EACA,EACM,CACN,GAAI,EAAM,UACR,MAAM,sBAAsB,EAAW,CAY3C,SAAgB,mBACd,EACA,EACA,EACY,CACZ,IAAM,EAAQ,qBAAqB,EAAQ,CAC3C,uBAAuB,EAAY,EAAM,CACzC,IAAM,EAAO,EAAM,OAAO,UACxB,uBAAuB,EAAY,EAAM,CAClC,GAAS,EAChB,CAKF,MAJA,GAAM,OAAS,EAAK,SACZ,IAAA,OACA,IAAA,GACP,CACM,EAQT,SAAgB,uBAAuB,EAAuB,CAC5D,qBAAqB,EAAQ,CAAC,UAAY,GAI5C,SAAS,qBAAqB,EAAuC,CACnE,IAAM,EAAW,EAAkB,IAAI,EAAQ,CAC/C,GAAI,EACF,OAAO,EAET,IAAM,EAAgC,CACpC,OAAQ,QAAQ,SAAS,CACzB,UAAW,GACZ,CAED,OADA,EAAkB,IAAI,EAAS,EAAQ,CAChC"}
|
|
1
|
+
{"version":3,"file":"pinned-session-FYOFV_gB.mjs","names":[],"sources":["../src/drivers/shared/pinned-session.ts"],"sourcesContent":["import { ConnectionError, VibORMErrorCode } from \"@errors\";\nimport { errorCause } from \"../../errors/diagnostic-safety\";\nimport { settleWithin } from \"./settle\";\nimport { withSuppressedFailure } from \"./suppressed-failure\";\n\n/** The PostgreSQL statement that resets a session's advisory-lock state. */\nconst ADVISORY_RESET = \"SELECT pg_advisory_unlock_all()\";\n\n/** Why a reserved session is abandoned, in the refusal's own words. */\nconst LOST_SESSION =\n \"lost the connection of a reserved migration session and sent nothing more on it.\";\nconst ADVISORY_RESET_FAILED = `could not prove the advisory-lock state of a discarded migration session: its \"${ADVISORY_RESET}\" reset failed.`;\n\n/**\n * How long one cleanup statement — `ROLLBACK`, the unlock, the limits reset,\n * the advisory reset — may take before its session is treated as lost.\n *\n * A healthy server answers each of them in milliseconds. A session that does\n * not answer one within this bound is a half-open socket or a dying backend,\n * and waiting on it longer only keeps the caller from the failure it already\n * has (plan S2: \"bound every cleanup statement\").\n */\nexport const CLEANUP_BOUND_MS = 5000;\n\n/**\n * One reserved physical session, as a provider hands it back.\n *\n * The plan's requirement (§3.5) is \"one physical producer across decisions and\n * commit boundaries\": a session lock is session-scoped, so acquiring it through\n * one pooled connection and running the protected work through another protects\n * nothing and can strand the lock. A reservation is therefore a connection the\n * provider has taken OUT of its pool, plus the exact way to give it back.\n */\nexport interface PinnedSessionReservation<TSession> {\n /** The reserved producer. Every statement of the session runs on it. */\n readonly session: TSession;\n /**\n * The failure the provider itself saw end this session's connection, or\n * `undefined` while it has seen none.\n *\n * Only a provider that observes its connection has one (`pg`, through the\n * client's `error` event). Elsewhere a lost connection is recognized by the\n * failure that reported it.\n */\n readonly lost?: () => unknown;\n /**\n * Returns the producer to the provider.\n *\n * `discard` is true when the session's state is unknown — a failed unlock, a\n * failed cleanup, or a thrown body — and the provider must then destroy the\n * connection rather than hand a session carrying unknown state back to a\n * pool. A provider whose session can never be made clean again (MySQL2, which\n * has executed `USE` and possibly author-owned statements) destroys\n * unconditionally and ignores the flag.\n *\n * `lost` is true when the connection itself is gone or stopped answering:\n * the provider must send nothing more on it — not even the reset a discard\n * otherwise runs — and abandon or destroy it.\n */\n release(discard: boolean, lost?: boolean): Promise<void>;\n}\n\n/**\n * The handle the pinned body uses to condemn its own producer.\n *\n * A thrown body already condemns the session. This exists for the case that\n * does not throw: an unlock statement that RETURNS a result proving the lock\n * was not released. That session is still usable in the provider's eyes and\n * would be returned to the pool holding a lock nobody owns.\n */\nexport interface PinnedSessionControl {\n /** Condemn this producer; it will be destroyed instead of released. */\n discard(): void;\n /**\n * Whether this session's connection is gone: the provider saw it end,\n * `failure` reports it, or a cleanup statement went unanswered. Once true it\n * stays true, and nothing more is sent on the session (plan S2).\n */\n lost(failure?: unknown): boolean;\n /** Runs one cleanup statement within `CLEANUP_BOUND_MS`; past it, the session is lost. */\n cleanup<T>(run: () => Promise<T>): Promise<T>;\n}\n\n/**\n * The refusal a discarded session whose reset FAILED raises.\n *\n * A session is discarded because its state is unknown, and the reset is what\n * makes it known again. When the reset fails too, the session may still hold\n * the migration lock every other command is excluded by — so it must not go\n * back to the provider, and saying nothing about that is not an option either:\n * a swallowed cleanup failure is how a pool ends up serving a connection that\n * blocks the next migration forever.\n *\n * The reset's own failure is the evidence, and it is the PROVIDER's value: it\n * goes through the one total normalizer rather than a bare `instanceof`, which\n * a rejection whose `getPrototypeOf` trap throws turns into a throw inside this\n * constructor — replacing the whole typed refusal with the trap's error.\n */\nexport function unprovenLockStateError(\n driverName: string,\n containment: string,\n cause: unknown\n): ConnectionError {\n return abandonedSessionError(\n driverName,\n ADVISORY_RESET_FAILED,\n containment,\n errorCause(cause)\n );\n}\n\nfunction abandonedSessionError(\n driverName: string,\n reason: string,\n containment: string,\n cause: Error | undefined\n): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" ${reason} ${containment}`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n cause,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * The refusal raised afterwards by EVERY driver whose one client was condemned.\n *\n * A transport that pools connections recovers by reserving a different one, so\n * this is only for the driver whose single client IS the session: there is no\n * other connection to reach for, and running the next migration command on a\n * session that may still hold the lock is precisely what the condemnation\n * exists to prevent. Two drivers over that one client are two callers of this\n * same refusal, because the session they would both pin is the same session.\n */\nexport function condemnedSessionError(driverName: string): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" will pin no further migration session: an earlier session's \"${ADVISORY_RESET}\" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * What was actually DONE about the abandoned connection, in the refusal's own\n * words.\n *\n * Three outcomes, three sentences, each chosen once the outcome is known\n * rather than once the ownership is known. A single sentence written before the\n * close was attempted claimed the backend had been ended even when ending it\n * threw — and the one thing a caller does with that claim is stop looking for a\n * connection that is still running, still holding the lock this refusal exists\n * to report.\n */\nconst CALLER_OWNED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.\";\nconst CLOSED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.\";\nconst CLOSE_FAILED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.\";\n\n/**\n * Returns a reserved PostgreSQL session to its pool, or condemns it — the ONE\n * rule for every provider that reserves a connection it cannot destroy.\n *\n * postgres.js and Bun SQL both expose `release()` and nothing else: there is no\n * destructive return to reach for, so a session whose reset failed is ABANDONED\n * — never released — which is the only way it stops being a connection the pool\n * will hand to the next caller.\n *\n * Abandoning it leaves the lock held until that backend goes away, so a\n * transport VibORM created is closed too: ending it terminates the backend, and\n * PostgreSQL frees every advisory lock the session held. A transport the CALLER\n * supplied is never closed for this — it is theirs, may be serving their own\n * code, and closing it to tidy up VibORM's cleanup failure would be a far\n * larger effect than the one being contained.\n *\n * A LOST session (plan S2) is abandoned the same way without the reset: its\n * connection is gone or stopped answering, and a statement written to it is,\n * on postgres.js, an uncaught crash from inside the provider's write loop. Its\n * owned transport is closed; a supplied one is reported, since abandoning is\n * all VibORM may do with it.\n */\nexport async function releaseReservedPostgresSession(reservation: {\n readonly driverName: string;\n readonly discard: boolean;\n readonly lost?: boolean | undefined;\n /** Runs `SELECT pg_advisory_unlock_all()` on the reserved session. */\n readonly reset: () => Promise<unknown>;\n /** Hands the reserved session back to the provider's pool. */\n readonly release: () => void;\n /** Closes the transport, or absent when the CALLER owns it. */\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n}): Promise<void> {\n if (reservation.lost === true) {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n LOST_SESSION,\n CALLER_OWNED_CONTAINMENT,\n undefined\n );\n }\n // Not awaited: the connection failure the caller holds is already the\n // answer, and the close lets the transport's other queries finish first\n // (postgres.js waits on the dead connection's unsettled query until its\n // bound). The transport is withdrawn before it closes, and a session the\n // close cannot end is ended by the server's idle limit.\n closeOwnedTransport().catch(() => undefined);\n return;\n }\n if (!reservation.discard) {\n reservation.release();\n return;\n }\n\n try {\n await settleWithin(\n reservation.reset(),\n CLEANUP_BOUND_MS,\n () =>\n new Error(\n `The advisory-lock reset went unanswered for ${CLEANUP_BOUND_MS} ms.`\n )\n );\n } catch (resetFailure) {\n await abandon(reservation, ADVISORY_RESET_FAILED, resetFailure);\n }\n reservation.release();\n}\n\n/**\n * Abandons a reserved session: never released, its owned transport closed,\n * and the refusal that says so thrown. A transport the caller supplied is only\n * abandoned.\n */\nasync function abandon(\n reservation: {\n readonly driverName: string;\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n },\n reason: string,\n cause: unknown\n): Promise<void> {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n reason,\n CALLER_OWNED_CONTAINMENT,\n errorCause(cause)\n );\n }\n try {\n await closeOwnedTransport();\n } catch (closeFailure) {\n // The reason stays primary — it is what the caller acts on — and the\n // close's own failure is cleanup evidence beside it.\n throw withSuppressedFailure(\n abandonedSessionError(\n driverName,\n reason,\n CLOSE_FAILED_CONTAINMENT,\n errorCause(cause)\n ),\n closeFailure\n );\n }\n throw abandonedSessionError(\n driverName,\n reason,\n CLOSED_CONTAINMENT,\n errorCause(cause)\n );\n}\n\n/** What VibORM knows about one PHYSICAL session it pins commands on. */\ninterface PhysicalSessionState {\n /**\n * The pinned commands already queued on this session. It never rejects, so\n * one command's failure cannot poison the queue — the next command runs\n * either way, exactly as it would after a success.\n */\n queued: Promise<void>;\n /**\n * Set when a discarded session's advisory-lock reset failed, and never\n * cleared: nothing that happens later can prove a lock was released.\n */\n condemned: boolean;\n}\n\n/**\n * What is known about each PHYSICAL session, keyed on the session itself.\n *\n * A driver's connection queue serializes the commands of THAT driver. Two\n * drivers built over one supplied client — the documented shape for two\n * schema-scoped estates over one PGlite — own two queues and one session, so\n * the queue arbitrates nothing between them, and a PostgreSQL session advisory\n * lock is REENTRANT: the second command re-acquires the lock the first is\n * holding instead of waiting for it, then reads and writes inside the first\n * command's session. The client is the only thing both drivers agree on, so it\n * is what this is keyed on.\n *\n * The condemnation shares that key because it answers for the same subject: a\n * failed reset leaves the CLIENT's lock state unknown, not the wrapper's. Kept\n * on the driver instead, it was a fact the other wrappers over that client\n * never consulted, and their next command ran inside the session it condemned.\n *\n * Weak by construction: the entry dies with the client, and a client nobody\n * holds keeps nothing alive here.\n */\nconst PHYSICAL_SESSIONS = new WeakMap<object, PhysicalSessionState>();\n\n/**\n * Refuses a command on a session whose advisory-lock state was condemned.\n *\n * One refusal, read at two moments, and each covers what the other cannot. At\n * ADMISSION, so a session condemned before this command arrived refuses now\n * rather than behind a queue whose head may itself be waiting on the very lock\n * nobody can account for. At the FRONT of the queue, because condemnation lands\n * BETWEEN the two: the command ahead of this one is the one whose reset fails,\n * and this one was admitted while that session still looked accountable.\n */\nfunction refuseCondemnedSession(\n driverName: string,\n state: PhysicalSessionState\n): void {\n if (state.condemned) {\n throw condemnedSessionError(driverName);\n }\n}\n\n/**\n * Runs `command` exclusively on this physical session, when it may still be\n * pinned at all.\n *\n * The refusal is here rather than beside it because this is the one path every\n * pinned command over a shared session takes, and it lands before `command` —\n * so no body and no statement of the refused command reaches the client.\n */\nexport function leasePinnedCommand<T>(\n driverName: string,\n session: object,\n command: () => Promise<T>\n): Promise<T> {\n const state = physicalSessionState(session);\n refuseCondemnedSession(driverName, state);\n const next = state.queued.then(() => {\n refuseCondemnedSession(driverName, state);\n return command();\n });\n state.queued = next.then(\n () => undefined,\n () => undefined\n );\n return next;\n}\n\n/**\n * Records that this physical session's advisory-lock state can no longer be\n * accounted for — for every driver that reaches it, not only the one whose\n * reset failed.\n */\nexport function condemnPhysicalSession(session: object): void {\n physicalSessionState(session).condemned = true;\n}\n\n/** This session's state, created on first use and mutated in place after. */\nfunction physicalSessionState(session: object): PhysicalSessionState {\n const existing = PHYSICAL_SESSIONS.get(session);\n if (existing) {\n return existing;\n }\n const created: PhysicalSessionState = {\n queued: Promise.resolve(),\n condemned: false,\n };\n PHYSICAL_SESSIONS.set(session, created);\n return created;\n}\n"],"mappings":"iOAMA,MAAM,EAAiB,kCAKjB,EAAwB,kFAAkF,EAAe,iBAWlH,EAAmB,IA4EhC,SAAgB,uBACd,EACA,EACA,EACiB,CACjB,OAAO,sBACL,EACA,EACA,EACA,EAAW,EAAM,CAClB,CAGH,SAAS,sBACP,EACA,EACA,EACA,EACiB,CACjB,OAAO,IAAI,EACT,WAAW,EAAW,IAAI,EAAO,GAAG,IACpC,CACE,KAAM,EAAgB,kBACtB,QACA,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAaH,SAAgB,sBAAsB,EAAqC,CACzE,OAAO,IAAI,EACT,WAAW,EAAW,iEAAiE,EAAe,4NACtG,CACE,KAAM,EAAgB,kBACtB,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAcH,MAAM,EACJ,yLA4BF,eAAsB,+BAA+B,EAUnC,CAChB,GAAI,EAAY,OAAS,GAAM,CAC7B,GAAM,CAAE,sBAAqB,cA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|
package/dist/planetscale.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-
|
|
1
|
+
import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-B4IWFJfv.mjs";
|
|
2
2
|
import { Client, Config, Connection } from "@planetscale/database";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/planetscale/index.d.ts
|