viborm 1.1.0 → 1.2.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-namespace-DMhEF6my.mjs → adapter-namespace-DqkJQdrD.mjs} +2 -2
- package/dist/{adapter-namespace-DMhEF6my.mjs.map → adapter-namespace-DqkJQdrD.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-DcEm5tt_.mjs → array-literal-BsbbSLw3.mjs} +1 -1
- package/dist/{array-literal-DcEm5tt_.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
- package/dist/base-AdXAoy6l.mjs +2 -0
- package/dist/base-AdXAoy6l.mjs.map +1 -0
- package/dist/batch-refs-4L8ECdPU.mjs +2 -0
- package/dist/batch-refs-4L8ECdPU.mjs.map +1 -0
- package/dist/bind-parameter-capacity-CjPgqnmx.mjs +2 -0
- package/dist/{bind-parameter-capacity-DzMcIB95.mjs.map → bind-parameter-capacity-CjPgqnmx.mjs.map} +1 -1
- package/dist/builder-Ycvq3ETg.mjs +2 -0
- package/dist/builder-Ycvq3ETg.mjs.map +1 -0
- package/dist/bun-sql.d.mts +19 -2
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +9 -8
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/bun-sqlite.mjs.map +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/memory.mjs.map +1 -1
- package/dist/cache-BO57X0TT.mjs +2 -0
- package/dist/cache-BO57X0TT.mjs.map +1 -0
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/canonical-json-rfC2Dg0X.mjs +2 -0
- package/dist/canonical-json-rfC2Dg0X.mjs.map +1 -0
- package/dist/chain-Dh0FV72b.mjs +2 -0
- package/dist/chain-Dh0FV72b.mjs.map +1 -0
- package/dist/cli.mjs +5 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-BLiBmykn.mjs +2 -0
- package/dist/client-BLiBmykn.mjs.map +1 -0
- package/dist/client-CCgfcp5A.mjs +52 -0
- package/dist/client-CCgfcp5A.mjs.map +1 -0
- package/dist/client-CRBo95D0.d.mts +610 -0
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-W8H2Khng.mjs → clock-CK41KO7t.mjs} +1 -1
- package/dist/{clock-W8H2Khng.mjs.map → clock-CK41KO7t.mjs.map} +1 -1
- package/dist/config.d.mts +3 -3
- package/dist/config.mjs +1 -1
- package/dist/controls-DXgIn4zh.mjs +2 -0
- package/dist/controls-DXgIn4zh.mjs.map +1 -0
- 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-oIhiYZEP.mjs +2 -0
- package/dist/{datetime-physical-codec-BK93pJGW.mjs.map → datetime-physical-codec-oIhiYZEP.mjs.map} +1 -1
- package/dist/driver-B19QlFqn.mjs +2 -0
- package/dist/{driver-ZIbkciaz.mjs.map → driver-B19QlFqn.mjs.map} +1 -1
- package/dist/driver-BlnKXPFF.mjs +2 -0
- package/dist/driver-BlnKXPFF.mjs.map +1 -0
- package/dist/driver.d.mts +2 -2
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-CnPCv1dm.mjs +2 -0
- package/dist/error-mapping-CnPCv1dm.mjs.map +1 -0
- package/dist/every-4KE0p2Gw.mjs +2 -0
- package/dist/every-4KE0p2Gw.mjs.map +1 -0
- package/dist/{execution-context-Bm_qTp1i.mjs → execution-context-BKR3bgES.mjs} +1 -1
- package/dist/{execution-context-Bm_qTp1i.mjs.map → execution-context-BKR3bgES.mjs.map} +1 -1
- package/dist/fs-estate-CAhDg7nY.mjs +2 -0
- package/dist/fs-estate-CAhDg7nY.mjs.map +1 -0
- package/dist/{geo-area-codec-B4DRInvA.mjs → geo-area-codec-1SY9im7O.mjs} +2 -2
- package/dist/{geo-area-codec-B4DRInvA.mjs.map → geo-area-codec-1SY9im7O.mjs.map} +1 -1
- package/dist/geo-point-codec-lhxH42SK.mjs +2 -0
- package/dist/geo-point-codec-lhxH42SK.mjs.map +1 -0
- package/dist/{hydration-D6JICBQG.mjs → hydration-CAxOL4aI.mjs} +2 -2
- package/dist/{hydration-D6JICBQG.mjs.map → hydration-CAxOL4aI.mjs.map} +1 -1
- package/dist/identifier-conversion-GgbwHc2G.mjs +2 -0
- package/dist/identifier-conversion-GgbwHc2G.mjs.map +1 -0
- package/dist/{identifier-EsWKVHXi.mjs → identifier-hQCs8M1n.mjs} +2 -2
- package/dist/{identifier-EsWKVHXi.mjs.map → identifier-hQCs8M1n.mjs.map} +1 -1
- package/dist/identity-CLFhCTZx.mjs +2 -0
- package/dist/identity-CLFhCTZx.mjs.map +1 -0
- package/dist/{index-BbcE-gyl.d.mts → index-C_XLSTy2.d.mts} +624 -351
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/instrumentation.mjs.map +1 -1
- package/dist/{invariant-DCsftyml.mjs → invariant-BnLYqsHO.mjs} +1 -1
- package/dist/{invariant-DCsftyml.mjs.map → invariant-BnLYqsHO.mjs.map} +1 -1
- package/dist/{json-number-TpD-pfqt.mjs → json-number-CGXpPu4D.mjs} +1 -1
- package/dist/{json-number-TpD-pfqt.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
- package/dist/key-BeoOwGr3.mjs +2 -0
- package/dist/key-BeoOwGr3.mjs.map +1 -0
- package/dist/libsql-Bu_IdFU1.mjs +11 -0
- package/dist/libsql-Bu_IdFU1.mjs.map +1 -0
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/memory-D4yxtCPK.mjs +2 -0
- package/dist/memory-D4yxtCPK.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +6 -0
- package/dist/migrations/mysql.mjs +2 -0
- package/dist/migrations/mysql.mjs.map +1 -0
- package/dist/migrations/postgres.d.mts +6 -0
- package/dist/migrations/postgres.mjs +2 -0
- package/dist/migrations/postgres.mjs.map +1 -0
- package/dist/migrations/sqlite.d.mts +6 -0
- package/dist/migrations/sqlite.mjs +2 -0
- package/dist/migrations/sqlite.mjs.map +1 -0
- package/dist/migrations/storage/durable-object.d.mts +17 -0
- package/dist/migrations/storage/durable-object.mjs +2 -0
- package/dist/migrations/storage/durable-object.mjs.map +1 -0
- package/dist/migrations/storage/fs.d.mts +6 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +14 -0
- package/dist/migrations/storage/r2.mjs +2 -0
- package/dist/migrations/storage/r2.mjs.map +1 -0
- package/dist/migrations/tenant.d.mts +92 -0
- package/dist/migrations/tenant.mjs +2 -0
- package/dist/migrations/tenant.mjs.map +1 -0
- package/dist/{migrations-BWZSBMZh.mjs → migrations-DTObIjAm.mjs} +2 -2
- package/dist/migrations-DTObIjAm.mjs.map +1 -0
- package/dist/migrations.d.mts +6 -561
- package/dist/migrations.mjs +1 -1
- package/dist/migrations.mjs.map +1 -1
- package/dist/mysql-CibPaHSp.mjs +99 -0
- package/dist/mysql-CibPaHSp.mjs.map +1 -0
- package/dist/mysql-adapter-DkJPfoGf.mjs +2 -0
- package/dist/mysql-adapter-DkJPfoGf.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -3
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/object-store-DQR6bTBY.mjs +2 -0
- package/dist/object-store-DQR6bTBY.mjs.map +1 -0
- package/dist/object-store-DyYOCtmX.d.mts +156 -0
- package/dist/observation-DUSm7oXK.mjs +2 -0
- package/dist/observation-DUSm7oXK.mjs.map +1 -0
- package/dist/pg.d.mts +37 -12
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +2 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/physical-6V_LNU3L.mjs +2 -0
- package/dist/{physical-BkelResN.mjs.map → physical-6V_LNU3L.mjs.map} +1 -1
- package/dist/pinned-session-CLxj5M5e.mjs +2 -0
- package/dist/pinned-session-CLxj5M5e.mjs.map +1 -0
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-Bbw8W81b.d.mts → planner-C6Lfsasx.d.mts} +57 -3
- package/dist/postgres-adapter-B3SQvcV1.mjs +2 -0
- package/dist/postgres-adapter-B3SQvcV1.mjs.map +1 -0
- package/dist/postgres-adapter-CQD2oGuD.mjs +2 -0
- package/dist/postgres-adapter-CQD2oGuD.mjs.map +1 -0
- package/dist/postgres-oqNW9xqo.mjs +415 -0
- package/dist/postgres-oqNW9xqo.mjs.map +1 -0
- package/dist/{postgres-result-Dc_iW3Hb.mjs → postgres-result-7F0DllQe.mjs} +2 -2
- package/dist/{postgres-result-Dc_iW3Hb.mjs.map → postgres-result-7F0DllQe.mjs.map} +1 -1
- package/dist/postgres.d.mts +11 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-DXj_pOT0.mjs → provider-limits-BHATED_m.mjs} +2 -2
- package/dist/{provider-limits-DXj_pOT0.mjs.map → provider-limits-BHATED_m.mjs.map} +1 -1
- package/dist/registration-preflight-DEjv050M.mjs +4 -0
- package/dist/registration-preflight-DEjv050M.mjs.map +1 -0
- package/dist/result-shape-CTNdNSW3.mjs +2 -0
- package/dist/result-shape-CTNdNSW3.mjs.map +1 -0
- package/dist/scalar-U0wD5bKy.mjs +2 -0
- package/dist/{scalar-BTktMqvO.mjs.map → scalar-U0wD5bKy.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema/json.mjs.map +1 -1
- package/dist/schema-Cjem1-0f.mjs +2 -0
- package/dist/{schema-BFNcMdO6.mjs.map → schema-Cjem1-0f.mjs.map} +1 -1
- package/dist/schema-introspection-DEYGC2qg.mjs +6 -0
- package/dist/schema-introspection-DEYGC2qg.mjs.map +1 -0
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-BgqlrePH.mjs → select-assembly-f1UGoblh.mjs} +2 -2
- package/dist/select-assembly-f1UGoblh.mjs.map +1 -0
- package/dist/settle-B9Vg1FnP.mjs +2 -0
- package/dist/settle-B9Vg1FnP.mjs.map +1 -0
- package/dist/soft-delete.d.mts +1 -1
- package/dist/{sql--69HUgel.mjs → sql-Bp7jicEX.mjs} +1 -1
- package/dist/{sql--69HUgel.mjs.map → sql-Bp7jicEX.mjs.map} +1 -1
- package/dist/{sql-statement-tokens-CykxFmOJ.mjs → sql-statement-tokens-BBcoGmJb.mjs} +1 -1
- package/dist/{sql-statement-tokens-CykxFmOJ.mjs.map → sql-statement-tokens-BBcoGmJb.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-CW_3l6ea.mjs +2 -0
- package/dist/sqlite-adapter-CW_3l6ea.mjs.map +1 -0
- package/dist/sqlite-utils-DlgokMJN.mjs +2 -0
- package/dist/sqlite-utils-DlgokMJN.mjs.map +1 -0
- package/dist/sqlite3.d.mts +2 -8
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/standard-sql-Bk4RZPqJ.mjs +6 -0
- package/dist/standard-sql-Bk4RZPqJ.mjs.map +1 -0
- package/dist/{suppressed-failure-BPxfHTMc.mjs → suppressed-failure-BwULh-8h.mjs} +1 -1
- package/dist/{suppressed-failure-BPxfHTMc.mjs.map → suppressed-failure-BwULh-8h.mjs.map} +1 -1
- package/dist/{terminal-BbRi0CNZ.mjs → terminal-C8cq1WWX.mjs} +2 -2
- package/dist/{terminal-BbRi0CNZ.mjs.map → terminal-C8cq1WWX.mjs.map} +1 -1
- package/dist/{transaction-oskVwmsf.mjs → transaction-Bnl6ULTw.mjs} +2 -2
- package/dist/transaction-Bnl6ULTw.mjs.map +1 -0
- package/dist/{transaction-operation-BC7aua5V.mjs → transaction-operation-CKK3l_9x.mjs} +2 -2
- package/dist/{transaction-operation-BC7aua5V.mjs.map → transaction-operation-CKK3l_9x.mjs.map} +1 -1
- package/dist/{utils-CRFUUfNn.mjs → utils-CZNaOZR7.mjs} +4 -3
- package/dist/utils-CZNaOZR7.mjs.map +1 -0
- package/dist/v-D5Z06FKN.mjs +2 -0
- package/dist/v-D5Z06FKN.mjs.map +1 -0
- package/dist/validation-Dk9Q_-C7.mjs +2 -0
- package/dist/validation-Dk9Q_-C7.mjs.map +1 -0
- package/dist/validation-PF9-_nKd.mjs +2 -0
- package/dist/{validation-tgjL_9n8.mjs.map → validation-PF9-_nKd.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-X9-bwtRo.mjs +2 -0
- package/dist/{validator-DMlEScV3.mjs.map → validator-X9-bwtRo.mjs.map} +1 -1
- package/dist/value-guards-CK9guf2Z.mjs +2 -0
- package/dist/value-guards-CK9guf2Z.mjs.map +1 -0
- package/dist/version-JDaZht4U.mjs +2 -0
- package/dist/{version-De1l_ZMF.mjs.map → version-JDaZht4U.mjs.map} +1 -1
- package/package.json +75 -33
- package/dist/base-vfur-DaU.mjs +0 -2
- package/dist/base-vfur-DaU.mjs.map +0 -1
- package/dist/batch-refs-Op1fx9Bo.mjs +0 -6
- package/dist/batch-refs-Op1fx9Bo.mjs.map +0 -1
- package/dist/bind-parameter-capacity-DzMcIB95.mjs +0 -2
- package/dist/builder-DkWfNHEV.mjs +0 -2
- package/dist/builder-DkWfNHEV.mjs.map +0 -1
- package/dist/chain-uIFlkkXS.mjs +0 -2
- package/dist/chain-uIFlkkXS.mjs.map +0 -1
- package/dist/client-C8gXvWIA.mjs +0 -2
- package/dist/client-C8gXvWIA.mjs.map +0 -1
- package/dist/client-z9mcpRtA.mjs +0 -435
- package/dist/client-z9mcpRtA.mjs.map +0 -1
- package/dist/controls-BhxRnPYS.mjs +0 -2
- package/dist/controls-BhxRnPYS.mjs.map +0 -1
- package/dist/datetime-physical-codec-BK93pJGW.mjs +0 -2
- package/dist/driver-CHclfK3q.mjs +0 -2
- package/dist/driver-CHclfK3q.mjs.map +0 -1
- package/dist/driver-ZIbkciaz.mjs +0 -2
- package/dist/driver-options-DVxWlZ0s.mjs +0 -2
- package/dist/driver-options-DVxWlZ0s.mjs.map +0 -1
- package/dist/error-mapping-LKqxnw-b.mjs +0 -2
- package/dist/error-mapping-LKqxnw-b.mjs.map +0 -1
- package/dist/fs-estate-3Bu_K9mk.d.mts +0 -7
- package/dist/fs-estate-BLqNdigQ.mjs +0 -2
- package/dist/fs-estate-BLqNdigQ.mjs.map +0 -1
- package/dist/geo-point-codec-DUTTtlav.mjs +0 -2
- package/dist/geo-point-codec-DUTTtlav.mjs.map +0 -1
- package/dist/key-DKaqPb8w.mjs +0 -2
- package/dist/key-DKaqPb8w.mjs.map +0 -1
- package/dist/migrations-BWZSBMZh.mjs.map +0 -1
- package/dist/mysql-adapter-DtZdwqzc.mjs +0 -2
- package/dist/mysql-adapter-DtZdwqzc.mjs.map +0 -1
- package/dist/observation-CLp8ylmL.mjs +0 -2
- package/dist/observation-CLp8ylmL.mjs.map +0 -1
- package/dist/physical-BkelResN.mjs +0 -2
- package/dist/pinned-session-CNANv7bv.mjs +0 -2
- package/dist/pinned-session-CNANv7bv.mjs.map +0 -1
- package/dist/postgres-adapter-ButxrmEa.mjs +0 -2
- package/dist/postgres-adapter-ButxrmEa.mjs.map +0 -1
- package/dist/registration-preflight-BrA3EWvq.mjs +0 -4
- package/dist/registration-preflight-BrA3EWvq.mjs.map +0 -1
- package/dist/result-shape-CKLOBSKl.mjs +0 -2
- package/dist/result-shape-CKLOBSKl.mjs.map +0 -1
- package/dist/scalar-BTktMqvO.mjs +0 -2
- package/dist/schema-BFNcMdO6.mjs +0 -2
- package/dist/schema-introspection-C7P7lwIs.mjs +0 -6
- package/dist/schema-introspection-C7P7lwIs.mjs.map +0 -1
- package/dist/select-assembly-BgqlrePH.mjs.map +0 -1
- package/dist/sqlite-adapter-1krz0OXw.mjs +0 -2
- package/dist/sqlite-adapter-1krz0OXw.mjs.map +0 -1
- package/dist/sqlite-utils-D26BFuJJ.mjs +0 -2
- package/dist/sqlite-utils-D26BFuJJ.mjs.map +0 -1
- package/dist/transaction-oskVwmsf.mjs.map +0 -1
- package/dist/transactions-gjmrWN5W.mjs +0 -2
- package/dist/transactions-gjmrWN5W.mjs.map +0 -1
- package/dist/utils-CRFUUfNn.mjs.map +0 -1
- package/dist/v-B2WwtcRz.mjs +0 -2
- package/dist/v-B2WwtcRz.mjs.map +0 -1
- package/dist/validation-Du6j0Q38.mjs +0 -2
- package/dist/validation-Du6j0Q38.mjs.map +0 -1
- package/dist/validation-tgjL_9n8.mjs +0 -2
- package/dist/validator-DMlEScV3.mjs +0 -2
- package/dist/version-De1l_ZMF.mjs +0 -2
- /package/dist/{contract-BHUOUAZ-.d.mts → contract-CIIqgFyb.d.mts} +0 -0
- /package/dist/{sql--yhoVvRM.d.mts → sql-BvfwUKIh.d.mts} +0 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { An as Dialect, Vn as AnyModel } from "./index-C_XLSTy2.mjs";
|
|
2
|
+
import { i as ResolveCallback, t as MigrationClient } from "./planner-C6Lfsasx.mjs";
|
|
3
|
+
import { i as Sha256, n as MigrationStorageWriter, r as PublishResult } from "./contract-CIIqgFyb.mjs";
|
|
4
|
+
import { B as MigrationCheckInput, V as MigrationDecisionV1 } from "./client-CRBo95D0.mjs";
|
|
5
|
+
|
|
6
|
+
//#region src/adapters/databases/sqlite/storage/datetime.d.ts
|
|
7
|
+
|
|
8
|
+
/** A reviewed manual-migration expression; the argument is a physical column name. */
|
|
9
|
+
declare function sqliteCanonicalDateTimeExpression(columnName: string): string;
|
|
10
|
+
/** Canonical millisecond Time storage; malformed source rows abort the statement. */
|
|
11
|
+
declare function sqliteCanonicalTimeExpression(columnName: string): string;
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/migrations/identifier-conversion.d.ts
|
|
14
|
+
|
|
15
|
+
/** The key whose text column is being converted, and the schema it lives in. */
|
|
16
|
+
interface IdentifierConversionRequest {
|
|
17
|
+
/**
|
|
18
|
+
* The WHOLE schema, not just the model: a foreign key's domain is derived
|
|
19
|
+
* from the resolved topology, and so is the list of columns that reference
|
|
20
|
+
* this key. Resolved here, exactly as `serializeModels` resolves it.
|
|
21
|
+
*/
|
|
22
|
+
readonly schema: Record<string, AnyModel>;
|
|
23
|
+
readonly model: AnyModel;
|
|
24
|
+
readonly field: string;
|
|
25
|
+
readonly dialect: Dialect;
|
|
26
|
+
/** PostgreSQL's target namespace, when the estate is bound to one. */
|
|
27
|
+
readonly namespace?: string | undefined;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The pre-checks for converting one key's text column into its identifier
|
|
31
|
+
* column, in the order a conversion needs them.
|
|
32
|
+
*
|
|
33
|
+
* Refuses a field with no compactly stored identifier domain rather than
|
|
34
|
+
* answering with an empty list: an empty list reads as "this estate is ready",
|
|
35
|
+
* and that is the one answer a caller who named the wrong field must not get.
|
|
36
|
+
*/
|
|
37
|
+
declare function identifierConversionChecks(request: IdentifierConversionRequest): readonly MigrationCheckInput[];
|
|
38
|
+
//#endregion
|
|
39
|
+
//#region src/migrations/resolver.d.ts
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Intent as data (plan T2): a resolve callback built from plain JSON
|
|
43
|
+
* decisions, so an API can carry them. It answers each change one decision
|
|
44
|
+
* names and leaves every other change unanswered, which refuses it. An entry
|
|
45
|
+
* that is not a decision is refused here (V4002); `generate` refuses (V4002)
|
|
46
|
+
* a decision that answered no change of its plan, such as one naming a table
|
|
47
|
+
* or column the plan does not touch. It serves one request: build one per
|
|
48
|
+
* `generate`.
|
|
49
|
+
*/
|
|
50
|
+
declare function createPredefinedResolver(decisions: readonly MigrationDecisionV1[]): ResolveCallback;
|
|
51
|
+
/**
|
|
52
|
+
* Rejects all changes requiring resolution.
|
|
53
|
+
* Useful for CI/CD pipelines where human intervention is not possible.
|
|
54
|
+
*/
|
|
55
|
+
declare const rejectAllResolver: ResolveCallback;
|
|
56
|
+
/**
|
|
57
|
+
* Accepts destructive changes, treats ambiguous column changes as renames,
|
|
58
|
+
* and maps enum value removals to NULL.
|
|
59
|
+
* A table pair stays undecided, so the plan refuses: the dropped side may be
|
|
60
|
+
* another application's table, and only a callback naming the pair may
|
|
61
|
+
* rename it.
|
|
62
|
+
*/
|
|
63
|
+
declare const lenientResolver: ResolveCallback;
|
|
64
|
+
/**
|
|
65
|
+
* Accepts destructive changes, treats ambiguous changes as add+drop,
|
|
66
|
+
* and maps enum value removals to NULL.
|
|
67
|
+
* Useful when you don't care about preserving data in ambiguous scenarios.
|
|
68
|
+
*/
|
|
69
|
+
declare const addDropResolver: ResolveCallback;
|
|
70
|
+
//#endregion
|
|
71
|
+
//#region src/migrations/sqlite-storage-audit.d.ts
|
|
72
|
+
/** One audited column; `null` counts and declarations mean the column is missing. */
|
|
73
|
+
type StorageColumnAudit = {
|
|
74
|
+
readonly table: string;
|
|
75
|
+
readonly column: string;
|
|
76
|
+
} & ({
|
|
77
|
+
readonly type: "datetime" | "time";
|
|
78
|
+
readonly list: boolean;
|
|
79
|
+
readonly noncanonical: number | null;
|
|
80
|
+
} | {
|
|
81
|
+
readonly type: "decimal";
|
|
82
|
+
/** The catalog's declared type. */
|
|
83
|
+
readonly declared: string | null;
|
|
84
|
+
readonly checked: boolean;
|
|
85
|
+
});
|
|
86
|
+
/**
|
|
87
|
+
* Audit the SQLite storage of `client`'s models: one catalog read per table
|
|
88
|
+
* decides which audited columns exist; each existing text DateTime/Time
|
|
89
|
+
* column's noncanonical rows are counted (one scan each), and each decimal
|
|
90
|
+
* column is checked against the scaled-integer storage of its descriptor.
|
|
91
|
+
* Other dialects store native types and return no audit.
|
|
92
|
+
*/
|
|
93
|
+
declare function auditStorage(client: Pick<MigrationClient, "$driver" | "$schema">): Promise<StorageColumnAudit[]>;
|
|
94
|
+
//#endregion
|
|
95
|
+
//#region src/migrations/storage/conformance.d.ts
|
|
96
|
+
declare function createStorageConformanceSuite(createWriter: () => MigrationStorageWriter): {
|
|
97
|
+
readonly name: string;
|
|
98
|
+
readonly run: () => Promise<void>;
|
|
99
|
+
}[];
|
|
100
|
+
//#endregion
|
|
101
|
+
//#region src/migrations/storage/memory.d.ts
|
|
102
|
+
declare class MemoryEstateStorage implements MigrationStorageWriter {
|
|
103
|
+
private estate;
|
|
104
|
+
private readonly states;
|
|
105
|
+
private readonly snapshots;
|
|
106
|
+
private readonly sql;
|
|
107
|
+
readEstate(): Promise<Uint8Array | null>;
|
|
108
|
+
listStates(): Promise<readonly Sha256[]>;
|
|
109
|
+
listSnapshots(): Promise<readonly Sha256[]>;
|
|
110
|
+
listSql(): Promise<readonly Sha256[]>;
|
|
111
|
+
readState(id: Sha256): Promise<Uint8Array | null>;
|
|
112
|
+
readSnapshot(hash: Sha256): Promise<Uint8Array | null>;
|
|
113
|
+
readSql(hash: Sha256): Promise<Uint8Array | null>;
|
|
114
|
+
publishEstate(bytes: Uint8Array): Promise<PublishResult>;
|
|
115
|
+
publishSnapshot(hash: Sha256, bytes: Uint8Array): Promise<PublishResult>;
|
|
116
|
+
publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult>;
|
|
117
|
+
publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult>;
|
|
118
|
+
}
|
|
119
|
+
//#endregion
|
|
120
|
+
//#region src/migrations/storage/object-store.d.ts
|
|
121
|
+
declare function refuseWorkersKvWritable(): never;
|
|
122
|
+
interface ObjectStoreConditionalPut {
|
|
123
|
+
putIfAbsent(key: string, bytes: Uint8Array): Promise<"created" | "exists">;
|
|
124
|
+
get(key: string): Promise<Uint8Array | null>;
|
|
125
|
+
list(prefix: string): Promise<readonly string[]>;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Estate writer over a strongly consistent object store with if-none-match
|
|
129
|
+
* publication. Manifests become visible only after referenced bytes exist.
|
|
130
|
+
*/
|
|
131
|
+
declare class ObjectStoreEstateStorage implements MigrationStorageWriter {
|
|
132
|
+
private readonly store;
|
|
133
|
+
constructor(store: ObjectStoreConditionalPut);
|
|
134
|
+
readEstate(): Promise<Uint8Array | null>;
|
|
135
|
+
listStates(): Promise<readonly Sha256[]>;
|
|
136
|
+
listSnapshots(): Promise<readonly Sha256[]>;
|
|
137
|
+
listSql(): Promise<readonly Sha256[]>;
|
|
138
|
+
readState(id: Sha256): Promise<Uint8Array | null>;
|
|
139
|
+
readSnapshot(hash: Sha256): Promise<Uint8Array | null>;
|
|
140
|
+
readSql(hash: Sha256): Promise<Uint8Array | null>;
|
|
141
|
+
publishEstate(bytes: Uint8Array): Promise<PublishResult>;
|
|
142
|
+
publishSnapshot(hash: Sha256, bytes: Uint8Array): Promise<PublishResult>;
|
|
143
|
+
publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult>;
|
|
144
|
+
publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult>;
|
|
145
|
+
private publish;
|
|
146
|
+
private listHex;
|
|
147
|
+
}
|
|
148
|
+
/** In-memory strong object store for the conformance fixture. */
|
|
149
|
+
declare class MemoryConditionalObjectStore implements ObjectStoreConditionalPut {
|
|
150
|
+
private readonly objects;
|
|
151
|
+
putIfAbsent(key: string, bytes: Uint8Array): Promise<"created" | "exists">;
|
|
152
|
+
get(key: string): Promise<Uint8Array | null>;
|
|
153
|
+
list(prefix: string): Promise<readonly string[]>;
|
|
154
|
+
}
|
|
155
|
+
//#endregion
|
|
156
|
+
export { MemoryEstateStorage as a, auditStorage as c, lenientResolver as d, rejectAllResolver as f, sqliteCanonicalTimeExpression as g, sqliteCanonicalDateTimeExpression as h, refuseWorkersKvWritable as i, addDropResolver as l, identifierConversionChecks as m, ObjectStoreConditionalPut as n, createStorageConformanceSuite as o, IdentifierConversionRequest as p, ObjectStoreEstateStorage as r, StorageColumnAudit as s, MemoryConditionalObjectStore as t, createPredefinedResolver as u };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./value-guards-CK9guf2Z.mjs";import{S as n,g as r}from"./base-AdXAoy6l.mjs";const i=new WeakMap,a=new WeakMap,o=new WeakMap,settleObserverReturn=()=>void 0;function getOfficialInstrumentationChainCapability(e){return e===void 0?void 0:o.get(e)}function registerOfficialInstrumentationChain(e,t){o.set(e,t)}function registerTrustedProtectedObserver(e,t,n){i.set(e,{capability:t,observer:n})}function getTrustedProtectedObserverCapability(e){return t(e)?i.get(e)?.capability:void 0}function selectTrustedObservers(e){let t=e?.find(({handler:e})=>i.has(e));return t===void 0?void 0:[t]}function prewarmProtectedObservers(e){if(!(e===void 0||e.length===0))for(let t of e){let e=i.get(t.handler);if(e===void 0)continue;let n=prewarmTrustedObserver(e.capability);if(n!==void 0)return n}}function readProtectedLifecycleFacts(e){return a.get(e)?.facts}function readProtectedLifecycleCompletionFacts(e){return a.get(e)?.completion}function runProtectedObservers(e,t,n,r,o){if(t===void 0||t.length===0)return n();let s=Date.now(),c=freezeLifecycleUnit(e),l=-1,u;for(let[e,n]of t.entries()){let t=i.get(n.handler);if(t!==void 0){l=e,u=t;break}}let d,f,p,m=u===void 0?void 0:new Promise(e=>{p=e}),h,g=u===void 0,_,v=!1,resolveOuterWhenReady=()=>{g&&h!==void 0&&p?.(h)},settleCompletion=(e,t)=>{let n=Math.max(0,Date.now()-s),i;try{i=r?.()?.commitCertainty}catch{i=void 0}let o=createCompletion(e,n,i,t);h=o;let l=a.get(c);if(l!==void 0)try{l.completion=l.facts.complete({status:e,durationMs:n,...e===`failure`?{failure:t}:{}})}catch{l.completion=void 0}d?.(o),resolveOuterWhenReady()},observeApplicationCompletion=()=>{v||f===void 0||_===void 0||(v=!0,_.then(()=>settleCompletion(`success`),e=>settleCompletion(`failure`,e)))},readCompletionPromise=()=>(f===void 0&&(f=new Promise(e=>{d=e})),observeApplicationCompletion(),f),startChild=()=>{let e;try{e=n()}catch(t){e=Promise.reject(t)}return _=e,observeApplicationCompletion(),e},startObserver=e=>{let n=t[e];if(n===void 0)return startChild();let r=i.get(n.handler);if(r!==void 0){if(o!==void 0)try{let e=o();e!==void 0&&a.set(c,{facts:e})}catch{}let t,n,i=new Promise((e,r)=>{t=e,n=r}),s=!1,startNext=()=>(s||(s=!0,startObserver(e+1).then(e=>t(e),e=>n(e))),readCompletionPromise()),l;try{l=r.observer(c,startNext)}catch{return startNext(),g=!0,resolveOuterWhenReady(),i}return Promise.resolve(l).then(()=>{s||startNext(),g=!0,resolveOuterWhenReady()},()=>{s||startNext(),g=!0,resolveOuterWhenReady()}),i}let s,startNextApplication=()=>(s===void 0&&(s=startObserver(e+1)),s),proceed=()=>(startNextApplication(),m!==void 0&&e<l?m:readCompletionPromise()),u;try{u=Reflect.apply(n.handler,void 0,[c,proceed])}catch{u=void 0}let d=startNextApplication();return consumeObserverReturn(u),d},y=o===void 0||u===void 0?void 0:prewarmTrustedObserver(u.capability);if(y===void 0)return startObserver(0);let b,x,S=new Promise((e,t)=>{b=e,x=t}),startAfterPrewarm=()=>{startObserver(0).then(e=>b(e),e=>x(e))};return y.then(startAfterPrewarm),S}function observeOperation(e,t,n,r,i,a){return runProtectedObservers({kind:`operation`,operation:t,...n===void 0?{}:{model:n}},e,r,i,a)}function observeStatement(e,t,n,r,i,a){return runProtectedObservers({kind:`statement`,...t===void 0?{}:{operation:t},...n===void 0||n===`$raw`?{}:{model:n}},e,r,i,a)}function observeDriverLifecycle(e,t,n,r,i,a){return runProtectedObservers({kind:e,...n===void 0?{}:{operation:n}},t,r,i,a)}function prewarmTrustedObserver(e){let t=e.prewarm;if(t===void 0)return;let n;try{n=t()}catch{return}if(n!==void 0)return Promise.resolve(n).then(()=>void 0,()=>void 0)}function freezeLifecycleUnit(e){return Object.freeze(e)}function consumeObserverReturn(e){if(!(e===null||typeof e!=`object`&&typeof e!=`function`))try{let n=Reflect.get(e,`then`);if(!t(n))return;Reflect.apply(n,e,[settleObserverReturn,settleObserverReturn])}catch{}}function createCompletion(e,t,n,r){let i=e===`failure`?summarizeFailure(r):void 0;return Object.freeze({status:e,durationMs:t,...i===void 0?{}:{error:i},...n===void 0?{}:{commitCertainty:n}})}function summarizeFailure(e){let t=r(n(e)?e:Error(`Application rejected with a non-Error value`)),i=Object.getOwnPropertyDescriptor(t,`code`)?.value;return Object.freeze({name:t.name,message:t.message,...typeof i==`string`?{code:i}:{}})}export{observeStatement as a,readProtectedLifecycleFacts as c,runProtectedObservers as d,selectTrustedObservers as f,observeOperation as i,registerOfficialInstrumentationChain as l,getTrustedProtectedObserverCapability as n,prewarmProtectedObservers as o,observeDriverLifecycle as r,readProtectedLifecycleCompletionFacts as s,getOfficialInstrumentationChainCapability as t,registerTrustedProtectedObserver as u};
|
|
2
|
+
//# sourceMappingURL=observation-DUSm7oXK.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"observation-DUSm7oXK.mjs","names":["resolveApplication","rejectApplication","applicationBridge"],"sources":["../src/extensions/observation.ts"],"sourcesContent":["import { sanitizeErrorForLogging } from \"@errors\";\nimport { isFunction } from \"@validation/value-guards\";\nimport { isError } from \"../errors/diagnostic-safety\";\nimport type { ResolvedExtensionChain, ResolvedExtensionHandler } from \"./chain\";\nimport type {\n OfficialLifecycleCompletionFacts,\n OfficialLifecycleFacts,\n OfficialLifecycleFactsReader,\n OfficialObservationCapability,\n} from \"./official-facts\";\n\n/** The exact public facts carried by each protected lifecycle boundary. */\nexport type LifecycleUnit =\n | Readonly<{\n kind: \"operation\";\n operation: string;\n model?: string;\n }>\n | Readonly<{\n kind: \"statement\";\n operation?: string;\n model?: string;\n }>\n | Readonly<{\n kind: \"batch\";\n operation: string;\n }>\n | Readonly<{\n kind: \"transaction\";\n operation?: string;\n }>\n | Readonly<{\n kind: \"savepoint\";\n operation?: string;\n }>\n | Readonly<{\n kind: \"connection\";\n operation?: string;\n }>\n | Readonly<{\n kind: \"cache\";\n operation: \"get\" | \"set\" | \"revalidate\" | \"invalidate\";\n }>;\n\nexport type LifecycleUnitKind = LifecycleUnit[\"kind\"];\n\nexport type CommitCertainty = \"committed\" | \"may-have-committed\";\n\nexport interface ObservationErrorSummary {\n readonly name: string;\n readonly message: string;\n readonly code?: string;\n}\n\nexport interface ObservationCompletion {\n readonly status: \"success\" | \"failure\";\n readonly durationMs: number;\n readonly error?: ObservationErrorSummary;\n readonly commitCertainty?: CommitCertainty;\n}\n\nexport interface ObservationCompletionFacts {\n readonly commitCertainty?: CommitCertainty;\n}\n\nexport type ObservationCompletionFactsReader = () =>\n | ObservationCompletionFacts\n | undefined;\n\nexport type ObservationUnit = LifecycleUnit;\n\nexport type ObserveHandler = (\n unit: ObservationUnit,\n proceed: () => Promise<ObservationCompletion>\n) => unknown;\n\ntype TrustedProtectedObserver = (\n unit: LifecycleUnit,\n proceed: () => Promise<ObservationCompletion>\n) => unknown;\n\ninterface TrustedProtectedObserverRegistration {\n readonly capability: OfficialObservationCapability;\n readonly observer: TrustedProtectedObserver;\n}\n\ninterface ProtectedLifecycleFactsState {\n readonly facts: OfficialLifecycleFacts;\n completion?: OfficialLifecycleCompletionFacts;\n}\n\nconst trustedObservers = new WeakMap<\n CallableFunction,\n TrustedProtectedObserverRegistration\n>();\nconst lifecycleFacts = new WeakMap<\n LifecycleUnit,\n ProtectedLifecycleFactsState\n>();\nconst officialCapabilitiesByChain = new WeakMap<\n ResolvedExtensionChain,\n OfficialObservationCapability\n>();\nconst settleObserverReturn = (): undefined => undefined;\n\n/** The one official capability registered for this exact chain, if any. */\nexport function getOfficialInstrumentationChainCapability(\n chain: ResolvedExtensionChain | undefined\n): OfficialObservationCapability | undefined {\n return chain === undefined\n ? undefined\n : officialCapabilitiesByChain.get(chain);\n}\n\n/** Bind the admitted official capability to one exact resolved chain. */\nexport function registerOfficialInstrumentationChain(\n chain: ResolvedExtensionChain,\n capability: OfficialObservationCapability\n): void {\n officialCapabilitiesByChain.set(chain, capability);\n}\n\n/** Register one package-owned observer identity without publishing a marker. */\nexport function registerTrustedProtectedObserver(\n handler: CallableFunction,\n capability: OfficialObservationCapability,\n observer: TrustedProtectedObserver\n): void {\n trustedObservers.set(handler, { capability, observer });\n}\n\n/** Recognize the exact package-owned handler identity and nothing else. */\nexport function getTrustedProtectedObserverCapability(\n handler: unknown\n): OfficialObservationCapability | undefined {\n return isFunction(handler)\n ? trustedObservers.get(handler)?.capability\n : undefined;\n}\n\n/**\n * The exact chain's one trusted observer, alone, or `undefined`. Dispatch\n * through it reaches no ordinary observer: cache backend delete/clear, which\n * have no public unit, run through the one runner this way.\n */\nexport function selectTrustedObservers(\n observers: readonly ResolvedExtensionHandler[] | undefined\n): readonly ResolvedExtensionHandler[] | undefined {\n const trusted = observers?.find(({ handler }) =>\n trustedObservers.has(handler)\n );\n return trusted === undefined ? undefined : [trusted];\n}\n\n/** Resolve the one trusted readiness once before a coordinated array starts. */\nexport function prewarmProtectedObservers(\n observers: readonly ResolvedExtensionHandler[] | undefined\n): void | Promise<void> {\n if (observers === undefined || observers.length === 0) return;\n for (const observer of observers) {\n const registration = trustedObservers.get(observer.handler);\n if (registration === undefined) continue;\n const readiness = prewarmTrustedObserver(registration.capability);\n if (readiness !== undefined) return readiness;\n }\n}\n\n/** Read facts only for the exact frozen unit created by this runner. */\nexport function readProtectedLifecycleFacts(\n unit: LifecycleUnit\n): OfficialLifecycleFacts | undefined {\n return lifecycleFacts.get(unit)?.facts;\n}\n\n/** Read completion facts projected by core after the child settled. */\nexport function readProtectedLifecycleCompletionFacts(\n unit: LifecycleUnit\n): OfficialLifecycleCompletionFacts | undefined {\n return lifecycleFacts.get(unit)?.completion;\n}\n\n/**\n * Runs completion-only observers without giving their onion authority over the\n * application promise.\n */\nexport function runProtectedObservers<Result>(\n unit: LifecycleUnit,\n observers: readonly ResolvedExtensionHandler[] | undefined,\n child: () => Promise<Result>,\n readCompletionFacts?: ObservationCompletionFactsReader,\n readInstrumentationFacts?: OfficialLifecycleFactsReader\n): Promise<Result> {\n if (observers === undefined || observers.length === 0) return child();\n\n const startedAt = Date.now();\n const immutableUnit = freezeLifecycleUnit(unit);\n let trustedIndex = -1;\n let trustedRegistration: TrustedProtectedObserverRegistration | undefined;\n for (const [index, observer] of observers.entries()) {\n const registration = trustedObservers.get(observer.handler);\n if (registration !== undefined) {\n trustedIndex = index;\n trustedRegistration = registration;\n break;\n }\n }\n let resolveCompletion:\n | ((completion: ObservationCompletion) => void)\n | undefined;\n let completionPromise: Promise<ObservationCompletion> | undefined;\n let resolveOuterCompletion:\n | ((completion: ObservationCompletion) => void)\n | undefined;\n const outerCompletionPromise =\n trustedRegistration === undefined\n ? undefined\n : new Promise<ObservationCompletion>((resolve) => {\n resolveOuterCompletion = resolve;\n });\n let settledCompletion: ObservationCompletion | undefined;\n let trustedSetupSettled = trustedRegistration === undefined;\n let applicationPromise: Promise<Result> | undefined;\n let observesApplicationCompletion = false;\n\n const resolveOuterWhenReady = (): void => {\n if (trustedSetupSettled && settledCompletion !== undefined) {\n resolveOuterCompletion?.(settledCompletion);\n }\n };\n\n const settleCompletion = (\n status: ObservationCompletion[\"status\"],\n failure?: unknown\n ): void => {\n const durationMs = Math.max(0, Date.now() - startedAt);\n let commitCertainty: CommitCertainty | undefined;\n try {\n commitCertainty = readCompletionFacts?.()?.commitCertainty;\n } catch {\n commitCertainty = undefined;\n }\n const completion = createCompletion(\n status,\n durationMs,\n commitCertainty,\n failure\n );\n settledCompletion = completion;\n const factsState = lifecycleFacts.get(immutableUnit);\n if (factsState !== undefined) {\n try {\n factsState.completion = factsState.facts.complete({\n status,\n durationMs,\n ...(status === \"failure\" ? { failure } : {}),\n });\n } catch {\n factsState.completion = undefined;\n }\n }\n resolveCompletion?.(completion);\n resolveOuterWhenReady();\n };\n\n const observeApplicationCompletion = (): void => {\n if (\n observesApplicationCompletion ||\n completionPromise === undefined ||\n applicationPromise === undefined\n ) {\n return;\n }\n observesApplicationCompletion = true;\n applicationPromise.then(\n () => settleCompletion(\"success\"),\n (failure: unknown) => settleCompletion(\"failure\", failure)\n );\n };\n\n const readCompletionPromise = (): Promise<ObservationCompletion> => {\n if (completionPromise === undefined) {\n completionPromise = new Promise<ObservationCompletion>((resolve) => {\n resolveCompletion = resolve;\n });\n }\n observeApplicationCompletion();\n return completionPromise;\n };\n\n const startChild = (): Promise<Result> => {\n let started: Promise<Result>;\n try {\n started = child();\n } catch (failure) {\n started = Promise.reject(failure);\n }\n applicationPromise = started;\n observeApplicationCompletion();\n return started;\n };\n\n const startObserver = (index: number): Promise<Result> => {\n const observer = observers[index];\n if (observer === undefined) return startChild();\n\n const trustedObserver = trustedObservers.get(observer.handler);\n if (trustedObserver !== undefined) {\n if (readInstrumentationFacts !== undefined) {\n try {\n const facts = readInstrumentationFacts();\n if (facts !== undefined) lifecycleFacts.set(immutableUnit, { facts });\n } catch {\n // Instrumentation fact production cannot stop the application.\n }\n }\n // Promise executors run synchronously; TypeScript does not model that guarantee.\n let resolveApplication!: (value: Result | PromiseLike<Result>) => void;\n let rejectApplication!: (reason?: unknown) => void;\n const applicationBridge = new Promise<Result>((resolve, reject) => {\n resolveApplication = resolve;\n rejectApplication = reject;\n });\n let proceeded = false;\n const startNext = (): Promise<ObservationCompletion> => {\n if (!proceeded) {\n proceeded = true;\n startObserver(index + 1).then(\n (value) => resolveApplication(value),\n (failure: unknown) => rejectApplication(failure)\n );\n }\n return readCompletionPromise();\n };\n let setup: unknown;\n try {\n setup = trustedObserver.observer(immutableUnit, startNext);\n } catch {\n startNext();\n trustedSetupSettled = true;\n resolveOuterWhenReady();\n return applicationBridge;\n }\n Promise.resolve(setup).then(\n () => {\n if (!proceeded) startNext();\n trustedSetupSettled = true;\n resolveOuterWhenReady();\n },\n () => {\n if (!proceeded) startNext();\n trustedSetupSettled = true;\n resolveOuterWhenReady();\n }\n );\n return applicationBridge;\n }\n\n let nextApplicationPromise: Promise<Result> | undefined;\n const startNextApplication = (): Promise<Result> => {\n if (nextApplicationPromise === undefined) {\n nextApplicationPromise = startObserver(index + 1);\n }\n return nextApplicationPromise;\n };\n const proceed = (): Promise<ObservationCompletion> => {\n startNextApplication();\n return outerCompletionPromise !== undefined && index < trustedIndex\n ? outerCompletionPromise\n : readCompletionPromise();\n };\n\n let returned: unknown;\n try {\n returned = Reflect.apply(observer.handler, undefined, [\n immutableUnit,\n proceed,\n ]);\n } catch {\n returned = undefined;\n }\n const nextApplication = startNextApplication();\n consumeObserverReturn(returned);\n return nextApplication;\n };\n\n const readiness =\n readInstrumentationFacts === undefined || trustedRegistration === undefined\n ? undefined\n : prewarmTrustedObserver(trustedRegistration.capability);\n if (readiness === undefined) return startObserver(0);\n\n // Promise executors run synchronously; TypeScript does not model that guarantee.\n let resolveApplication!: (value: Result | PromiseLike<Result>) => void;\n let rejectApplication!: (reason?: unknown) => void;\n const applicationBridge = new Promise<Result>((resolve, reject) => {\n resolveApplication = resolve;\n rejectApplication = reject;\n });\n const startAfterPrewarm = (): void => {\n startObserver(0).then(\n (value) => resolveApplication(value),\n (failure: unknown) => rejectApplication(failure)\n );\n };\n readiness.then(startAfterPrewarm);\n return applicationBridge;\n}\n\n/** Observe one logical operation without duplicating its completion protocol. */\nexport function observeOperation<Result>(\n observers: readonly ResolvedExtensionHandler[],\n operation: string,\n model: string | undefined,\n child: () => Promise<Result>,\n readCompletionFacts?: ObservationCompletionFactsReader,\n readInstrumentationFacts?: OfficialLifecycleFactsReader\n): Promise<Result> {\n return runProtectedObservers(\n {\n kind: \"operation\",\n operation,\n ...(model === undefined ? {} : { model }),\n },\n observers,\n child,\n readCompletionFacts,\n readInstrumentationFacts\n );\n}\n\n/** Observe one driver-owned physical statement boundary. */\nexport function observeStatement<Result>(\n observers: readonly ResolvedExtensionHandler[],\n operation: string | undefined,\n model: string | undefined,\n child: () => Promise<Result>,\n readCompletionFacts?: ObservationCompletionFactsReader,\n readInstrumentationFacts?: OfficialLifecycleFactsReader\n): Promise<Result> {\n return runProtectedObservers(\n {\n kind: \"statement\",\n ...(operation === undefined ? {} : { operation }),\n ...(model === undefined || model === \"$raw\" ? {} : { model }),\n },\n observers,\n child,\n readCompletionFacts,\n readInstrumentationFacts\n );\n}\n\n/** Observe one driver-owned connection, transaction, or savepoint boundary. */\nexport function observeDriverLifecycle<Result>(\n kind: Extract<LifecycleUnitKind, \"connection\" | \"savepoint\" | \"transaction\">,\n observers: readonly ResolvedExtensionHandler[],\n operation: string | undefined,\n child: () => Promise<Result>,\n readCompletionFacts?: ObservationCompletionFactsReader,\n readInstrumentationFacts?: OfficialLifecycleFactsReader\n): Promise<Result> {\n return runProtectedObservers(\n {\n kind,\n ...(operation === undefined ? {} : { operation }),\n },\n observers,\n child,\n readCompletionFacts,\n readInstrumentationFacts\n );\n}\n\nfunction prewarmTrustedObserver(\n capability: OfficialObservationCapability\n): void | Promise<void> {\n const prewarm = capability.prewarm;\n if (prewarm === undefined) return;\n let readiness: void | Promise<void>;\n try {\n readiness = prewarm();\n } catch {\n return;\n }\n if (readiness === undefined) return;\n return Promise.resolve(readiness).then(\n () => undefined,\n () => undefined\n );\n}\n\nfunction freezeLifecycleUnit(unit: LifecycleUnit): LifecycleUnit {\n return Object.freeze(unit);\n}\n\nfunction consumeObserverReturn(returned: unknown): void {\n if (\n returned === null ||\n (typeof returned !== \"object\" && typeof returned !== \"function\")\n ) {\n return;\n }\n try {\n const then = Reflect.get(returned, \"then\");\n if (!isFunction(then)) return;\n Reflect.apply(then, returned, [settleObserverReturn, settleObserverReturn]);\n } catch {\n // Observer returns cannot affect the application.\n }\n}\n\nfunction createCompletion(\n status: ObservationCompletion[\"status\"],\n durationMs: number,\n commitCertainty: CommitCertainty | undefined,\n failure: unknown\n): ObservationCompletion {\n const error = status === \"failure\" ? summarizeFailure(failure) : undefined;\n return Object.freeze({\n status,\n durationMs,\n ...(error === undefined ? {} : { error }),\n ...(commitCertainty === undefined ? {} : { commitCertainty }),\n });\n}\n\nfunction summarizeFailure(failure: unknown): ObservationErrorSummary {\n const normalized = isError(failure)\n ? failure\n : new Error(\"Application rejected with a non-Error value\");\n const sanitized = sanitizeErrorForLogging(normalized);\n const code = Object.getOwnPropertyDescriptor(sanitized, \"code\")?.value;\n return Object.freeze({\n name: sanitized.name,\n message: sanitized.message,\n ...(typeof code === \"string\" ? { code } : {}),\n });\n}\n"],"mappings":"wIA2FA,MAAM,EAAmB,IAAI,QAIvB,EAAiB,IAAI,QAIrB,EAA8B,IAAI,QAIlC,yBAAwC,IAAA,GAG9C,SAAgB,0CACd,EAC2C,CAC3C,OAAO,IAAU,IAAA,GACb,IAAA,GACA,EAA4B,IAAI,EAAM,CAI5C,SAAgB,qCACd,EACA,EACM,CACN,EAA4B,IAAI,EAAO,EAAW,CAIpD,SAAgB,iCACd,EACA,EACA,EACM,CACN,EAAiB,IAAI,EAAS,CAAE,aAAY,WAAU,CAAC,CAIzD,SAAgB,sCACd,EAC2C,CAC3C,OAAO,EAAW,EAAQ,CACtB,EAAiB,IAAI,EAAQ,EAAE,WAC/B,IAAA,GAQN,SAAgB,uBACd,EACiD,CACjD,IAAM,EAAU,GAAW,MAAM,CAAE,aACjC,EAAiB,IAAI,EAAQ,CAC9B,CACD,OAAO,IAAY,IAAA,GAAY,IAAA,GAAY,CAAC,EAAQ,CAItD,SAAgB,0BACd,EACsB,CAClB,SAAc,IAAA,IAAa,EAAU,SAAW,GACpD,IAAK,IAAM,KAAY,EAAW,CAChC,IAAM,EAAe,EAAiB,IAAI,EAAS,QAAQ,CA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AW,QAC3B,GAAI,IAAY,IAAA,GAAW,OAC3B,IAAI,EACJ,GAAI,CACF,EAAY,GAAS,MACf,CACN,OAEE,OAAc,IAAA,GAClB,OAAO,QAAQ,QAAQ,EAAU,CAAC,SAC1B,IAAA,OACA,IAAA,GACP,CAGH,SAAS,oBAAoB,EAAoC,CAC/D,OAAO,OAAO,OAAO,EAAK,CAG5B,SAAS,sBAAsB,EAAyB,CAEpD,SAAa,MACZ,OAAO,GAAa,UAAY,OAAO,GAAa,YAIvD,GAAI,CACF,IAAM,EAAO,QAAQ,IAAI,EAAU,OAAO,CAC1C,GAAI,CAAC,EAAW,EAAK,CAAE,OACvB,QAAQ,MAAM,EAAM,EAAU,CAAC,qBAAsB,qBAAqB,CAAC,MACrE,GAKV,SAAS,iBACP,EACA,EACA,EACA,EACuB,CACvB,IAAM,EAAQ,IAAW,UAAY,iBAAiB,EAAQ,CAAG,IAAA,GACjE,OAAO,OAAO,OAAO,CACnB,SACA,aACA,GAAI,IAAU,IAAA,GAAY,EAAE,CAAG,CAAE,QAAO,CACxC,GAAI,IAAoB,IAAA,GAAY,EAAE,CAAG,CAAE,kBAAiB,CAC7D,CAAC,CAGJ,SAAS,iBAAiB,EAA2C,CAInE,IAAM,EAAY,EAHC,EAAQ,EAAQ,CAC/B,EACI,MAAM,8CAA8C,CACP,CAC/C,EAAO,OAAO,yBAAyB,EAAW,OAAO,EAAE,MACjE,OAAO,OAAO,OAAO,CACnB,KAAM,EAAU,KAChB,QAAS,EAAU,QACnB,GAAI,OAAO,GAAS,SAAW,CAAE,OAAM,CAAG,EAAE,CAC7C,CAAC"}
|
package/dist/pg.d.mts
CHANGED
|
@@ -1,19 +1,42 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as Schema, B as LinkedClientConfig, Dn as TransactionOptionSupport, En as DriverTransactionOptions, Mn as QueryResult, Pt as DriverConfig, Rt as NoExtraDriverConfigKeys, d as MigrationSessionAttestation, jn as QueryExecutionContext, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver, zt as VibORMClient } from "./index-C_XLSTy2.mjs";
|
|
2
2
|
import { Pool, PoolClient, PoolConfig, PoolConfig as PgOptions } from "pg";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/pg/index.d.ts
|
|
5
5
|
|
|
6
|
+
interface PgErrorEvents {
|
|
7
|
+
on(event: "error", listener: (error: Error) => void): unknown;
|
|
8
|
+
off(event: "error", listener: (error: Error) => void): unknown;
|
|
9
|
+
}
|
|
10
|
+
/** The part of a node-postgres `PoolClient` this driver uses. */
|
|
11
|
+
interface PgPoolClient extends Pick<PoolClient, "query" | "release">, PgErrorEvents {}
|
|
12
|
+
/**
|
|
13
|
+
* The part of a node-postgres `Pool` this driver uses, so any pool with that
|
|
14
|
+
* shape is accepted. A Neon WebSocket `Pool` (`@neondatabase/serverless`) is
|
|
15
|
+
* node-postgres's pool over a WebSocket and runs here unchanged, but its
|
|
16
|
+
* bundled copy of the pg declarations lags `@types/pg`: in 8.23 a
|
|
17
|
+
* `PoolClient` is a whole `Client`, and the full `Pool` type refused Neon's.
|
|
18
|
+
*/
|
|
19
|
+
interface PgPool extends Pick<Pool, "query" | "end">, PgErrorEvents {
|
|
20
|
+
connect(): Promise<PgPoolClient>;
|
|
21
|
+
}
|
|
6
22
|
interface PgDriverOptions {
|
|
7
|
-
pool?:
|
|
23
|
+
pool?: PgPool;
|
|
8
24
|
options?: PoolConfig;
|
|
9
25
|
pgvector?: boolean;
|
|
10
26
|
postgis?: boolean;
|
|
11
27
|
databaseUrl?: string;
|
|
12
28
|
/** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */
|
|
13
29
|
namespace?: string;
|
|
30
|
+
/**
|
|
31
|
+
* Your claim, at your risk, that every connection this pool opens is one
|
|
32
|
+
* server session for its whole life. It lifts migrations' refusal of
|
|
33
|
+
* Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never
|
|
34
|
+
* need it.
|
|
35
|
+
*/
|
|
36
|
+
migrationSessionAttestation?: MigrationSessionAttestation;
|
|
14
37
|
}
|
|
15
38
|
type PgClientConfig<C extends DriverConfig> = PgDriverOptions & C;
|
|
16
|
-
declare class PgDriver extends Driver<
|
|
39
|
+
declare class PgDriver extends Driver<PgPool, PgPoolClient> {
|
|
17
40
|
readonly adapter: DatabaseAdapter;
|
|
18
41
|
readonly maxBindParametersPerStatement: number | undefined;
|
|
19
42
|
/**
|
|
@@ -29,11 +52,10 @@ declare class PgDriver extends Driver<Pool, PoolClient> {
|
|
|
29
52
|
*
|
|
30
53
|
* A copy of THIS record, not of what it points at: a nested `ssl` object or
|
|
31
54
|
* stream is the caller's to own, and the keys that decide where a pool
|
|
32
|
-
* connects — host, port, user, database, connectionString — all live here
|
|
55
|
+
* connects — host, port, user, database, connectionString — all live here,
|
|
56
|
+
* with the caller's `databaseUrl` merged in (see `connectionRecord`).
|
|
33
57
|
*/
|
|
34
58
|
private readonly connectionOptions;
|
|
35
|
-
/** The caller's `databaseUrl`, read once, for the same reason. */
|
|
36
|
-
private readonly connectionString;
|
|
37
59
|
/**
|
|
38
60
|
* The listener and latest idle failure for each pool this driver created.
|
|
39
61
|
*
|
|
@@ -44,6 +66,8 @@ declare class PgDriver extends Driver<Pool, PoolClient> {
|
|
|
44
66
|
*/
|
|
45
67
|
private readonly ownedPoolErrors;
|
|
46
68
|
constructor(options?: PgDriverOptions);
|
|
69
|
+
/** Every host or URL this driver's pool connects through, for migration admission. */
|
|
70
|
+
protected migrationSessionEndpoints(): readonly unknown[];
|
|
47
71
|
/**
|
|
48
72
|
* The pool this driver connects through.
|
|
49
73
|
*
|
|
@@ -59,7 +83,7 @@ declare class PgDriver extends Driver<Pool, PoolClient> {
|
|
|
59
83
|
* for a caller who never asked it to — and for the other consumers of a pool
|
|
60
84
|
* two estates share. This driver listens only on the pool it made.
|
|
61
85
|
*/
|
|
62
|
-
protected initClient(): Promise<
|
|
86
|
+
protected initClient(): Promise<PgPool>;
|
|
63
87
|
private readBackgroundPoolFailure;
|
|
64
88
|
/** Clear exactly the failure observed before an operation started. */
|
|
65
89
|
private clearBackgroundPoolFailure;
|
|
@@ -92,23 +116,24 @@ declare class PgDriver extends Driver<Pool, PoolClient> {
|
|
|
92
116
|
* caller's record says now: every pool this driver made is ended, and the one
|
|
93
117
|
* it was handed never is.
|
|
94
118
|
*/
|
|
95
|
-
protected closeClient(pool:
|
|
96
|
-
protected execute<T>(client:
|
|
97
|
-
protected executeRaw<T>(client:
|
|
119
|
+
protected closeClient(pool: PgPool): Promise<void>;
|
|
120
|
+
protected execute<T>(client: PgPool | PgPoolClient, sql: string, params: unknown[], context?: QueryExecutionContext): Promise<QueryResult<T>>;
|
|
121
|
+
protected executeRaw<T>(client: PgPool | PgPoolClient, sql: string, params: unknown[] | undefined, context?: QueryExecutionContext): Promise<QueryResult<T>>;
|
|
122
|
+
private executeQuery;
|
|
98
123
|
/**
|
|
99
124
|
* PostgreSQL takes the isolation level as the first statement inside the
|
|
100
125
|
* transaction, and node-postgres hands out a pooled client we can wait for
|
|
101
126
|
* with a bound (and release if we stop waiting).
|
|
102
127
|
*/
|
|
103
128
|
protected transactionOptionSupport(): TransactionOptionSupport;
|
|
104
|
-
protected transaction<T>(client:
|
|
129
|
+
protected transaction<T>(client: PgPool | PgPoolClient, fn: (tx: PgPoolClient) => Promise<T>, context?: QueryExecutionContext, options?: DriverTransactionOptions): Promise<T>;
|
|
105
130
|
protected transactionCleanupFailed(_error: Error): void;
|
|
106
131
|
/**
|
|
107
132
|
* One `PoolClient` from `pool.connect()` — plan §3.5's pinned producer for
|
|
108
133
|
* `pg`. `release(true)` destroys the connection instead of returning it, so a
|
|
109
134
|
* session whose advisory-lock state is unknown never re-enters the pool.
|
|
110
135
|
*/
|
|
111
|
-
protected pinnedSession(): Promise<PinnedSessionReservation<
|
|
136
|
+
protected pinnedSession(): Promise<PinnedSessionReservation<PgPool | PgPoolClient>>;
|
|
112
137
|
}
|
|
113
138
|
declare function createClient<S extends Schema, C extends DriverConfig<S>>(config: PgClientConfig<C> & DriverConfig<S> & NoExtraDriverConfigKeys<C, PgDriverOptions, S>): VibORMClient<{ [P in keyof LinkedClientConfig<C & {
|
|
114
139
|
driver: PgDriver;
|
package/dist/pg.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{l as t,n,p as r,r as i}from"./error-mapping-CnPCv1dm.mjs";import{r as a}from"./validation-Dk9Q_-C7.mjs";import{n as o}from"./transaction-Bnl6ULTw.mjs";import{n as s}from"./suppressed-failure-BwULh-8h.mjs";import{s as c}from"./execution-context-BKR3bgES.mjs";import{n as l}from"./client-BLiBmykn.mjs";import{c as u,d,f,i as p,o as m,s as h,t as g,u as _}from"./driver-BlnKXPFF.mjs";import{t as v}from"./postgres-result-7F0DllQe.mjs";import{t as y}from"./postgres-adapter-CQD2oGuD.mjs";import{Pool as b,types as x}from"pg";const identityParser=e=>e,S={getTypeParser:(e,t)=>[1082,1114,1184,1115,1182,1185].includes(e)&&t!==`binary`?identityParser:x.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 C=new Set([`user`,`password`,`host`,`port`]),w=[`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&&(C.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 w)i.searchParams.delete(e);else e===`database`?i.pathname=`/${String(t)}`:C.has(e)&&(typeof t==`string`||typeof t==`number`)&&i.searchParams.set(e,String(t));return{...e,connectionString:i.href}}const T={pool:!0,options:!0,pgvector:!0,postgis:!0,databaseUrl:!0,namespace:!0,migrationSessionAttestation:!0};var PgDriver=class extends g{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;ownedPoolErrors=new WeakMap;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),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 b({types:S,...this.connectionOptions}),t=createOwnedPoolErrorState();return this.ownedPoolErrors.set(e,t),e.on(`error`,t.retain),Promise.resolve(e)}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:S}).catch(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`,T);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}))}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 { PostgresAdapter } from \"@adapters/databases/postgres/postgres-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 { TransactionError, unsupportedVector } from \"@errors\";\nimport { Pool, type PoolClient, type PoolConfig, types as pgTypes } from \"pg\";\nimport { Driver, type QueryExecutionContext } 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 resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\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: PoolClient): 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// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PoolConfig as PgOptions } from \"pg\";\n\nexport interface PgDriverOptions {\n pool?: Pool;\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\nexport type PgClientConfig<C extends DriverConfig> = PgDriverOptions & C;\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PgDriver extends Driver<Pool, PoolClient> {\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: Pool | 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 */\n private readonly connectionOptions: PoolConfig;\n /** The caller's `databaseUrl`, read once, for the same reason. */\n private readonly connectionString: string | undefined;\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 this.connectionOptions = { ...options.options };\n this.connectionString = options.databaseUrl;\n\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n\n const adapter = new PostgresAdapter(namespace, options.postgis === true);\n adapter.capabilities.supportsVector = options.pgvector === true;\n if (!options.pgvector) adapter.vector = unsupportedVector;\n defineImmutableDriverFact(this, \"adapter\", adapter);\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<Pool> {\n if (this.suppliedPool !== undefined) {\n return Promise.resolve(this.suppliedPool);\n }\n const options: PoolConfig = {\n types: utcSafeTypes,\n ...this.connectionOptions,\n };\n if (this.connectionString !== undefined) {\n options.connectionString ??= this.connectionString;\n }\n const pool = new Pool(options);\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: Pool | PoolClient\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: Pool | PoolClient,\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: Pool | PoolClient,\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: Pool | PoolClient,\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: Pool,\n context: QueryExecutionContext = {},\n maxWaitMs?: number\n ): Promise<PoolClient> {\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: Pool): 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: Pool | PoolClient,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\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 protected async executeRaw<T>(\n client: Pool | PoolClient,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\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 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: Pool | PoolClient,\n fn: (tx: PoolClient) => 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 pool = client as Pool;\n const poolClient = await this.acquirePooledClient(\n pool,\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<Pool | PoolClient>\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 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 const { pool, options = {}, pgvector, postgis, databaseUrl } = config;\n const namespace = resolveNamespaceOption(config);\n\n // The caller's `options` record is theirs: the connection string goes on a\n // copy this wrapper owns.\n const driverOptions: PgDriverOptions = {\n options:\n databaseUrl === undefined\n ? options\n : { ...options, connectionString: databaseUrl },\n };\n if (pool) driverOptions.pool = pool;\n if (pgvector !== undefined) driverOptions.pgvector = pgvector;\n if (postgis !== undefined) driverOptions.postgis = postgis;\n if (namespace !== undefined) driverOptions.namespace = namespace;\n\n const driver = new PgDriver(driverOptions);\n\n return createClientFromDriverConfig<S, C, PgDriver>(config, driver);\n}\n"],"mappings":"inBAkDA,MAEM,eAAkB,GAAkB,EACpC,EAAoC,CACxC,eAAgB,EAAa,IAEzB,CAAC,KAAU,KAAe,KAAM,KAAM,KAAM,KAAK,CAAC,SAAS,EAAI,EAC/D,IAAW,SAEJ,eAEFA,EAAQ,cAAc,EAAc,EAAgB,CAE9D,CAaD,SAAS,2BAAiD,CACxD,IAAI,EAAa,EACX,EAA6B,CACjC,OAAO,EAAO,CACZ,GAAc,EACd,EAAM,kBAAoB,CAAE,QAAO,aAAY,YAAa,GAAM,EAErE,CACD,OAAO,EAqBT,SAA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ACjD,MAAO,CACL,QAAS,EACT,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,GAAM,CAAE,OAAM,UAAU,EAAE,CAAE,WAAU,UAAS,eAAgB,EACzD,EAAY,EAAuB,EAAO,CAI1C,EAAiC,CACrC,QACE,IAAgB,IAAA,GACZ,EACA,CAAE,GAAG,EAAS,iBAAkB,EAAa,CACpD,CAQD,OAPI,IAAM,EAAc,KAAO,GAC3B,IAAa,IAAA,KAAW,EAAc,SAAW,GACjD,IAAY,IAAA,KAAW,EAAc,QAAU,GAC/C,IAAc,IAAA,KAAW,EAAc,UAAY,GAIhD,EAA6C,EAFrC,IAAI,SAAS,EAAc,CAEyB"}
|
|
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 * 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 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 });\n\n return createClientFromDriverConfig<S, C, PgDriver>(config, driver);\n}\n"],"mappings":"yjBA4DA,MAEM,eAAkB,GAAkB,EACpC,EAAoC,CACxC,eAAgB,EAAa,IAEzB,CAAC,KAAU,KAAe,KAAM,KAAM,KAAM,KAAK,CAAC,SAAS,EAAI,EAC/D,IAAW,SAEJ,eAEFA,EAAQ,cAAc,EAAc,EAAgB,CAE9D,CAaD,SAAS,2BAAiD,CACxD,IAAI,EAAa,EACX,EAA6B,CACjC,OAAO,EAAO,CACZ,GAAc,EACd,EAAM,kBAAoB,CAAE,QAAO,aAAY,YAAa,GAAM,EAErE,CACD,OAAO,EAqBT,SAAS,iBAAiB,EAAwC,CAChE,IAAI,EACE,OAAU,GAAiB,CAC/B,IAAY,GAGd,OADA,EAAO,GAAG,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AAU,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,EAe/D,OAAO,EAA6C,EAdrC,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,UACD,CAAC,CAEiE"}
|
package/dist/pglite.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as Schema, B as LinkedClientConfig, Dn as TransactionOptionSupport, Mn as QueryResult, Pt as DriverConfig, Rt as NoExtraDriverConfigKeys, jn as QueryExecutionContext, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver, zt as VibORMClient } from "./index-C_XLSTy2.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
|
|
@@ -49,6 +49,7 @@ declare class PGliteDriver extends Driver<PGlite, Transaction> {
|
|
|
49
49
|
protected closeClient(client: PGlite): Promise<void>;
|
|
50
50
|
protected execute<T>(client: PGlite | Transaction, sql: string, params: unknown[], context?: QueryExecutionContext): Promise<QueryResult<T>>;
|
|
51
51
|
protected executeRaw<T>(client: PGlite | Transaction, sql: string, params: unknown[] | undefined, context?: QueryExecutionContext): Promise<QueryResult<T>>;
|
|
52
|
+
private executeQuery;
|
|
52
53
|
/**
|
|
53
54
|
* PGlite is a full PostgreSQL, so the isolation level is a real post-BEGIN
|
|
54
55
|
* statement. It is also single-connection, so top-level transactions queue —
|
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{c as t}from"./bind-parameter-capacity-CjPgqnmx.mjs";import{d as n,l as r}from"./error-mapping-CnPCv1dm.mjs";import{s as i}from"./execution-context-BKR3bgES.mjs";import{n as a}from"./client-BLiBmykn.mjs";import{a as o,n as s}from"./pinned-session-CLxj5M5e.mjs";import{c,d as l,r as u,t as d}from"./driver-BlnKXPFF.mjs";import{t as f}from"./postgres-adapter-CQD2oGuD.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,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;return a(e,new PGliteDriver({client:t,dataDir:n,options:r,pgvector:i,postgis:o,namespace:l(e)}))}export{PGliteDriver,createClient};
|
|
2
2
|
//# sourceMappingURL=pglite.mjs.map
|