viborm 1.14.2 → 1.16.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-DwFnfpED.mjs +2 -0
- package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DwFnfpED.mjs.map} +1 -1
- package/dist/adapters.d.mts +26 -10
- package/dist/adapters.mjs +1 -1
- package/dist/args-7WgBFd_f.mjs +2 -0
- package/dist/{args-764KdWMr.mjs.map → args-7WgBFd_f.mjs.map} +1 -1
- package/dist/array-literal-BOzj0E2u.mjs +2 -0
- package/dist/{array-literal-DHinAnVs.mjs.map → array-literal-BOzj0E2u.mjs.map} +1 -1
- package/dist/base-17NSFtrA.mjs +2 -0
- package/dist/base-17NSFtrA.mjs.map +1 -0
- package/dist/batch-refs-Bd8HvwUc.mjs +2 -0
- package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-Bd8HvwUc.mjs.map} +1 -1
- package/dist/better-auth.d.mts +116 -0
- package/dist/better-auth.mjs +6 -0
- package/dist/better-auth.mjs.map +1 -0
- package/dist/bind-parameter-capacity-BAFQM9Jt.mjs +2 -0
- package/dist/{bind-parameter-capacity-BMD-bxMO.mjs.map → bind-parameter-capacity-BAFQM9Jt.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/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/cloudflare-kv.mjs.map +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.d.mts +2 -2
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/call-0bd_B9Vp.mjs +2 -0
- package/dist/{call-Cz8XUmrl.mjs.map → call-0bd_B9Vp.mjs.map} +1 -1
- package/dist/cli.mjs +6 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-D7sWgUt2.mjs +2 -0
- package/dist/client-D7sWgUt2.mjs.map +1 -0
- package/dist/client-DEfFqv4S.mjs +9 -0
- package/dist/client-DEfFqv4S.mjs.map +1 -0
- package/dist/{client-CRxfhw2y.d.mts → client-Dlz3-2JC.d.mts} +3 -3
- package/dist/client.d.mts +3 -3
- package/dist/client.mjs +1 -1
- package/dist/client.mjs.map +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/confine-CyI9IwjC.mjs +2 -0
- package/dist/{confine-DqFBTUw6.mjs.map → confine-CyI9IwjC.mjs.map} +1 -1
- package/dist/coordination-BxMskOgi.mjs +2 -0
- package/dist/coordination-BxMskOgi.mjs.map +1 -0
- package/dist/d1.d.mts +2 -30
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-BMjJiBFm.d.mts} +8476 -8386
- package/dist/datetime-physical-codec-DAF7WJpy.mjs +2 -0
- package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +1 -0
- package/dist/defaults-DAPb-tJ4.mjs +2 -0
- package/dist/{defaults-DwOHWI_M.mjs.map → defaults-DAPb-tJ4.mjs.map} +1 -1
- package/dist/{document-BVTQ-cF-.d.mts → document-CHaVF7Vn.d.mts} +36 -2
- package/dist/{driver-BBEmaJZy.d.mts → driver-BvTixv-m.d.mts} +1 -1
- package/dist/driver-diagnostics-aQ54bArn.mjs +2 -0
- package/dist/{driver-diagnostics-DW9NdckJ.mjs.map → driver-diagnostics-aQ54bArn.mjs.map} +1 -1
- package/dist/driver-kiIQS_Fd.mjs +2 -0
- package/dist/driver-kiIQS_Fd.mjs.map +1 -0
- package/dist/driver-lShUkDmf.mjs +2 -0
- package/dist/driver-lShUkDmf.mjs.map +1 -0
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/durable-object.d.mts +1 -1
- package/dist/durable-object.mjs +2 -2
- package/dist/durable-object.mjs.map +1 -1
- package/dist/error-mapping-B9rSvgG9.mjs +2 -0
- package/dist/error-mapping-B9rSvgG9.mjs.map +1 -0
- package/dist/every-JpbiHdMb.mjs +2 -0
- package/dist/{every-tOgQmaIE.mjs.map → every-JpbiHdMb.mjs.map} +1 -1
- package/dist/execution-context-couU2tgh.mjs +2 -0
- package/dist/execution-context-couU2tgh.mjs.map +1 -0
- package/dist/{exports-COCJ8f2f.d.mts → exports-DYnTfvQo.d.mts} +1 -1
- package/dist/extension-Dh1ddrlA.mjs +2 -0
- package/dist/{extension-CGepsF-p.mjs.map → extension-Dh1ddrlA.mjs.map} +1 -1
- package/dist/fs-estate-n-QpsFqb.mjs +2 -0
- package/dist/{fs-estate-D1Nsg9G1.mjs.map → fs-estate-n-QpsFqb.mjs.map} +1 -1
- package/dist/geo-area-codec-Bti2PA2i.mjs +2 -0
- package/dist/geo-area-codec-Bti2PA2i.mjs.map +1 -0
- package/dist/id-domain-Cg65TLZ-.mjs +2 -0
- package/dist/id-domain-Cg65TLZ-.mjs.map +1 -0
- package/dist/identifier-conversion-BTDxDwDB.mjs +2 -0
- package/dist/identifier-conversion-BTDxDwDB.mjs.map +1 -0
- package/dist/identifiers-BxOf57qy.mjs +2 -0
- package/dist/identifiers-BxOf57qy.mjs.map +1 -0
- package/dist/identity-CJlRQA-m.mjs +2 -0
- package/dist/identity-CJlRQA-m.mjs.map +1 -0
- package/dist/index.d.mts +3 -3
- 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/introspect-q3Rf_Xv8.mjs +2 -0
- package/dist/introspect-q3Rf_Xv8.mjs.map +1 -0
- package/dist/json-CsAdz9pg.mjs +2 -0
- package/dist/json-CsAdz9pg.mjs.map +1 -0
- package/dist/json-number-C09rsm1g.mjs +2 -0
- package/dist/{json-number-AI-SdUUn.mjs.map → json-number-C09rsm1g.mjs.map} +1 -1
- package/dist/json-parameter-D7hDrVKw.mjs +2 -0
- package/dist/{json-parameter-oQ8nGaKr.mjs.map → json-parameter-D7hDrVKw.mjs.map} +1 -1
- package/dist/judge-words-k5GCc4cV.mjs +2 -0
- package/dist/judge-words-k5GCc4cV.mjs.map +1 -0
- package/dist/key-BDH6oTyC.mjs +2 -0
- package/dist/key-BDH6oTyC.mjs.map +1 -0
- package/dist/keys-CIal55WQ.mjs +2 -0
- package/dist/{keys-BQxM4c_a.mjs.map → keys-CIal55WQ.mjs.map} +1 -1
- package/dist/keys-DZdKAd4n.mjs +2 -0
- package/dist/keys-DZdKAd4n.mjs.map +1 -0
- package/dist/libsql-DEZ0uhK2.mjs +3 -0
- package/dist/libsql-DEZ0uhK2.mjs.map +1 -0
- package/dist/libsql.d.mts +2 -20
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/light-D2wNSbzY.mjs +2 -0
- package/dist/{light-BkJe3-yW.mjs.map → light-D2wNSbzY.mjs.map} +1 -1
- package/dist/memory-BaGWNdvk.mjs +2 -0
- package/dist/{memory-G4cSuc6A.mjs.map → memory-BaGWNdvk.mjs.map} +1 -1
- package/dist/methods-part-BaNx3o7b.mjs +2 -0
- package/dist/methods-part-BaNx3o7b.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +5 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +5 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/snowflake.d.mts +5 -5
- package/dist/migrations/snowflake.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +5 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.d.mts +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs.map +1 -1
- package/dist/migrations/storage/fs.d.mts +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/storage/r2.mjs.map +1 -1
- package/dist/migrations/surrealdb.d.mts +5 -5
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations/tenant.mjs.map +1 -1
- package/dist/migrations-DIUltjr3.mjs +2 -0
- package/dist/{migrations-BMiRjR-N.mjs.map → migrations-DIUltjr3.mjs.map} +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/model-Dtd37Sky.mjs +2 -0
- package/dist/model-Dtd37Sky.mjs.map +1 -0
- package/dist/mysql-BFPF8xyv.mjs +9 -0
- package/dist/mysql-BFPF8xyv.mjs.map +1 -0
- package/dist/mysql-adapter-BFWYPoM0.mjs +2 -0
- package/dist/mysql-adapter-BFWYPoM0.mjs.map +1 -0
- package/dist/mysql2.d.mts +2 -27
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/named-statements-CkOOD__I.mjs +2 -0
- package/dist/named-statements-CkOOD__I.mjs.map +1 -0
- package/dist/named-statements-NF7Iycjk.d.mts +13 -0
- package/dist/native-types-1ewJXVks.mjs +2 -0
- package/dist/native-types-1ewJXVks.mjs.map +1 -0
- 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/normalized-result-D7nVkF36.mjs +2 -0
- package/dist/normalized-result-D7nVkF36.mjs.map +1 -0
- package/dist/{object-store-B_YMoW8u.d.mts → object-store-C4qmW7xf.d.mts} +4 -4
- package/dist/object-store-Chq1PMYz.mjs +2 -0
- package/dist/object-store-Chq1PMYz.mjs.map +1 -0
- package/dist/on-ZkOVmE4-.mjs +2 -0
- package/dist/{on-ylYaKuRu.mjs.map → on-ZkOVmE4-.mjs.map} +1 -1
- package/dist/on.d.mts +1 -1
- package/dist/on.mjs +1 -1
- package/dist/on.mjs.map +1 -1
- package/dist/ordering/keys.mjs +1 -1
- package/dist/ordering.d.mts +9 -3
- package/dist/ordering.mjs +10 -10
- package/dist/ordering.mjs.map +1 -1
- package/dist/pending-operation-D4gUKMxD.mjs +2 -0
- package/dist/pending-operation-D4gUKMxD.mjs.map +1 -0
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/permissions.mjs.map +1 -1
- package/dist/pg.d.mts +16 -99
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/physical-DO4PEYcc.mjs +2 -0
- package/dist/physical-DO4PEYcc.mjs.map +1 -0
- package/dist/pinned-session-Y7-2pRBJ.mjs +2 -0
- package/dist/pinned-session-Y7-2pRBJ.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-DHjdvjwk.d.mts → planner-C-zjj19U.d.mts} +123 -1
- package/dist/postgres-DQQE2ys_.mjs +34 -0
- package/dist/postgres-DQQE2ys_.mjs.map +1 -0
- package/dist/postgres-adapter-BpLizOaK.mjs +2 -0
- package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-BpLizOaK.mjs.map} +1 -1
- package/dist/postgres-adapter-psTVfuw7.mjs +2 -0
- package/dist/postgres-adapter-psTVfuw7.mjs.map +1 -0
- package/dist/postgres-result-133boRW-.mjs +2 -0
- package/dist/postgres-result-133boRW-.mjs.map +1 -0
- package/dist/postgres.d.mts +27 -59
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/provider-limits-Bcsz0EJv.mjs +2 -0
- package/dist/provider-limits-Bcsz0EJv.mjs.map +1 -0
- package/dist/provider-parameter-snapshot-cyTUDutH.mjs +2 -0
- package/dist/provider-parameter-snapshot-cyTUDutH.mjs.map +1 -0
- package/dist/quantized-BKBs0joq.mjs +2 -0
- package/dist/quantized-BKBs0joq.mjs.map +1 -0
- package/dist/query-BTb6iakn.mjs +2 -0
- package/dist/query-BTb6iakn.mjs.map +1 -0
- package/dist/query-backend-TisPjCPF.mjs +2 -0
- package/dist/query-backend-TisPjCPF.mjs.map +1 -0
- package/dist/query-inspection-DwYBKSDG.mjs +2 -0
- package/dist/query-inspection-DwYBKSDG.mjs.map +1 -0
- package/dist/raw-DqEb71JZ.mjs +2 -0
- package/dist/raw-DqEb71JZ.mjs.map +1 -0
- package/dist/relation-bound-CSNKLyDy.mjs +2 -0
- package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-CSNKLyDy.mjs.map} +1 -1
- package/dist/result-parsing-BbffueEX.mjs +2 -0
- package/dist/{result-parsing-B0Y4KGDT.mjs.map → result-parsing-BbffueEX.mjs.map} +1 -1
- package/dist/routed-operations-CcKOdn51.mjs +2 -0
- package/dist/{routed-operations-wytpbYKv.mjs.map → routed-operations-CcKOdn51.mjs.map} +1 -1
- package/dist/rows-of-Bgl9GVtK.mjs +2 -0
- package/dist/rows-of-Bgl9GVtK.mjs.map +1 -0
- package/dist/rule-words-DMbQuvD2.mjs +2 -0
- package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-DMbQuvD2.mjs.map} +1 -1
- package/dist/scalar-Dm9brvAU.mjs +4 -0
- package/dist/scalar-Dm9brvAU.mjs.map +1 -0
- package/dist/schema/introspect.d.mts +2 -2
- package/dist/schema/introspect.mjs +1 -1
- package/dist/schema/json.d.mts +6 -4
- package/dist/schema/json.mjs +1 -1
- package/dist/schema-DDkAUfOb.mjs +2 -0
- package/dist/schema-DDkAUfOb.mjs.map +1 -0
- package/dist/schema-DqR_Kcje.mjs +2 -0
- package/dist/schema-DqR_Kcje.mjs.map +1 -0
- package/dist/schema-introspection-Bbo4DN_d.mjs +4 -0
- package/dist/schema-introspection-Bbo4DN_d.mjs.map +1 -0
- package/dist/schema.d.mts +2 -2
- package/dist/schema.mjs +1 -1
- package/dist/select-assembly-CEpNu-Gw.mjs +2 -0
- package/dist/select-assembly-CEpNu-Gw.mjs.map +1 -0
- package/dist/serializer-ettLu5xG.mjs +33 -0
- package/dist/serializer-ettLu5xG.mjs.map +1 -0
- package/dist/settle-Pui-1tfJ.mjs +2 -0
- package/dist/{settle-1cy5x_52.mjs.map → settle-Pui-1tfJ.mjs.map} +1 -1
- package/dist/settled-DYYPcaBX.mjs +2 -0
- package/dist/{settled-BjyuA76m.mjs.map → settled-DYYPcaBX.mjs.map} +1 -1
- package/dist/snowflake-BfF8xwfP.mjs +2 -0
- package/dist/{snowflake-UOCC820W.mjs.map → snowflake-BfF8xwfP.mjs.map} +1 -1
- package/dist/snowflake.d.mts +3 -3
- package/dist/snowflake.mjs +2 -2
- package/dist/snowflake.mjs.map +1 -1
- package/dist/soft-delete.d.mts +9 -3
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/{spans-XDUFeTzC.mjs → spans-DwDXMvyd.mjs} +1 -1
- package/dist/{spans-XDUFeTzC.mjs.map → spans-DwDXMvyd.mjs.map} +1 -1
- package/dist/sql-Bu63iAfT.mjs +2 -0
- package/dist/sql-Bu63iAfT.mjs.map +1 -0
- package/dist/{sql-BVZ8QefY.d.mts → sql-C4_sFNDm.d.mts} +18 -5
- package/dist/sql-statement-tokens-Z5Ta4iDB.mjs +3 -0
- package/dist/{sql-statement-tokens-DbeMwHra.mjs.map → sql-statement-tokens-Z5Ta4iDB.mjs.map} +1 -1
- package/dist/sql-tegqTqGq.mjs +2 -0
- package/dist/sql-tegqTqGq.mjs.map +1 -0
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-Cb-SJw2f.mjs +2 -0
- package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +1 -0
- package/dist/sqlite-statement-classifier-JBHiQO6Q.mjs +2 -0
- package/dist/{sqlite-statement-classifier-BAHl-WXS.mjs.map → sqlite-statement-classifier-JBHiQO6Q.mjs.map} +1 -1
- package/dist/sqlite-utils-Bfmtkt1b.mjs +2 -0
- package/dist/sqlite-utils-Bfmtkt1b.mjs.map +1 -0
- package/dist/sqlite3.d.mts +2 -46
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/standard-sql-Bl2OHGfi.mjs +6 -0
- package/dist/standard-sql-Bl2OHGfi.mjs.map +1 -0
- package/dist/suppressed-failure-CFUDJrUw.mjs +2 -0
- package/dist/{suppressed-failure-CQkQsMVS.mjs.map → suppressed-failure-CFUDJrUw.mjs.map} +1 -1
- package/dist/surrealdb.d.mts +2 -2
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/surrealql-DY74AUeD.mjs +2 -0
- package/dist/surrealql-DY74AUeD.mjs.map +1 -0
- package/dist/time-step-DJaIhpAz.mjs +2 -0
- package/dist/time-step-DJaIhpAz.mjs.map +1 -0
- package/dist/transaction-Bv5nyp-U.mjs +2 -0
- package/dist/{transaction-BNomMtme.mjs.map → transaction-Bv5nyp-U.mjs.map} +1 -1
- package/dist/transaction-operation-CaWzo7gE.mjs +2 -0
- package/dist/{transaction-operation-CVVJxQ19.mjs.map → transaction-operation-CaWzo7gE.mjs.map} +1 -1
- package/dist/types-Dy33vBdd.mjs +2 -0
- package/dist/{types-DtDnXhwa.mjs.map → types-Dy33vBdd.mjs.map} +1 -1
- package/dist/unit-DUPX5Sdd.mjs +2 -0
- package/dist/{unit-BhHbZyuJ.mjs.map → unit-DUPX5Sdd.mjs.map} +1 -1
- package/dist/unit-words-BXpLpyr2.mjs +2 -0
- package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BXpLpyr2.mjs.map} +1 -1
- package/dist/utils-BHkJsduV.mjs +26 -0
- package/dist/{utils-CpAojrCj.mjs.map → utils-BHkJsduV.mjs.map} +1 -1
- package/dist/v1-parse-shared-cJ-uD14P.mjs +2 -0
- package/dist/v1-parse-shared-cJ-uD14P.mjs.map +1 -0
- package/dist/validation-ATmgN5RE.mjs +2 -0
- package/dist/validation-ATmgN5RE.mjs.map +1 -0
- package/dist/validation-BHjx13zG.mjs +2 -0
- package/dist/validation-BHjx13zG.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-DMzH5Tz0.mjs +2 -0
- package/dist/validator-DMzH5Tz0.mjs.map +1 -0
- package/dist/value-guards-CBVIJXlI.mjs +2 -0
- package/dist/{value-guards-CBuxSC66.mjs.map → value-guards-CBVIJXlI.mjs.map} +1 -1
- package/dist/values-Ch2cTlss.mjs +2 -0
- package/dist/{values-B4aj1i1f.mjs.map → values-Ch2cTlss.mjs.map} +1 -1
- package/dist/version-0BDwfy7C.mjs +2 -0
- package/dist/{version-CXGIA82S.mjs.map → version-0BDwfy7C.mjs.map} +1 -1
- package/dist/view-CHgjF2BO.mjs +2 -0
- package/dist/view-CHgjF2BO.mjs.map +1 -0
- package/dist/write-sinks-Bei5vFHP.mjs +2 -0
- package/dist/{write-sinks-3IKCDF-S.mjs.map → write-sinks-Bei5vFHP.mjs.map} +1 -1
- package/package.json +50 -37
- package/dist/adapter-internals-DOqI8IlQ.mjs +0 -2
- package/dist/adapter-internals-DOqI8IlQ.mjs.map +0 -1
- package/dist/adapter-namespace-DaRiTIIf.mjs +0 -2
- package/dist/adapter-result-parser-3WP82Cm-.mjs +0 -2
- package/dist/adapter-result-parser-3WP82Cm-.mjs.map +0 -1
- package/dist/args-764KdWMr.mjs +0 -2
- package/dist/array-literal-DHinAnVs.mjs +0 -2
- package/dist/base-z-cH5ZBI.mjs +0 -2
- package/dist/base-z-cH5ZBI.mjs.map +0 -1
- package/dist/batch-refs-C-gx7A4-.mjs +0 -2
- package/dist/bind-parameter-capacity-BMD-bxMO.mjs +0 -2
- package/dist/call-Cz8XUmrl.mjs +0 -2
- package/dist/canonical-json-Bl-fKFF_.mjs +0 -2
- package/dist/canonical-json-Bl-fKFF_.mjs.map +0 -1
- package/dist/chunk-BuuaeEvq.mjs +0 -1
- package/dist/client-DRpX3-vw.mjs +0 -2
- package/dist/client-DRpX3-vw.mjs.map +0 -1
- package/dist/client-y7TV0PRZ.mjs +0 -9
- package/dist/client-y7TV0PRZ.mjs.map +0 -1
- package/dist/confine-DqFBTUw6.mjs +0 -2
- package/dist/coordination-6qZHx_kl.mjs +0 -2
- package/dist/coordination-6qZHx_kl.mjs.map +0 -1
- package/dist/current-DBTlPsQg.mjs +0 -2
- package/dist/current-DBTlPsQg.mjs.map +0 -1
- package/dist/datetime-physical-codec-Dj-APo9f.mjs +0 -2
- package/dist/datetime-physical-codec-Dj-APo9f.mjs.map +0 -1
- package/dist/defaults-DwOHWI_M.mjs +0 -2
- package/dist/driver-BGVcgnIX.mjs +0 -2
- package/dist/driver-BGVcgnIX.mjs.map +0 -1
- package/dist/driver-BIXhOH2_.mjs +0 -2
- package/dist/driver-BIXhOH2_.mjs.map +0 -1
- package/dist/driver-diagnostics-DW9NdckJ.mjs +0 -2
- package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
- package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
- package/dist/every-tOgQmaIE.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
- package/dist/extension-CGepsF-p.mjs +0 -2
- package/dist/fs-estate-D1Nsg9G1.mjs +0 -2
- package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
- package/dist/geo-area-codec-mHrM3b9A.mjs.map +0 -1
- package/dist/hydration-A3zffFWP.mjs +0 -2
- package/dist/hydration-A3zffFWP.mjs.map +0 -1
- package/dist/identifier-conversion-DHYPTgzr.mjs +0 -2
- package/dist/identifier-conversion-DHYPTgzr.mjs.map +0 -1
- package/dist/identifiers-s00pGES8.mjs +0 -2
- package/dist/identifiers-s00pGES8.mjs.map +0 -1
- package/dist/identity-CtW15WlB.mjs +0 -2
- package/dist/identity-CtW15WlB.mjs.map +0 -1
- package/dist/introspect-Bm6xnXcG.mjs +0 -2
- package/dist/introspect-Bm6xnXcG.mjs.map +0 -1
- package/dist/json-DgMc8-GU.mjs +0 -2
- package/dist/json-DgMc8-GU.mjs.map +0 -1
- package/dist/json-number-AI-SdUUn.mjs +0 -2
- package/dist/json-parameter-oQ8nGaKr.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
- package/dist/key-hxFFCKed.mjs +0 -2
- package/dist/key-hxFFCKed.mjs.map +0 -1
- package/dist/keys-BQxM4c_a.mjs +0 -2
- package/dist/libsql-DuGR904j.mjs +0 -3
- package/dist/libsql-DuGR904j.mjs.map +0 -1
- package/dist/light-BkJe3-yW.mjs +0 -2
- package/dist/memory-G4cSuc6A.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
- package/dist/migrations-BMiRjR-N.mjs +0 -2
- package/dist/mysql-BNXWfTOo.mjs +0 -100
- package/dist/mysql-BNXWfTOo.mjs.map +0 -1
- package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
- package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
- package/dist/native-types-DgjMUikz.mjs +0 -2
- package/dist/native-types-DgjMUikz.mjs.map +0 -1
- package/dist/normalized-result-B8pifWS0.mjs +0 -2
- package/dist/normalized-result-B8pifWS0.mjs.map +0 -1
- package/dist/object-store-DS0F0yZX.mjs +0 -2
- package/dist/object-store-DS0F0yZX.mjs.map +0 -1
- package/dist/on-ylYaKuRu.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
- package/dist/physical-CeE2nYmI.mjs +0 -2
- package/dist/physical-CeE2nYmI.mjs.map +0 -1
- package/dist/pinned-session-DCoAZDOz.mjs +0 -2
- package/dist/pinned-session-DCoAZDOz.mjs.map +0 -1
- package/dist/postgres-CDdh5dSP.mjs +0 -437
- package/dist/postgres-CDdh5dSP.mjs.map +0 -1
- package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
- package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
- package/dist/postgres-adapter-axapXX8d.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
- package/dist/provider-limits-Ccsb8PTb.mjs +0 -2
- package/dist/provider-limits-Ccsb8PTb.mjs.map +0 -1
- package/dist/provider-parameter-snapshot-BikrgKqI.mjs +0 -2
- package/dist/provider-parameter-snapshot-BikrgKqI.mjs.map +0 -1
- package/dist/query-BZVHfA0s.mjs +0 -2
- package/dist/query-BZVHfA0s.mjs.map +0 -1
- package/dist/query-inspection-BoG-yAln.mjs +0 -2
- package/dist/query-inspection-BoG-yAln.mjs.map +0 -1
- package/dist/raw-Dyq6Y6UX.mjs +0 -2
- package/dist/raw-Dyq6Y6UX.mjs.map +0 -1
- package/dist/relation-bound-ku_cMdye.mjs +0 -2
- package/dist/result-parsing-B0Y4KGDT.mjs +0 -2
- package/dist/routed-operations-wytpbYKv.mjs +0 -2
- package/dist/rule-words-ZIGm7cDm.mjs +0 -2
- package/dist/scalar-BHCh7aUz.mjs +0 -4
- package/dist/scalar-BHCh7aUz.mjs.map +0 -1
- package/dist/schema-BYA-_bpk.mjs +0 -2
- package/dist/schema-BYA-_bpk.mjs.map +0 -1
- package/dist/schema-CFIaebgi.mjs +0 -2
- package/dist/schema-CFIaebgi.mjs.map +0 -1
- package/dist/schema-introspection-D0f8cti4.mjs +0 -6
- package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
- package/dist/select-assembly-DVI7d3tf.mjs +0 -2
- package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
- package/dist/serializer-rBq3v1xr.mjs +0 -51
- package/dist/serializer-rBq3v1xr.mjs.map +0 -1
- package/dist/settle-1cy5x_52.mjs +0 -2
- package/dist/settled-BjyuA76m.mjs +0 -2
- package/dist/snowflake-UOCC820W.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs.map +0 -1
- package/dist/sql-Dl6nykFV.mjs +0 -2
- package/dist/sql-Dl6nykFV.mjs.map +0 -1
- package/dist/sql-statement-tokens-DbeMwHra.mjs +0 -3
- package/dist/sqlite-adapter-Ad0d-m2t.mjs +0 -2
- package/dist/sqlite-adapter-Ad0d-m2t.mjs.map +0 -1
- package/dist/sqlite-statement-classifier-BAHl-WXS.mjs +0 -2
- package/dist/sqlite-utils-BRvbmlQ1.mjs +0 -2
- package/dist/sqlite-utils-BRvbmlQ1.mjs.map +0 -1
- package/dist/standard-sql-qLcQyCtK.mjs +0 -6
- package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
- package/dist/suppressed-failure-CQkQsMVS.mjs +0 -2
- package/dist/surrealql-C1dp1sWw.mjs +0 -2
- package/dist/surrealql-C1dp1sWw.mjs.map +0 -1
- package/dist/to-many-BybuKQM1.mjs +0 -2
- package/dist/to-many-BybuKQM1.mjs.map +0 -1
- package/dist/transaction-BNomMtme.mjs +0 -2
- package/dist/transaction-operation-CVVJxQ19.mjs +0 -2
- package/dist/types-DtDnXhwa.mjs +0 -2
- package/dist/unit-BhHbZyuJ.mjs +0 -2
- package/dist/unit-words-CT0yeqfZ.mjs +0 -2
- package/dist/utils-CpAojrCj.mjs +0 -26
- package/dist/validation--qS7OPmg.mjs +0 -2
- package/dist/validation--qS7OPmg.mjs.map +0 -1
- package/dist/validation-CYaJ8ndO.mjs +0 -2
- package/dist/validation-CYaJ8ndO.mjs.map +0 -1
- package/dist/validator-CZLW7aR3.mjs +0 -2
- package/dist/validator-CZLW7aR3.mjs.map +0 -1
- package/dist/value-guards-CBuxSC66.mjs +0 -2
- package/dist/values-B4aj1i1f.mjs +0 -2
- package/dist/version-CXGIA82S.mjs +0 -2
- package/dist/write-sinks-3IKCDF-S.mjs +0 -2
- /package/dist/{contract-CrIB-3ZJ.d.mts → contract-CxJn0_cV.d.mts} +0 -0
package/dist/pg.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { $a as QueryExecutionContext, Di as LinkedClientConfig, Gr as Schema, Ja as TransactionOptionSupport, S as PinnedSessionReservation, eo as QueryResult, h as Driver, pt as VibORMClient, qa as DriverTransactionOptions, st as DriverConfig, t as DatabaseAdapter, ut as NoExtraDriverConfigKeys, v as MigrationSessionAttestation } from "./database-adapter-BMjJiBFm.mjs";
|
|
2
|
+
import { t as NamedStatementsOption } from "./named-statements-NF7Iycjk.mjs";
|
|
2
3
|
import { Pool, PoolClient, PoolConfig, PoolConfig as PgOptions } from "pg";
|
|
3
4
|
|
|
4
5
|
//#region src/drivers/pg/index.d.ts
|
|
@@ -53,119 +54,35 @@ interface PgDriverOptions {
|
|
|
53
54
|
* need it.
|
|
54
55
|
*/
|
|
55
56
|
migrationSessionAttestation?: MigrationSessionAttestation;
|
|
57
|
+
/**
|
|
58
|
+
* Send statements as named, server-side prepared statements: each
|
|
59
|
+
* connection parses and plans one once, then only binds it. With `true`
|
|
60
|
+
* (`{ max: 100, auto: true }`) a statement is named the second time it is
|
|
61
|
+
* sent; with `"explicit"` (`{ max: 100, auto: false }`) only the statements
|
|
62
|
+
* of a call that passes `named: true` are. A call's `named: true` names its
|
|
63
|
+
* statements at their first sending, `named: false` never. A connection
|
|
64
|
+
* holds at most `max` of them. Off by default: behind PgBouncer in
|
|
65
|
+
* transaction mode, set `max_prepared_statements` first.
|
|
66
|
+
*/
|
|
67
|
+
namedStatements?: NamedStatementsOption;
|
|
56
68
|
}
|
|
57
69
|
type PgClientConfig<C extends DriverConfig> = PgDriverOptions & C;
|
|
58
70
|
declare class PgDriver extends Driver<PgPool, PgPoolClient> {
|
|
71
|
+
#private;
|
|
59
72
|
readonly adapter: DatabaseAdapter;
|
|
60
73
|
readonly maxBindParametersPerStatement: number | undefined;
|
|
61
|
-
|
|
62
|
-
* The EXACT pool the caller supplied, or absent when this driver makes its
|
|
63
|
-
* own. Identity, settled here, is the whole ownership answer: the caller's
|
|
64
|
-
* options object is theirs to change, and a `pool` key deleted after
|
|
65
|
-
* construction used to make `$disconnect()` end a transport VibORM was handed
|
|
66
|
-
* and may be sharing with the caller's own code.
|
|
67
|
-
*/
|
|
68
|
-
private readonly suppliedPool;
|
|
69
|
-
/**
|
|
70
|
-
* The caller's connection record, copied once.
|
|
71
|
-
*
|
|
72
|
-
* A copy of THIS record, not of what it points at: a nested `ssl` object or
|
|
73
|
-
* stream is the caller's to own, and the keys that decide where a pool
|
|
74
|
-
* connects — host, port, user, database, connectionString — all live here,
|
|
75
|
-
* with the caller's `databaseUrl` merged in (see `connectionRecord`).
|
|
76
|
-
*/
|
|
77
|
-
private readonly connectionOptions;
|
|
78
|
-
/**
|
|
79
|
-
* The listener and latest idle failure for each pool this driver created.
|
|
80
|
-
*
|
|
81
|
-
* Pool identity matters after a failed `end()`: the base lifecycle
|
|
82
|
-
* quarantines that exact pool for a later disconnect retry, while this state
|
|
83
|
-
* keeps its error listener and retained evidence attached to the same
|
|
84
|
-
* transport until a proven successful end.
|
|
85
|
-
*/
|
|
86
|
-
private readonly ownedPoolErrors;
|
|
87
|
-
/**
|
|
88
|
-
* The `server_version` the last connection this driver's own pool opened
|
|
89
|
-
* received at startup, read for the relation bound (`boundByServer`); a
|
|
90
|
-
* pool given its own `Client` class, or supplied, is not read.
|
|
91
|
-
*/
|
|
92
|
-
private serverVersion;
|
|
93
|
-
private readonly readsServer;
|
|
74
|
+
private readonly _p;
|
|
94
75
|
constructor(options?: PgDriverOptions);
|
|
95
76
|
/** Every host or URL this driver's pool connects through, for migration admission. */
|
|
96
77
|
protected migrationSessionEndpoints(): readonly unknown[];
|
|
97
|
-
/**
|
|
98
|
-
* The pool this driver connects through.
|
|
99
|
-
*
|
|
100
|
-
* A caller's pool is RETURNED rather than replaced: reconnecting after a
|
|
101
|
-
* `$disconnect()` used to build a second pool behind their back — a transport
|
|
102
|
-
* they never asked for, pointed at whatever their options record said by
|
|
103
|
-
* then, and then never closed, because the ownership question was still
|
|
104
|
-
* answered "supplied".
|
|
105
|
-
*
|
|
106
|
-
* It is also returned UNSUBSCRIBED. A supplied pool is borrowed transport and
|
|
107
|
-
* its events belong to its owner: an 'error' listener added here is the very
|
|
108
|
-
* thing that stops Node from throwing, so VibORM would be silencing a crash
|
|
109
|
-
* for a caller who never asked it to — and for the other consumers of a pool
|
|
110
|
-
* two estates share. This driver listens only on the pool it made.
|
|
111
|
-
*/
|
|
112
78
|
protected initClient(): Promise<PgPool>;
|
|
113
|
-
/**
|
|
114
|
-
* node-postgres's `Client`, reading each connection's startup: it keeps no
|
|
115
|
-
* parameter status, so the `server_version` that names Neki is read as it
|
|
116
|
-
* arrives, before the connection is handed out (to a statement, or to a
|
|
117
|
-
* transaction before its callback builds any).
|
|
118
|
-
*/
|
|
119
|
-
private readingClient;
|
|
120
|
-
private readBackgroundPoolFailure;
|
|
121
|
-
/** Clear exactly the failure observed before an operation started. */
|
|
122
|
-
private clearBackgroundPoolFailure;
|
|
123
|
-
/** Claim one retained failure for one failed acquisition, at most once. */
|
|
124
|
-
private consumeBackgroundPoolFailure;
|
|
125
|
-
/** Surface one pool-owned idle failure beside one pool query failure. */
|
|
126
|
-
private throwPoolQueryFailure;
|
|
127
|
-
/**
|
|
128
|
-
* One pooled connection, and — when there is none to be had — the current
|
|
129
|
-
* acquisition failure as primary, with the pool's last background failure
|
|
130
|
-
* retained beside it.
|
|
131
|
-
*
|
|
132
|
-
* The acquisition rejection is the failure of the requested action, so it
|
|
133
|
-
* stays primary. The background report arrived outside every request and is
|
|
134
|
-
* retained through the shared suppressed-failure record. Reported once and
|
|
135
|
-
* released, so the next failure speaks for itself rather than inheriting an
|
|
136
|
-
* explanation that has already been given. An acquisition that fails with
|
|
137
|
-
* nothing retained is left exactly as it was.
|
|
138
|
-
*/
|
|
139
|
-
private acquirePooledClient;
|
|
140
|
-
/**
|
|
141
|
-
* A supplied pool belongs to the caller, who may be sharing it with other
|
|
142
|
-
* clients — two schema-scoped estates over one pool is the documented shape
|
|
143
|
-
* — and §5.3's rule is that VibORM never changes a caller's connection
|
|
144
|
-
* state. `$disconnect()` used to end it regardless, so disconnecting one
|
|
145
|
-
* client tore down every other consumer of that pool.
|
|
146
|
-
*
|
|
147
|
-
* The test is on the pool's IDENTITY against what construction captured, so
|
|
148
|
-
* it answers for the pool actually being closed rather than for whatever the
|
|
149
|
-
* caller's record says now: every pool this driver made is ended, and the one
|
|
150
|
-
* it was handed never is.
|
|
151
|
-
*/
|
|
152
79
|
protected closeClient(pool: PgPool): Promise<void>;
|
|
153
80
|
protected execute<T>(client: PgPool | PgPoolClient, sql: string, params: unknown[], context?: QueryExecutionContext): Promise<QueryResult<T>>;
|
|
154
81
|
protected executeRaw<T>(client: PgPool | PgPoolClient, sql: string, params: unknown[] | undefined, context?: QueryExecutionContext): Promise<QueryResult<T>>;
|
|
155
|
-
private
|
|
156
|
-
/**
|
|
157
|
-
* PostgreSQL takes the isolation level as the first statement inside the
|
|
158
|
-
* transaction, and node-postgres hands out a pooled client we can wait for
|
|
159
|
-
* with a bound (and release if we stop waiting).
|
|
160
|
-
*/
|
|
82
|
+
private static isPositionalCandidate;
|
|
161
83
|
protected transactionOptionSupport(): TransactionOptionSupport;
|
|
162
84
|
protected transaction<T>(client: PgPool | PgPoolClient, fn: (tx: PgPoolClient) => Promise<T>, context?: QueryExecutionContext, options?: DriverTransactionOptions): Promise<T>;
|
|
163
85
|
protected transactionCleanupFailed(_error: Error): void;
|
|
164
|
-
/**
|
|
165
|
-
* One `PoolClient` from `pool.connect()` — plan §3.5's pinned producer for
|
|
166
|
-
* `pg`. `release(true)` destroys the connection instead of returning it, so a
|
|
167
|
-
* session whose advisory-lock state is unknown never re-enters the pool.
|
|
168
|
-
*/
|
|
169
86
|
protected pinnedSession(): Promise<PinnedSessionReservation<PgPool | PgPoolClient>>;
|
|
170
87
|
}
|
|
171
88
|
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 & {
|
package/dist/pg.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{B as e,m as t,n,r,u as i}from"./error-mapping-B9rSvgG9.mjs";import{r as a}from"./validation-ATmgN5RE.mjs";import{n as o}from"./transaction-Bv5nyp-U.mjs";import{n as s}from"./normalized-result-D7nVkF36.mjs";import{n as c}from"./suppressed-failure-CFUDJrUw.mjs";import{f as l,n as u,u as d}from"./client-D7sWgUt2.mjs";import{_ as f,d as p,h as m,l as h,m as g,p as _,r as v,s as y,v as b,y as x}from"./driver-lShUkDmf.mjs";import{t as S}from"./postgres-result-133boRW-.mjs";import{n as C,r as w}from"./named-statements-CkOOD__I.mjs";import{t as T}from"./postgres-adapter-BpLizOaK.mjs";import{n as E,t as D}from"./relation-bound-CSNKLyDy.mjs";import{Client as O,Pool as k,types as A}from"pg";const j=e=>e,M={getTypeParser:(e,t)=>[1082,1114,1184,1115,1182,1185].includes(e)&&t!==`binary`?j:A.getTypeParser(e,t)};function N(){let e=0,t={r(n){e+=1,t.f={e:n,g:e,a:!0}}};return t}function P(e){let t,n=e=>{t??=e};return e.on(`error`,n),{f:()=>t,s:()=>{e.off(`error`,n)}}}const F=new Set([`user`,`password`,`host`,`port`]),I=[`sslmode`,`sslcert`,`sslkey`,`sslrootcert`];function L(e,t){let n=e.connectionString??t;if(!n)return e;if(typeof e.password==`function`)throw new a(`Driver "pg": password callback conflicts with URL.`,{meta:{driver:`pg`,operation:`configuration`}});let r=x(n),i;try{i=new URL(r)}catch{i=void 0}let o=Object.entries(e).filter(([e,t])=>t!==void 0&&(F.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": invalid URL.`,{meta:{driver:`pg`,operation:`configuration`}});for(let[e,t]of o)if(i.searchParams.delete(e),e===`ssl`)for(let e of I)i.searchParams.delete(e);else e===`database`?i.pathname=`/${String(t)}`:F.has(e)&&(typeof t==`string`||typeof t==`number`)&&i.searchParams.set(e,String(t));return{...e,connectionString:i.href}}const R={pool:!0,options:!0,pgvector:!0,postgis:!0,databaseUrl:!0,namespace:!0,sharedRelationBodies:!0,relationsPerStatement:!0,migrationSessionAttestation:!0,namedStatements:!0};function z(e){return class extends O{constructor(t){super(t),this.connection.on(`parameterStatus`,t=>{t.parameterName===`server_version`&&(e.v=t.parameterValue)})}}}function B(e,t){return e.e.get(t)?.f}function V(e,t,n){if(!n?.a)return!1;n.a=!1;let r=e.e.get(t);return r?.f?.g===n.g&&(r.f=void 0),!0}function H(e,t,n){return V(e,t,n)?n?.e:void 0}function U(e,t,n,i,a,o,s){E(e.adapter,i);let l=H(e._p,t,n);throw l===void 0?i:c(r(i,{...h(e,s,!0),query:a,params:p(o??[],s),hb:!0}),l)}async function W(e,t,n,r,i,a,o){let s=e._p,c=B(s,t),l=a===`execute`&&r?.length&&i?.model!==`$raw`?s.n?.name(n,i?.named):void 0,u=o?{text:n,values:r,types:M,rowMode:`array`}:{text:n,values:r,types:M},d=t.query(l===void 0?u:{...u,name:l}),f=a=>U(e,t,c,a,n,r,i),p;try{p=await d}catch(e){if(l===void 0||!C(e)||(s.n?.m6(n),`release`in t))return f(e);try{p=await t.query(u)}catch(e){return f(e)}}return V(s,t,c),p}async function G(e,t,n,r,i,a){let o=i?.operation??a,s=await W(e,t,n,r,i,a,!1);return{rows:s.rows,rowCount:S(s.rowCount,s.command,s.rows,{provider:`pg`,operation:o})}}async function K(e,t,r={},i){let a=e._p,o=B(a,t),s=!1;try{return await y(async()=>{try{let e=await t.connect();return V(a,t,o),e}finally{s=!0}},e=>e.release(),i,{driverName:e.driverName,form:`callback`})}catch(i){if(!s)throw i;let l=H(a,t,o);throw l===void 0?i:c(n(i,h(e,r),`Connection failed after pool error`),l)}}var q=class r extends v{static get name(){return`PgDriver`}static#e=r.prototype._execute;static#t=r.prototype.execute;static#n=r.prototype.executeTypedStatement;maxBindParametersPerStatement=65535;_p;#r;constructor(e={}){super(`postgresql`,`pg`);let t=b(e),n=e.pool,i={...e.options};g(`pg`,e,!!(n||i.host||i.connectionString));let a={p:n,c:L(i,e.databaseUrl),e:new WeakMap,v:void 0,r:!1,n:w(`pg`,e.namedStatements)};this._p=a,n&&(this.client=n),T(this,t,e),this.#r=r.#a(this),l(this,(e,t)=>this.#i(e,t),r.nl),a.r=n===void 0&&i.Client===void 0&&D(this.adapter,()=>a.v),_(this,`migrationSessionAttestation`,f(e))}migrationSessionEndpoints(){let e=this._p,t=e.p?Reflect.get(e.p,`options`):void 0,n=typeof t==`object`&&t?t:{};return[e.c.host,e.c.connectionString,Reflect.get(n,`host`),Reflect.get(n,`connectionString`)]}initClient(){let e=this._p;if(e.p!==void 0)return Promise.resolve(e.p);let t=new k({types:M,...e.c,...e.r?{Client:z(e)}:{}}),n=N();return e.e.set(t,n),t.on(`error`,n.r),Promise.resolve(t)}async closeClient(e){let t=this._p;if(e===t.p)return;let r=t.e.get(e);try{await e.end()}catch(i){let a=H(t,e,r?.f);throw a===void 0?i:c(n(i,{driverName:this.driverName},`Database disconnection failed`),a)}r!==void 0&&(r.f=void 0,t.e.delete(e))}async execute(e,t,n,r){return G(this,e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return G(this,e,t,n,r,`executeRaw`)}#i(e,t){return this.executeTypedStatement(e,t,async(e,t,n,i)=>{let a={provider:this.driverName,operation:i.operation??`execute`};if(!r.nl(this)){let r=await this.execute(e,t,n,i);return s(r,a),{kind:`borrowed`,result:r}}let o=await W(this,e,t,n,i,`execute`,!0),c=o.rows;if(c.length>0&&!Array.isArray(c[0])){let e={rows:c,rowCount:c.length};return s(e,a),{kind:`borrowed`,result:e}}let l=o.fields.map(e=>e.name);return d(c,l,a),{kind:`positional`,rows:c,columns:l}})}static nl(e){if(!(e instanceof r))return!1;let t=e.#r,{adapter:n}=e,{result:i}=n;return Object.getPrototypeOf(e)===r.prototype&&e._execute===r.#e&&e.execute===r.#t&&e.executeTypedStatement===r.#n&&e.result===void 0&&t[0]===n&&t[1]===i&&t[2]===i.parseField&&t[3]===i.parseRelation&&t[4]===i.parseResult}static#a(e){let{adapter:t}=e,{result:n}=t;return[t,n,n.parseField,n.parseRelation,n.parseResult]}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(n,r,a,s){if(`release`in n)throw i(this.driverName);let l=await K(this,n,a,s?.maxWaitMs),u=P(l),d=e=>{let t=u.f();return t===void 0||t===e?e:c(e,t)},f,p=async e=>{try{await l.query(e)}catch(e){throw f??=e instanceof Error?e:!0,d(e)}};return t({begin:()=>p(`BEGIN`),callback:async()=>{try{return await r(l)}catch(e){throw d(e)}},commit:()=>{let e=u.f();if(e!==void 0)throw e;return p(`COMMIT`)},rollback:()=>u.f()===void 0?p(`ROLLBACK`):void 0,he:e(a),close:()=>{try{let e=f??u.f();if(e){l.release(e);return}l.release()}catch(e){throw super.transactionCleanupFailed(new o(`Driver "pg": tx release failed.`,{meta:{driver:`pg`,method:`$transaction`}})),e}finally{u.s()}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(`release`in e)throw i(this.driverName);let t=await K(this,e,{operation:`pinnedSession`}),n=P(t);return{session:t,lost:n.f,release:e=>{try{t.release(n.f()??(e?!0:void 0))}finally{n.s()}return Promise.resolve()}}}};function J(e){m(e,`pg`,R);let{pool:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e;return u(e,new q({namespace:b(e),migrationSessionAttestation:f(e),pool:t||void 0,options:n,...Object.hasOwn(e,`databaseUrl`)?{databaseUrl:a}:{},pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namedStatements:e.namedStatements}))}export{q as PgDriver,J as createClient};
|
|
2
2
|
//# sourceMappingURL=pg.mjs.map
|
package/dist/pg.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pg.mjs","names":["pgTypes"],"sources":["../src/drivers/pg/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (node-postgres)\n *\n * Driver implementation for pg (node-postgres) with connection pooling.\n *\n * No statement pipelining. node-postgres has no pipeline mode: a `Client` holds\n * one query active at a time and drains the rest from an internal queue, so the\n * statements of a transaction always cost one round trip each no matter how\n * they are issued. Nothing here can change that, and nothing here tries to —\n * see the Phase 9 disposition in `docs/architecture/query-performance-plan.md`,\n * which measured the same limit on the postgres.js driver for different\n * reasons.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, TransactionError } from \"@errors\";\nimport {\n Client,\n type ClientConfig,\n Pool,\n type PoolClient,\n type PoolConfig,\n types as pgTypes,\n} from \"pg\";\nimport {\n Driver,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n normalizeDriverConnectionError,\n normalizeDriverError,\n} from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport {\n refuseEmptyDatabaseUrl,\n refuseUnknownDriverConfigKeys,\n systemRootAsVerifyFull,\n} from \"../shared/driver-options\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport { boundByServer, learnRelationLimit } from \"../shared/relation-bound\";\nimport type { QueryResult } from \"../types\";\n\n// DATE (1082) and TIMESTAMP WITHOUT TIME ZONE (1114): pg's default parsers\n// build process-local Dates, shifting the stored value by the process\n// timezone. Return the raw strings instead — the shared result parser builds\n// UTC Dates from them, matching every other driver.\nconst DATE_OID = 1082;\nconst TIMESTAMP_OID = 1114;\nconst identityParser = (value: string) => value;\nconst utcSafeTypes: PoolConfig[\"types\"] = {\n getTypeParser: (oid: number, format?: string) => {\n if (\n [DATE_OID, TIMESTAMP_OID, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return pgTypes.getTypeParser(oid as never, format as never);\n },\n};\n\ninterface BackgroundPoolFailure {\n readonly error: Error;\n readonly generation: number;\n isAvailable: boolean;\n}\n\ninterface OwnedPoolErrorState {\n backgroundFailure?: BackgroundPoolFailure;\n readonly retain: (error: Error) => void;\n}\n\nfunction createOwnedPoolErrorState(): OwnedPoolErrorState {\n let generation = 0;\n const state: OwnedPoolErrorState = {\n retain(error) {\n generation += 1;\n state.backgroundFailure = { error, generation, isAvailable: true };\n },\n };\n return state;\n}\n\n/**\n * The `error` channel of one checked-out client, owned for as long as VibORM\n * holds that client.\n *\n * pg-pool removes its idle listener on checkout and puts it back on release,\n * so a connection that drops in between (a restart, a failover, a terminated\n * backend) would otherwise emit an unhandled `error` and end the process. The\n * first failure is kept: its holder refuses to commit after it and releases the\n * client with it, so the pool destroys that connection instead of reusing it.\n *\n * This holds for a supplied pool too. Its `error` event stays the caller's, but\n * a checked-out client is the holder's to answer for until it is released.\n */\ninterface HeldClientErrors {\n readonly failure: () => Error | undefined;\n readonly stop: () => void;\n}\n\nfunction holdClientErrors(client: PgPoolClient): HeldClientErrors {\n let failure: Error | undefined;\n const retain = (error: Error) => {\n failure ??= error;\n };\n client.on(\"error\", retain);\n return {\n failure: () => failure,\n stop: () => {\n client.off(\"error\", retain);\n },\n };\n}\n\n/** The keys node-postgres's URL parser reads from the query before the authority. */\nconst URL_QUERY_KEYS = new Set([\"user\", \"password\", \"host\", \"port\"]);\n/** The query parameters node-postgres derives `ssl` from. */\nconst URL_SSL_KEYS = [\"sslmode\", \"sslcert\", \"sslkey\", \"sslrootcert\"];\n\n/**\n * The pool's connection record: the caller's options, with `databaseUrl` as\n * the connection string unless `options.connectionString` names one, and each\n * connection option they set written into that URL so that it wins.\n *\n * node-postgres parses the connection string over the options beside it and\n * fills the connection keys the URL lacks with empty values, so a per-tenant\n * URL without a password lost `options.password` from a secret, and the URL's\n * port replaced `options.port`. Its parser prefers `user`, `password`, `host`\n * and `port` from the query and reads the database from the path, so an\n * explicit key is written there; any other option the query also names is\n * dropped from it, and an explicit `ssl` drops the parameters that derive one.\n * A password callback cannot be written into a URL, and node-postgres would\n * replace it with the URL's password, so one beside a URL is refused.\n */\nfunction connectionRecord(\n options: PoolConfig,\n databaseUrl: string | undefined\n): PoolConfig {\n const given = options.connectionString ?? databaseUrl;\n if (!given) return options;\n if (typeof options.password === \"function\") {\n throw new ClientInitializationError(\n 'Driver \"pg\" cannot keep a password callback beside a connection URL: node-postgres reads the password from the URL. Pass `host`, `user` and `database` in `options` instead.',\n { meta: { driver: \"pg\", operation: \"configuration\" } }\n );\n }\n const connectionString = systemRootAsVerifyFull(given);\n let url: URL | undefined;\n try {\n url = new URL(connectionString);\n } catch {\n url = undefined;\n }\n const entries: [string, unknown][] = Object.entries(options);\n const overrides = entries.filter(\n ([key, value]) =>\n value !== undefined &&\n (URL_QUERY_KEYS.has(key) ||\n key === \"database\" ||\n key === \"ssl\" ||\n (key !== \"connectionString\" && url?.searchParams.has(key)))\n );\n if (overrides.length === 0) return { ...options, connectionString };\n if (url === undefined) {\n throw new ClientInitializationError(\n 'Driver \"pg\" could not read its connection URL to apply the connection options beside it.',\n { meta: { driver: \"pg\", operation: \"configuration\" } }\n );\n }\n for (const [key, value] of overrides) {\n url.searchParams.delete(key);\n if (key === \"ssl\") {\n for (const sslKey of URL_SSL_KEYS) url.searchParams.delete(sslKey);\n } else if (key === \"database\") {\n url.pathname = `/${String(value)}`;\n } else if (\n URL_QUERY_KEYS.has(key) &&\n (typeof value === \"string\" || typeof value === \"number\")\n ) {\n url.searchParams.set(key, String(value));\n }\n }\n return { ...options, connectionString: url.href };\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PoolConfig as PgOptions } from \"pg\";\n\ninterface PgErrorEvents {\n on(event: \"error\", listener: (error: Error) => void): unknown;\n off(event: \"error\", listener: (error: Error) => void): unknown;\n}\n\n/** The part of a node-postgres `PoolClient` this driver uses. */\ninterface PgPoolClient\n extends Pick<PoolClient, \"query\" | \"release\">,\n PgErrorEvents {}\n\n/**\n * The part of a node-postgres `Pool` this driver uses, so any pool with that\n * shape is accepted. A Neon WebSocket `Pool` (`@neondatabase/serverless`) is\n * node-postgres's pool over a WebSocket and runs here unchanged, but its\n * bundled copy of the pg declarations lags `@types/pg`: in 8.23 a\n * `PoolClient` is a whole `Client`, and the full `Pool` type refused Neon's.\n */\ninterface PgPool extends Pick<Pool, \"query\" | \"end\">, PgErrorEvents {\n connect(): Promise<PgPoolClient>;\n}\n\nexport interface PgDriverOptions {\n pool?: PgPool;\n options?: PoolConfig;\n pgvector?: boolean;\n postgis?: boolean;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Each relation filter body a statement repeats is stated once, in a\n * `WITH`, as the key set its arms test: the answers are the same, the\n * statement smaller, and a server that bounds the relations one statement\n * references (PlanetScale's Neki: 256) accepts it. Defaults to `true`;\n * `false` keeps every body inline.\n */\n sharedRelationBodies?: boolean;\n /**\n * The most relations (`FROM` items) one statement may reference. Past it, a\n * statement states the recursive filters it repeats as key sets, and then\n * joins the key sets a row tests, as far as it needs to fit: the answers are\n * the same, some plans slower. PlanetScale Neki refuses a statement over\n * 256: absent, a pool this driver makes reads each connection's startup,\n * 256 on Neki and before the first connection, none on plain PostgreSQL (a\n * supplied pool learns from Neki's first refusal). A stated bound always\n * wins. Only where relation bodies are shared.\n */\n relationsPerStatement?: number;\n /**\n * Your claim, at your risk, that every connection this pool opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport type PgClientConfig<C extends DriverConfig> = PgDriverOptions & C;\n\nconst PG_CONFIG_KEYS: Record<keyof PgDriverOptions, true> = {\n pool: true,\n options: true,\n pgvector: true,\n postgis: true,\n databaseUrl: true,\n namespace: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n migrationSessionAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PgDriver extends Driver<PgPool, PgPoolClient> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled here, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed\n * and may be sharing with the caller's own code.\n */\n private readonly suppliedPool: PgPool | undefined;\n /**\n * The caller's connection record, copied once.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database, connectionString — all live here,\n * with the caller's `databaseUrl` merged in (see `connectionRecord`).\n */\n private readonly connectionOptions: PoolConfig;\n /**\n * The listener and latest idle failure for each pool this driver created.\n *\n * Pool identity matters after a failed `end()`: the base lifecycle\n * quarantines that exact pool for a later disconnect retry, while this state\n * keeps its error listener and retained evidence attached to the same\n * transport until a proven successful end.\n */\n private readonly ownedPoolErrors = new WeakMap<object, OwnedPoolErrorState>();\n /**\n * The `server_version` the last connection this driver's own pool opened\n * received at startup, read for the relation bound (`boundByServer`); a\n * pool given its own `Client` class, or supplied, is not read.\n */\n private serverVersion: string | undefined;\n private readonly readsServer: boolean;\n\n constructor(options: PgDriverOptions = {}) {\n super(\"postgresql\", \"pg\");\n const namespace = resolveNamespaceOption(options);\n this.suppliedPool = options.pool;\n const connection = { ...options.options };\n refuseEmptyDatabaseUrl(\n \"pg\",\n options,\n Boolean(\n this.suppliedPool || connection.host || connection.connectionString\n )\n );\n this.connectionOptions = connectionRecord(connection, options.databaseUrl);\n\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n\n installPostgresAdapter(this, namespace, options);\n this.readsServer =\n this.suppliedPool === undefined &&\n connection.Client === undefined &&\n boundByServer(this.adapter, () => this.serverVersion);\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's pool connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const supplied: unknown = this.suppliedPool\n ? Reflect.get(this.suppliedPool, \"options\")\n : undefined;\n const pool =\n typeof supplied === \"object\" && supplied !== null ? supplied : {};\n return [\n this.connectionOptions.host,\n this.connectionOptions.connectionString,\n Reflect.get(pool, \"host\"),\n Reflect.get(pool, \"connectionString\"),\n ];\n }\n\n /**\n * The pool this driver connects through.\n *\n * A caller's pool is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second pool behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n *\n * It is also returned UNSUBSCRIBED. A supplied pool is borrowed transport and\n * its events belong to its owner: an 'error' listener added here is the very\n * thing that stops Node from throwing, so VibORM would be silencing a crash\n * for a caller who never asked it to — and for the other consumers of a pool\n * two estates share. This driver listens only on the pool it made.\n */\n protected initClient(): Promise<PgPool> {\n if (this.suppliedPool !== undefined) {\n return Promise.resolve(this.suppliedPool);\n }\n const pool = new Pool({\n types: utcSafeTypes,\n ...this.connectionOptions,\n ...(this.readsServer ? { Client: this.readingClient() } : {}),\n });\n const errorState = createOwnedPoolErrorState();\n this.ownedPoolErrors.set(pool, errorState);\n pool.on(\"error\", errorState.retain);\n return Promise.resolve(pool);\n }\n\n /**\n * node-postgres's `Client`, reading each connection's startup: it keeps no\n * parameter status, so the `server_version` that names Neki is read as it\n * arrives, before the connection is handed out (to a statement, or to a\n * transaction before its callback builds any).\n */\n private readingClient(): typeof Client {\n const read = (version: string) => {\n this.serverVersion = version;\n };\n return class extends Client {\n constructor(config?: string | ClientConfig) {\n super(config);\n this.connection.on(\n \"parameterStatus\",\n (status: { parameterName: string; parameterValue: string }) => {\n if (status.parameterName === \"server_version\")\n read(status.parameterValue);\n }\n );\n }\n };\n }\n\n private readBackgroundPoolFailure(\n pool: PgPool | PgPoolClient\n ): BackgroundPoolFailure | undefined {\n return this.ownedPoolErrors.get(pool)?.backgroundFailure;\n }\n\n /** Clear exactly the failure observed before an operation started. */\n private clearBackgroundPoolFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n ): boolean {\n if (observed === undefined || !observed.isAvailable) return false;\n observed.isAvailable = false;\n const state = this.ownedPoolErrors.get(pool);\n if (state?.backgroundFailure?.generation === observed.generation) {\n state.backgroundFailure = undefined;\n }\n return true;\n }\n\n /** Claim one retained failure for one failed acquisition, at most once. */\n private consumeBackgroundPoolFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n ): Error | undefined {\n if (!this.clearBackgroundPoolFailure(pool, observed)) return undefined;\n return observed?.error;\n }\n\n /** Surface one pool-owned idle failure beside one pool query failure. */\n private throwPoolQueryFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined,\n error: unknown,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined\n ): never {\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const queryFailure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n model: context?.model,\n operation: context?.operation,\n correlationId: context?.correlationId,\n query: sql,\n params: this.getDiagnosticParameters(params ?? [], context),\n diagnostics: this.getErrorDisclosure(context),\n forceContext: true,\n });\n throw withSuppressedFailure(queryFailure, background);\n }\n\n /**\n * One pooled connection, and — when there is none to be had — the current\n * acquisition failure as primary, with the pool's last background failure\n * retained beside it.\n *\n * The acquisition rejection is the failure of the requested action, so it\n * stays primary. The background report arrived outside every request and is\n * retained through the shared suppressed-failure record. Reported once and\n * released, so the next failure speaks for itself rather than inheriting an\n * explanation that has already been given. An acquisition that fails with\n * nothing retained is left exactly as it was.\n */\n private async acquirePooledClient(\n pool: PgPool,\n context: QueryExecutionContext = {},\n maxWaitMs?: number\n ): Promise<PgPoolClient> {\n const observed = this.readBackgroundPoolFailure(pool);\n let acquisitionSettled = false;\n try {\n const client = await acquireWithMaxWait(\n async () => {\n try {\n const acquired = await pool.connect();\n // This runs even when maxWait has already rejected the caller: a\n // late success healed the pre-start failure before the abandoned\n // client goes straight back to the pool.\n this.clearBackgroundPoolFailure(pool, observed);\n return acquired;\n } finally {\n acquisitionSettled = true;\n }\n },\n (acquired) => acquired.release(),\n maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n return client;\n } catch (error) {\n // A maxWait winner abandons the acquisition. Its eventual rejection is\n // observed by acquireWithMaxWait, but it must not consume evidence into\n // a promise whose result no caller will ever inspect.\n if (!acquisitionSettled) throw error;\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const acquisitionFailure = normalizeDriverConnectionError(\n error,\n {\n driverName: this.driverName,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n diagnostics: this.getErrorDisclosure(context),\n },\n \"Database connection failed after the pool reported a background failure\"\n );\n throw withSuppressedFailure(acquisitionFailure, background);\n }\n }\n\n /**\n * A supplied pool belongs to the caller, who may be sharing it with other\n * clients — two schema-scoped estates over one pool is the documented shape\n * — and §5.3's rule is that VibORM never changes a caller's connection\n * state. `$disconnect()` used to end it regardless, so disconnecting one\n * client tore down every other consumer of that pool.\n *\n * The test is on the pool's IDENTITY against what construction captured, so\n * it answers for the pool actually being closed rather than for whatever the\n * caller's record says now: every pool this driver made is ended, and the one\n * it was handed never is.\n */\n protected async closeClient(pool: PgPool): Promise<void> {\n if (pool === this.suppliedPool) {\n return;\n }\n const errorState = this.ownedPoolErrors.get(pool);\n try {\n await pool.end();\n } catch (error) {\n const background = this.consumeBackgroundPoolFailure(\n pool,\n errorState?.backgroundFailure\n );\n if (background === undefined) throw error;\n const disconnectFailure = normalizeDriverConnectionError(\n error,\n { driverName: this.driverName },\n \"Database disconnection failed\"\n );\n throw withSuppressedFailure(disconnectFailure, background);\n }\n // The pool keeps its listener for good. `end()` resolves once it has told\n // its idle clients to close, not once their sockets have: pg's idle\n // listener on each still re-emits on the pool what the server says on the\n // way out, a terminated backend or a shutdown, after this has returned.\n // Nothing reads it any more, and nothing throws it.\n if (errorState !== undefined) {\n errorState.backgroundFailure = undefined;\n this.ownedPoolErrors.delete(pool);\n }\n }\n\n protected async execute<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"execute\");\n }\n\n protected async executeRaw<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const observed = this.readBackgroundPoolFailure(client);\n const result = await client\n .query({ text: sql, values: params, types: utcSafeTypes })\n .catch((error: unknown) => {\n learnRelationLimit(this.adapter, error);\n return this.throwPoolQueryFailure(\n client,\n observed,\n error,\n sql,\n params,\n context\n );\n });\n // `Pool.query` includes an acquisition. Its success proves transport\n // recovery, but only for evidence that predates this exact operation.\n this.clearBackgroundPoolFailure(client, observed);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n { provider: \"pg\", operation }\n ),\n };\n }\n\n /**\n * PostgreSQL takes the isolation level as the first statement inside the\n * transaction, and node-postgres hands out a pooled client we can wait for\n * with a bound (and release if we stop waiting).\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: PgPool | PgPoolClient,\n fn: (tx: PgPoolClient) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction\n const poolClient = await this.acquirePooledClient(\n client,\n context,\n options?.maxWaitMs\n );\n const clientErrors = holdClientErrors(poolClient);\n // A step's own failure stays primary; a different client failure travels\n // beside it through the shared evidence owner instead of being lost.\n const withClientFailure = (error: unknown): unknown => {\n const failure = clientErrors.failure();\n return failure === undefined || failure === error\n ? error\n : withSuppressedFailure(error, failure);\n };\n let releaseError: Error | boolean | undefined;\n const queryOrDiscard = async (statement: string) => {\n try {\n await poolClient.query(statement);\n } catch (error) {\n releaseError ??= error instanceof Error ? error : true;\n throw withClientFailure(error);\n }\n };\n return runTransactionLifecycle({\n begin: () => queryOrDiscard(\"BEGIN\"),\n callback: async () => {\n try {\n return await fn(poolClient);\n } catch (error) {\n throw withClientFailure(error);\n }\n },\n commit: () => {\n // A callback that settles after its connection failed must not commit:\n // whatever it awaited meanwhile never reached the database.\n const failure = clientErrors.failure();\n if (failure !== undefined) throw failure;\n return queryOrDiscard(\"COMMIT\");\n },\n // The server ends a transaction with its session; a ROLLBACK sent on a\n // client that is no longer queryable would only add a second failure.\n rollback: () =>\n clientErrors.failure() === undefined\n ? queryOrDiscard(\"ROLLBACK\")\n : undefined,\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n const discard = releaseError ?? clientErrors.failure();\n if (discard) {\n poolClient.release(discard);\n return;\n }\n poolClient.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"pg\" could not release an unsafe transaction connection.',\n { meta: { driver: \"pg\", method: \"$transaction\" } }\n )\n );\n throw error;\n } finally {\n clientErrors.stop();\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // The failed PoolClient was discarded with release(error); the pool stays usable.\n }\n\n /**\n * One `PoolClient` from `pool.connect()` — plan §3.5's pinned producer for\n * `pg`. `release(true)` destroys the connection instead of returning it, so a\n * session whose advisory-lock state is unknown never re-enters the pool.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PgPool | PgPoolClient>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const poolClient = await this.acquirePooledClient(client, {\n operation: \"pinnedSession\",\n });\n const clientErrors = holdClientErrors(poolClient);\n return {\n session: poolClient,\n // The client's own `error` event is how pg reports a socket that died\n // between or under statements; the pinned session then sends nothing\n // more on it (plan S2). Release destroys it either way.\n lost: clientErrors.failure,\n release: (discard) => {\n try {\n poolClient.release(\n clientErrors.failure() ?? (discard ? true : undefined)\n );\n } finally {\n clientErrors.stop();\n }\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PgClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PgDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: PgDriver }>]: LinkedClientConfig<\n C & { driver: PgDriver }\n >[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pg\", PG_CONFIG_KEYS);\n const { pool, options = {}, pgvector, postgis, databaseUrl } = config;\n const driver = new PgDriver({\n // Namespace, then attestation: the order a refusal reports in.\n namespace: resolveNamespaceOption(config),\n migrationSessionAttestation:\n resolveMigrationSessionAttestationOption(config),\n // Only a supplied pool counts: a falsy one leaves the driver to build its own.\n pool: pool || undefined,\n options,\n // Present even when undefined: the driver refuses an empty one (parity-18).\n ...(Object.hasOwn(config, \"databaseUrl\") ? { databaseUrl } : {}),\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n });\n\n return createClientFromDriverConfig<S, C, PgDriver>(config, driver);\n}\n"],"mappings":"qlBAoEA,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,QAAS,OAAO,CACnB,CACL,YAAe,EACf,SAAY,CACV,EAAO,IAAI,QAAS,OAAO,EAE9B,CAIH,MAAM,EAAiB,IAAI,IAAI,CAAC,OAAQ,WAAY,OAAQ,OAAO,CAAC,CAE9D,EAAe,CAAC,UAAW,UAAW,SAAU,cAAc,CAiBpE,SAAS,iBACP,EACA,EACY,CACZ,IAAM,EAAQ,EAAQ,kBAAoB,EAC1C,GAAI,CAAC,EAAO,OAAO,EACnB,GAAI,OAAO,EAAQ,UAAa,WAC9B,MAAM,IAAI,EACR,+KACA,CAAE,KAAM,CAAE,O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B,GAAI,CACF,EAAW,QACT,EAAa,SAAS,GAAK,EAAU,GAAO,IAAA,IAC7C,QACO,CACR,EAAa,MAAM,CAErB,OAAO,QAAQ,SAAS,EAE3B,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,KAAM,EAAe,CAC3D,GAAM,CAAE,OAAM,UAAU,EAAE,CAAE,WAAU,UAAS,eAAgB,EAiB/D,OAAO,EAA6C,EAhBrC,IAAI,SAAS,CAE1B,UAAW,EAAuB,EAAO,CACzC,4BACE,EAAyC,EAAO,CAElD,KAAM,GAAQ,IAAA,GACd,UAEA,GAAI,OAAO,OAAO,EAAQ,cAAc,CAAG,CAAE,cAAa,CAAG,EAAE,CAC/D,WACA,UACA,qBAAsB,EAAO,qBAC7B,sBAAuB,EAAO,sBAC/B,CAAC,CAEiE"}
|
|
1
|
+
{"version":3,"file":"pg.mjs","names":[],"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 type { Sql } from \"@sql\";\nimport {\n Client,\n type ClientConfig,\n Pool,\n type PoolClient,\n type PoolConfig,\n types as pgTypes,\n} from \"pg\";\nimport {\n type AnyDriver,\n Driver,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n driverErrorContext,\n getDiagnosticParameters,\n} from \"../driver-instrumentation\";\nimport {\n normalizeDriverConnectionError,\n normalizeDriverError,\n} from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport { assertNormalizedQueryResult } from \"../normalized-result\";\nimport {\n assertPositionalRows,\n type ProjectionExecutionResult,\n registerPositionalResultDriver,\n} from \"../positional-result\";\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 {\n isStaleStatement,\n type NamedStatements,\n type NamedStatementsOption,\n namedStatements,\n} from \"../shared/named-statements\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport { boundByServer, learnRelationLimit } from \"../shared/relation-bound\";\nimport type { QueryResult } from \"../types\";\n\n// DATE (1082) and TIMESTAMP WITHOUT TIME ZONE (1114): pg's default parsers\n// build process-local Dates, shifting the stored value by the process\n// timezone. Return the raw strings instead — the shared result parser builds\n// UTC Dates from them, matching every other driver.\nconst DATE_OID = 1082;\nconst TIMESTAMP_OID = 1114;\nconst identityParser = (value: string) => value;\nconst utcSafeTypes: PoolConfig[\"types\"] = {\n getTypeParser: (oid: number, format?: string) => {\n if (\n [DATE_OID, TIMESTAMP_OID, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return pgTypes.getTypeParser(oid as never, format as never);\n },\n};\n\ninterface BackgroundPoolFailure {\n readonly e: Error;\n readonly g: number;\n a: boolean;\n}\n\ninterface OwnedPoolErrorState {\n f?: BackgroundPoolFailure;\n readonly r: (error: Error) => void;\n}\n\nfunction createOwnedPoolErrorState(): OwnedPoolErrorState {\n let generation = 0;\n const state: OwnedPoolErrorState = {\n r(error) {\n generation += 1;\n state.f = { e: error, g: generation, a: true };\n },\n };\n return state;\n}\n\ninterface HeldClientErrors {\n readonly f: () => Error | undefined;\n readonly s: () => 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 f: () => failure,\n s: () => {\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\": password callback conflicts with URL.',\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('Driver \"pg\": invalid URL.', {\n meta: { driver: \"pg\", operation: \"configuration\" },\n });\n }\n for (const [key, value] of overrides) {\n url.searchParams.delete(key);\n if (key === \"ssl\") {\n for (const sslKey of URL_SSL_KEYS) url.searchParams.delete(sslKey);\n } else if (key === \"database\") {\n url.pathname = `/${String(value)}`;\n } else if (\n URL_QUERY_KEYS.has(key) &&\n (typeof value === \"string\" || typeof value === \"number\")\n ) {\n url.searchParams.set(key, String(value));\n }\n }\n return { ...options, connectionString: url.href };\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PoolConfig as PgOptions } from \"pg\";\n\ninterface PgErrorEvents {\n on(event: \"error\", listener: (error: Error) => void): unknown;\n off(event: \"error\", listener: (error: Error) => void): unknown;\n}\n\n/** The part of a node-postgres `PoolClient` this driver uses. */\ninterface PgPoolClient\n extends Pick<PoolClient, \"query\" | \"release\">,\n PgErrorEvents {}\n\n/**\n * The part of a node-postgres `Pool` this driver uses, so any pool with that\n * shape is accepted. A Neon WebSocket `Pool` (`@neondatabase/serverless`) is\n * node-postgres's pool over a WebSocket and runs here unchanged, but its\n * bundled copy of the pg declarations lags `@types/pg`: in 8.23 a\n * `PoolClient` is a whole `Client`, and the full `Pool` type refused Neon's.\n */\ninterface PgPool extends Pick<Pool, \"query\" | \"end\">, PgErrorEvents {\n connect(): Promise<PgPoolClient>;\n}\n\nexport interface PgDriverOptions {\n pool?: PgPool;\n options?: PoolConfig;\n pgvector?: boolean;\n postgis?: boolean;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Each relation filter body a statement repeats is stated once, in a\n * `WITH`, as the key set its arms test: the answers are the same, the\n * statement smaller, and a server that bounds the relations one statement\n * references (PlanetScale's Neki: 256) accepts it. Defaults to `true`;\n * `false` keeps every body inline.\n */\n sharedRelationBodies?: boolean;\n /**\n * The most relations (`FROM` items) one statement may reference. Past it, a\n * statement states the recursive filters it repeats as key sets, and then\n * joins the key sets a row tests, as far as it needs to fit: the answers are\n * the same, some plans slower. PlanetScale Neki refuses a statement over\n * 256: absent, a pool this driver makes reads each connection's startup,\n * 256 on Neki and before the first connection, none on plain PostgreSQL (a\n * supplied pool learns from Neki's first refusal). A stated bound always\n * wins. Only where relation bodies are shared.\n */\n relationsPerStatement?: number;\n /**\n * Your claim, at your risk, that every connection this pool opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n /**\n * Send statements as named, server-side prepared statements: each\n * connection parses and plans one once, then only binds it. With `true`\n * (`{ max: 100, auto: true }`) a statement is named the second time it is\n * sent; with `\"explicit\"` (`{ max: 100, auto: false }`) only the statements\n * of a call that passes `named: true` are. A call's `named: true` names its\n * statements at their first sending, `named: false` never. A connection\n * holds at most `max` of them. Off by default: behind PgBouncer in\n * transaction mode, set `max_prepared_statements` first.\n */\n namedStatements?: NamedStatementsOption;\n}\n\nexport type PgClientConfig<C extends DriverConfig> = PgDriverOptions & C;\n\nconst PG_CONFIG_KEYS: Record<keyof PgDriverOptions, true> = {\n pool: true,\n options: true,\n pgvector: true,\n postgis: true,\n databaseUrl: true,\n namespace: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n migrationSessionAttestation: true,\n namedStatements: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\ninterface PgState {\n readonly p: PgPool | undefined;\n readonly c: PoolConfig;\n readonly e: WeakMap<object, OwnedPoolErrorState>;\n v: string | undefined;\n r: boolean;\n readonly n: NamedStatements | undefined;\n}\n\nfunction readingPgClient(state: PgState): typeof Client {\n return class extends Client {\n constructor(config?: string | ClientConfig) {\n super(config);\n this.connection.on(\n \"parameterStatus\",\n (status: { parameterName: string; parameterValue: string }) => {\n if (status.parameterName === \"server_version\")\n state.v = status.parameterValue;\n }\n );\n }\n };\n}\n\nfunction readPoolFailure(\n state: PgState,\n pool: PgPool | PgPoolClient\n): BackgroundPoolFailure | undefined {\n return state.e.get(pool)?.f;\n}\n\nfunction clearPoolFailure(\n state: PgState,\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n): boolean {\n if (!observed?.a) return false;\n observed.a = false;\n const entry = state.e.get(pool);\n if (entry?.f?.g === observed.g) entry.f = undefined;\n return true;\n}\n\nfunction consumePoolFailure(\n state: PgState,\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n): Error | undefined {\n return clearPoolFailure(state, pool, observed) ? observed?.e : undefined;\n}\n\nfunction failPgSend(\n driver: PgDriver,\n client: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined,\n error: unknown,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined\n): never {\n learnRelationLimit(driver.adapter, error);\n const background = consumePoolFailure(driver[\"_p\"], client, observed);\n if (background === undefined) throw error;\n const queryFailure = normalizeDriverError(error, {\n ...driverErrorContext(driver, context, true),\n query: sql,\n params: getDiagnosticParameters(params ?? [], context),\n forceContext: true,\n });\n throw withSuppressedFailure(queryFailure, background);\n}\n\nasync function sendPg(\n driver: PgDriver,\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\",\n array: boolean\n) {\n const state = driver[\"_p\"];\n const observed = readPoolFailure(state, client);\n const name =\n fallbackOperation === \"execute\" &&\n params?.length &&\n context?.model !== \"$raw\"\n ? state.n?.name(sql, context?.named)\n : undefined;\n const query = array\n ? { text: sql, values: params, types: utcSafeTypes, rowMode: \"array\" }\n : { text: sql, values: params, types: utcSafeTypes };\n const sent = client.query(name === undefined ? query : { ...query, name });\n const fail = (err: unknown): never =>\n failPgSend(driver, client, observed, err, sql, params, context);\n let result: Awaited<typeof sent>;\n try {\n result = await sent;\n } catch (error) {\n if (name === undefined || !isStaleStatement(error)) return fail(error);\n state.n?.retire(sql);\n if (\"release\" in client) return fail(error);\n try {\n result = await client.query(query);\n } catch (failure) {\n return fail(failure);\n }\n }\n clearPoolFailure(state, client, observed);\n return result;\n}\n\nasync function executePgQuery<T>(\n driver: PgDriver,\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 result = await sendPg(\n driver,\n client,\n sql,\n params,\n context,\n fallbackOperation,\n false\n );\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\nasync function acquirePgClient(\n driver: PgDriver,\n pool: PgPool,\n context: QueryExecutionContext = {},\n maxWaitMs?: number\n): Promise<PgPoolClient> {\n const state = driver[\"_p\"];\n const observed = readPoolFailure(state, pool);\n let acquisitionSettled = false;\n try {\n return await acquireWithMaxWait(\n async () => {\n try {\n const acquired = await pool.connect();\n clearPoolFailure(state, pool, observed);\n return acquired;\n } finally {\n acquisitionSettled = true;\n }\n },\n (acquired) => acquired.release(),\n maxWaitMs,\n { driverName: driver.driverName, form: \"callback\" }\n );\n } catch (error) {\n if (!acquisitionSettled) throw error;\n const background = consumePoolFailure(state, pool, observed);\n if (background === undefined) throw error;\n const acquisitionFailure = normalizeDriverConnectionError(\n error,\n driverErrorContext(driver, context),\n \"Connection failed after pool error\"\n );\n throw withSuppressedFailure(acquisitionFailure, background);\n }\n}\n\nexport class PgDriver extends Driver<PgPool, PgPoolClient> {\n static readonly #executeEntry = PgDriver.prototype._execute;\n static readonly #execute = PgDriver.prototype.execute;\n static readonly #typedStatement = PgDriver.prototype.executeTypedStatement;\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n private readonly _p: PgState;\n /** The adapter and its parsers as installed, which positional rows require. */\n readonly #installed: readonly unknown[];\n\n constructor(options: PgDriverOptions = {}) {\n super(\"postgresql\", \"pg\");\n const namespace = resolveNamespaceOption(options);\n const suppliedPool = options.pool;\n const connection = { ...options.options };\n refuseEmptyDatabaseUrl(\n \"pg\",\n options,\n Boolean(suppliedPool || connection.host || connection.connectionString)\n );\n const state: PgState = {\n p: suppliedPool,\n c: connectionRecord(connection, options.databaseUrl),\n e: new WeakMap(),\n v: undefined,\n r: false,\n n: namedStatements(\"pg\", options.namedStatements),\n };\n this._p = state;\n\n if (suppliedPool) {\n this.client = suppliedPool;\n }\n\n installPostgresAdapter(this, namespace, options);\n this.#installed = PgDriver.#surface(this);\n registerPositionalResultDriver(\n this,\n (query, context) => this.#executePositional(query, context),\n PgDriver.isPositionalCandidate\n );\n state.r =\n suppliedPool === undefined &&\n connection.Client === undefined &&\n boundByServer(this.adapter, () => state.v);\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 state = this._p;\n const supplied: unknown = state.p\n ? Reflect.get(state.p, \"options\")\n : undefined;\n const pool =\n typeof supplied === \"object\" && supplied !== null ? supplied : {};\n return [\n state.c.host,\n state.c.connectionString,\n Reflect.get(pool, \"host\"),\n Reflect.get(pool, \"connectionString\"),\n ];\n }\n\n protected initClient(): Promise<PgPool> {\n const state = this._p;\n if (state.p !== undefined) {\n return Promise.resolve(state.p);\n }\n const pool = new Pool({\n types: utcSafeTypes,\n ...state.c,\n ...(state.r ? { Client: readingPgClient(state) } : {}),\n });\n const errorState = createOwnedPoolErrorState();\n state.e.set(pool, errorState);\n pool.on(\"error\", errorState.r);\n return Promise.resolve(pool);\n }\n\n protected async closeClient(pool: PgPool): Promise<void> {\n const state = this._p;\n if (pool === state.p) {\n return;\n }\n const errorState = state.e.get(pool);\n try {\n await pool.end();\n } catch (error) {\n const background = consumePoolFailure(state, pool, errorState?.f);\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 if (errorState !== undefined) {\n errorState.f = undefined;\n state.e.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 executePgQuery(this, 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 executePgQuery(this, client, sql, params, context, \"executeRaw\");\n }\n\n /**\n * A collection read as positional rows: node-postgres's `rowMode: \"array\"`\n * hands each row over as the array it parsed, and the columns once, instead\n * of building an object keyed by every column name for every row.\n */\n #executePositional(\n query: Sql,\n context: QueryExecutionContext\n ): Promise<ProjectionExecutionResult> {\n return this.executeTypedStatement(\n query,\n context,\n async (\n client,\n sql,\n params,\n executionContext\n ): Promise<ProjectionExecutionResult> => {\n const resultContext = {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n };\n if (!PgDriver.isPositionalCandidate(this)) {\n const result = await this.execute<unknown>(\n client,\n sql,\n params,\n executionContext\n );\n assertNormalizedQueryResult(result, resultContext);\n return { kind: \"borrowed\", result };\n }\n const result = await sendPg(\n this,\n client,\n sql,\n params,\n executionContext,\n \"execute\",\n true\n );\n const rows: unknown[] = result.rows;\n if (rows.length > 0 && !Array.isArray(rows[0])) {\n const borrowed = { rows, rowCount: rows.length };\n assertNormalizedQueryResult(borrowed, resultContext);\n return { kind: \"borrowed\", result: borrowed };\n }\n const columns = result.fields.map((field) => field.name);\n assertPositionalRows(rows, columns, resultContext);\n return { kind: \"positional\", rows, columns };\n }\n );\n }\n\n private static isPositionalCandidate(driver: AnyDriver): boolean {\n if (!(driver instanceof PgDriver)) return false;\n const installed = driver.#installed;\n const { adapter } = driver;\n const { result } = adapter;\n return (\n Object.getPrototypeOf(driver) === PgDriver.prototype &&\n driver._execute === PgDriver.#executeEntry &&\n driver.execute === PgDriver.#execute &&\n driver.executeTypedStatement === PgDriver.#typedStatement &&\n driver.result === undefined &&\n installed[0] === adapter &&\n installed[1] === result &&\n installed[2] === result.parseField &&\n installed[3] === result.parseRelation &&\n installed[4] === result.parseResult\n );\n }\n\n /** The adapter and the parsers positional rows are decoded by. */\n static #surface(driver: PgDriver): readonly unknown[] {\n const { adapter } = driver;\n const { result } = adapter;\n return [\n adapter,\n result,\n result.parseField,\n result.parseRelation,\n result.parseResult,\n ];\n }\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 acquirePgClient(\n this,\n client,\n context,\n options?.maxWaitMs\n );\n const clientErrors = holdClientErrors(poolClient);\n const withClientFailure = (error: unknown): unknown => {\n const failure = clientErrors.f();\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 const failure = clientErrors.f();\n if (failure !== undefined) throw failure;\n return queryOrDiscard(\"COMMIT\");\n },\n rollback: () =>\n clientErrors.f() === undefined ? queryOrDiscard(\"ROLLBACK\") : undefined,\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n const discard = releaseError ?? clientErrors.f();\n if (discard) {\n poolClient.release(discard);\n return;\n }\n poolClient.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError('Driver \"pg\": tx release failed.', {\n meta: { driver: \"pg\", method: \"$transaction\" },\n })\n );\n throw error;\n } finally {\n clientErrors.s();\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 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 acquirePgClient(this, client, {\n operation: \"pinnedSession\",\n });\n const clientErrors = holdClientErrors(poolClient);\n return {\n session: poolClient,\n lost: clientErrors.f,\n release: (discard) => {\n try {\n poolClient.release(clientErrors.f() ?? (discard ? true : undefined));\n } finally {\n clientErrors.s();\n }\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PgClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PgDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: PgDriver }>]: LinkedClientConfig<\n C & { driver: PgDriver }\n >[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pg\", PG_CONFIG_KEYS);\n const { pool, options = {}, pgvector, postgis, databaseUrl } = config;\n const driver = new PgDriver({\n // Namespace, then attestation: the order a refusal reports in.\n namespace: resolveNamespaceOption(config),\n migrationSessionAttestation:\n resolveMigrationSessionAttestationOption(config),\n // Only a supplied pool counts: a falsy one leaves the driver to build its own.\n pool: pool || undefined,\n options,\n // Present even when undefined: the driver refuses an empty one (parity-18).\n ...(Object.hasOwn(config, \"databaseUrl\") ? { databaseUrl } : {}),\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n namedStatements: config.namedStatements,\n });\n\n return createClientFromDriverConfig<S, C, PgDriver>(config, driver);\n}\n"],"mappings":"wrBAsFA,MAEM,EAAkB,GAAkB,EACpC,EAAoC,CACxC,eAAgB,EAAa,IAEzB,CAAC,KAAU,KAAe,KAAM,KAAM,KAAM,KAAK,CAAC,SAAS,EAAI,EAC/D,IAAW,SAEJ,EAEF,EAAQ,cAAc,EAAc,EAAgB,CAE9D,CAaD,SAAS,GAAiD,CACxD,IAAI,EAAa,EACX,EAA6B,CACjC,EAAE,EAAO,CACP,GAAc,EACd,EAAM,EAAI,CAAE,EAAG,EAAO,EAAG,EAAY,EAAG,GAAM,EAEjD,CACD,OAAO,EAQT,SAAS,EAAiB,EAAwC,CAChE,IAAI,EACE,EAAU,GAAiB,CAC/B,IAAY,GAGd,OADA,EAAO,GAAG,QAAS,EAAO,CACnB,CACL,MAAS,EACT,MAAS,CACP,EAAO,IAAI,QAAS,EAAO,EAE9B,CAIH,MAAM,EAAiB,IAAI,IAAI,CAAC,OAAQ,WAAY,OAAQ,OAAO,CAAC,CAE9D,EAAe,CAAC,UAAW,UAAW,SAAU,cAAc,CAiBpE,SAAS,EACP,EACA,EACY,CACZ,IAAM,EAAQ,EAAQ,kBAAoB,EAC1C,GAAI,CAAC,EAAO,OAAO,EACnB,GAAI,OAAO,EAAQ,UAAa,WAC9B,MAAM,IAAI,EACR,qDACA,CAAE,KAAM,CAAE,OAAQ,KAAM,UAAW,gBAAiB,CAAC,CACtD,CAEH,IAAM,EAAmB,EAAuB,EAAM,CAClD,EACJ,GAAI,CACF,EAAM,IAAI,IAAI,EAAiB,MACzB,CACN,EAAM,IAAA,GAGR,IAAM,EAD+B,OAAO,QAA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
|
|
1
|
+
import { $a as QueryExecutionContext, Di as LinkedClientConfig, Gr as Schema, Ja as TransactionOptionSupport, S as PinnedSessionReservation, eo as QueryResult, h as Driver, pt as VibORMClient, st as DriverConfig, t as DatabaseAdapter, ut as NoExtraDriverConfigKeys } from "./database-adapter-BMjJiBFm.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
|
|
@@ -18,6 +18,7 @@ interface PGliteDriverOptions {
|
|
|
18
18
|
}
|
|
19
19
|
type PGliteConfig<C extends DriverConfig> = PGliteDriverOptions & C;
|
|
20
20
|
declare class PGliteDriver extends Driver<PGlite, Transaction> {
|
|
21
|
+
#private;
|
|
21
22
|
readonly adapter: DatabaseAdapter;
|
|
22
23
|
readonly maxBindParametersPerStatement: number | undefined;
|
|
23
24
|
protected readonly serializeTransactions = true;
|
|
@@ -54,6 +55,7 @@ declare class PGliteDriver extends Driver<PGlite, Transaction> {
|
|
|
54
55
|
protected execute<T>(client: PGlite | Transaction, sql: string, params: unknown[], context?: QueryExecutionContext): Promise<QueryResult<T>>;
|
|
55
56
|
protected executeRaw<T>(client: PGlite | Transaction, sql: string, params: unknown[] | undefined, context?: QueryExecutionContext): Promise<QueryResult<T>>;
|
|
56
57
|
private executeQuery;
|
|
58
|
+
private static isPositionalCandidate;
|
|
57
59
|
/**
|
|
58
60
|
* PGlite is a full PostgreSQL, so the isolation level is a real post-BEGIN
|
|
59
61
|
* statement. It is also single-connection, so top-level transactions queue —
|
package/dist/pglite.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{B as e,f as t,u as n}from"./error-mapping-B9rSvgG9.mjs";import{p as r}from"./validation-ATmgN5RE.mjs";import{n as i,o as a,r as o}from"./normalized-result-D7nVkF36.mjs";import{f as s,n as c,u as l}from"./client-D7sWgUt2.mjs";import{a as u,n as d}from"./pinned-session-Y7-2pRBJ.mjs";import{h as f,o as p,r as m,v as h}from"./driver-lShUkDmf.mjs";import{t as g}from"./postgres-adapter-BpLizOaK.mjs";import{PGlite as _}from"@electric-sql/pglite";const v=Object.freeze(Object.fromEntries([1082,1114,1184,1115,1182,1185].map(e=>[e,e=>e]))),y={client:!0,dataDir:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,namespace:!0};function b(e){return`transaction`in e}var x=class c extends m{static get name(){return`PGliteDriver`}static#e=c.prototype._execute;static#t=c.prototype.execute;static#n=c.prototype.executeTypedStatement;maxBindParametersPerStatement=32767;serializeTransactions=!0;eg;#r;eb;constructor(e={}){super(`postgresql`,`pglite`);let t=h(e);this.eg=e,this.eb=e.client,this.eb&&(this.client=this.eb,Object.defineProperty(this,`connectionQueue`,{value:p(this.eb)})),g(this,t,e),this.#r=c.#a(this),s(this,(e,t)=>this.#i(e,t),c.nl)}async initClient(){if(this.eb!==void 0)return this.eb;let e=this.eg.dataDir,t=this.eg.options??{},n={...t,parsers:{1114:e=>e,...t.parsers}};return e?await _.create(e,n):await _.create(n)}async closeClient(e){e!==this.eb&&await e.close()}async execute(e,t,n,r){return this.pw(e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return this.pw(e,t,n,r,`executeRaw`)}async pw(e,t,n,r,i){let o=r?.operation??i,s=await e.query(t,n,{parsers:v}),c=a(s.affectedRows,{provider:`pglite`,operation:o});return{rows:s.rows,rowCount:s.rows.length>0?s.rows.length:c}}#i(e,t){return this.executeTypedStatement(e,t,async(e,t,n,s)=>{let u={provider:this.driverName,operation:s.operation??`execute`};if(!c.nl(this)){let r=await this.execute(e,t,n,s);return i(r,u),{kind:`borrowed`,result:r}}let d=await e.query(t,n,{parsers:v,rowMode:`array`}),f=a(d.affectedRows,u),p=d.rows;if(p.length>0&&!Array.isArray(p[0])){let e={rows:p,rowCount:p.length};return i(e,u),{kind:`borrowed`,result:e}}if(!Array.isArray(d.fields)){if(p.length===0)return{kind:`borrowed`,result:{rows:p,rowCount:f}};throw new r(`Driver "${u.provider}" malformed positional rows for "${u.operation}".`,{meta:o(u)})}let m=d.fields.map(e=>e.name);return l(p,m,u),{kind:`positional`,rows:p,columns:m}})}static nl(e){if(!(e instanceof c))return!1;let t=e.#r,{adapter:n}=e,{result:r}=n;return Object.getPrototypeOf(e)===c.prototype&&e._execute===c.#e&&e.execute===c.#t&&e.executeTypedStatement===c.#n&&e.result===void 0&&t[0]===n&&t[1]===r&&t[2]===r.parseField&&t[3]===r.parseRelation&&t[4]===r.parseResult}static#a(e){let{adapter:t}=e,{result:n}=t;return[t,n,n.parseField,n.parseRelation,n.parseResult]}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`queue`}}transaction(r,i,a){if(!b(r))throw n(this.driverName);return t({run:e=>r.transaction(e),callback:i,he:e(a),close:async()=>void 0})}async physicalPinnedSession(){return await this.getClient({operation:`pinnedSession`})}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!b(e))throw n(this.driverName);return{session:e,release:async t=>{if(t)try{await e.query(`SELECT pg_advisory_unlock_all()`)}catch(t){throw d(e),u(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 S(e){f(e,`pglite`,y);let{client:t,dataDir:n,options:r,pgvector:i,postgis:a}=e,o=h(e);return c(e,new x({client:t,dataDir:n,options:r,pgvector:i,postgis:a,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:o}))}export{x as PGliteDriver,S as createClient};
|
|
2
2
|
//# sourceMappingURL=pglite.mjs.map
|
package/dist/pglite.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pglite.mjs","names":[],"sources":["../src/drivers/pglite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\n/**\n * PGlite Driver\n *\n * Driver implementation for PGlite (PostgreSQL in WebAssembly).\n * Supports optional pgvector and PostGIS extensions.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n PGlite,\n type PGliteOptions,\n type Transaction,\n} from \"@electric-sql/pglite\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport { normalizeProviderRowCount } from \"../normalized-result\";\nimport {\n nestedTransactionDispatchError,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport {\n condemnPhysicalSession,\n type PinnedSessionReservation,\n unprovenLockStateError,\n} from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type { QueryResult } from \"../types\";\n\nconst temporalParsers = Object.fromEntries(\n [1082, 1114, 1184, 1115, 1182, 1185].map((oid) => [\n oid,\n (value: string) => value,\n ])\n);\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PGliteOptions } from \"@electric-sql/pglite\";\n\nexport interface PGliteDriverOptions {\n client?: PGlite;\n dataDir?: string;\n options?: PGliteOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. Set 256 for PlanetScale Neki, which refuses more. Absent: unbounded. Only where relation bodies are shared. */\n relationsPerStatement?: number;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type PGliteConfig<C extends DriverConfig> = PGliteDriverOptions & C;\n\nconst PGLITE_CONFIG_KEYS: Record<keyof PGliteDriverOptions, true> = {\n client: true,\n dataDir: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n namespace: true,\n};\n\n/**\n * The database, as opposed to a transaction handle, which has no `transaction`\n * method. Not `instanceof PGlite`: a PGlite built by another copy of\n * `@electric-sql/pglite` (its CommonJS build beside the ESM one, or a second\n * installed version) has another class, and every transaction and pinned\n * command on it used to fail as \"nested provider state\".\n */\nfunction isPGliteDatabase(client: PGlite | Transaction): client is PGlite {\n return \"transaction\" in client;\n}\n\n// === ======================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PGliteDriver extends Driver<PGlite, Transaction> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 32_767;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: PGliteDriverOptions;\n /**\n * The EXACT database the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's database while believing it had made its own.\n */\n private readonly suppliedClient: PGlite | undefined;\n\n constructor(options: PGliteDriverOptions = {}) {\n super(\"postgresql\", \"pglite\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n\n installPostgresAdapter(this, namespace, options);\n }\n\n /**\n * The database this driver runs on.\n *\n * A caller's database is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second, EMPTY in-memory PGlite behind their\n * back — a database they never asked for, holding none of their data, while\n * the one they handed over stayed open and unused.\n */\n protected async initClient(): Promise<PGlite> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const dataDir = this.driverOptions.dataDir;\n const userOptions = this.driverOptions.options ?? {};\n const options: PGliteOptions = {\n ...userOptions,\n parsers: {\n // TIMESTAMP WITHOUT TIME ZONE: PGlite builds process-local Dates,\n // shifting the stored UTC wall clock. Keep the raw string — the\n // shared result parser builds a UTC Date, matching other drivers.\n 1114: (value: string) => value,\n ...userOptions.parsers,\n },\n };\n\n // PGlite.create accepts dataDir as first argument or in options\n return dataDir\n ? await PGlite.create(dataDir, options)\n : await PGlite.create(options);\n }\n\n /**\n * A supplied database belongs to the caller, who may be running two\n * schema-scoped estates over it — the documented shape — and closing it here\n * would take the sibling's data down with this one's `$disconnect()`, on an\n * in-memory database for good.\n *\n * The test is on the client's IDENTITY against what construction captured, so\n * it answers for the database actually being closed rather than for whatever\n * the caller's record says now.\n */\n protected async closeClient(client: PGlite): Promise<void> {\n if (client === this.suppliedClient) {\n return;\n }\n await client.close();\n }\n\n protected async execute<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"execute\");\n }\n\n protected async executeRaw<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const result = await client.query<T>(sql, params, {\n parsers: temporalParsers,\n });\n const affectedRows = normalizeProviderRowCount(result.affectedRows, {\n provider: \"pglite\",\n operation,\n });\n return {\n rows: result.rows,\n rowCount: result.rows.length > 0 ? result.rows.length : affectedRows,\n };\n }\n\n /**\n * PGlite is a full PostgreSQL, so the isolation level is a real post-BEGIN\n * statement. It is also single-connection, so top-level transactions queue —\n * and that queue wait is exactly what `maxWait` bounds.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"queue\",\n };\n }\n\n protected transaction<T>(\n client: PGlite | Transaction,\n fn: (tx: Transaction) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n if (!isPGliteDatabase(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return runProviderManagedTransaction({\n run: (callback) => client.transaction(callback),\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n /**\n * The PGlite instance itself — the physical session a pinned command runs on.\n *\n * A caller may hand ONE PGlite to several drivers (two schema-scoped estates\n * over one database is the documented shape), and each of those drivers owns\n * its own connection queue. The client is what they all agree on, so it is\n * what serializes their pinned commands; without it the second command\n * re-acquires the reentrant session advisory lock the first is holding and\n * runs inside the first command's session.\n */\n protected override async physicalPinnedSession(): Promise<object> {\n return await this.getClient({ operation: \"pinnedSession\" });\n }\n\n /**\n * PGlite's single client, under the queue it already owns — plan §3.5's\n * pinned producer here. There is nothing to reserve and nothing to return:\n * one connection IS the session, which is exactly what a session lock needs.\n *\n * A condemned session can be neither destroyed nor abandoned: closing this\n * client closes the DATABASE, which for an in-memory one takes the caller's\n * data with it and for a supplied one is not VibORM's to do at all. So the\n * session is reset with `pg_advisory_unlock_all()`, and when that reset FAILS\n * the CLIENT is condemned instead — the subject of an unknown lock state is\n * the session, so the condemnation is recorded on it and refuses the next\n * pinned command through every driver over it. Ordinary queries keep working\n * — the data was never in doubt. Swallowing that reset failure was the\n * alternative, and it left the next migration command running inside a\n * session that may still hold the lock, on the one transport where the lock\n * is reentrant and would not stop it.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PGlite | Transaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!isPGliteDatabase(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return {\n session: client,\n release: async (discard) => {\n if (!discard) {\n return;\n }\n try {\n await client.query(\"SELECT pg_advisory_unlock_all()\");\n } catch (resetFailure) {\n condemnPhysicalSession(client);\n throw unprovenLockStateError(\n this.driverName,\n \"No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.\",\n resetFailure\n );\n }\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PGliteConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PGliteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PGliteDriver }\n >]: LinkedClientConfig<C & { driver: PGliteDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pglite\", PGLITE_CONFIG_KEYS);\n const { client, dataDir, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new PGliteDriver({\n client,\n dataDir,\n options,\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, PGliteDriver>(config, driver);\n}\n"],"mappings":"4ZAwCA,MAAM,EAAkB,OAAO,YAC7B,CAAC,KAAM,KAAM,KAAM,KAAM,KAAM,KAAK,CAAC,IAAK,GAAQ,CAChD,EACC,GAAkB,EACpB,CAAC,CACH,CAwBK,EAA8D,CAClE,OAAQ,GACR,QAAS,GACT,QAAS,GACT,SAAU,GACV,QAAS,GACT,qBAAsB,GACtB,sBAAuB,GACvB,UAAW,GACZ,CASD,SAAS,iBAAiB,EAAgD,CACxE,MAAO,gBAAiB,EAO1B,IAAa,aAAb,cAAkC,CAA4B,CAE5D,8BAA6D,MAC7D,sBAAoD,GAEpD,cAQA,eAEA,YAAY,EAA+B,EAAE,CAAE,CAC7C,MAAM,aAAc,SAAS,CAC7B,IAAM,EAAY,EAAuB,EAAQ,CACjD,KAAK,cAAgB,EACrB,KAAK,eAAiB,EAAQ,OAE1B,KAA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EAA8B,EAAQ,CAG9C,MAAO,SAAY,IAAA,GACpB,CAAC,CAaJ,MAAyB,uBAAyC,CAChE,OAAO,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CAoB7D,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,CAAC,iBAAiB,EAAO,CAC3B,MAAM,EAA+B,KAAK,WAAW,CAEvD,MAAO,CACL,QAAS,EACT,QAAS,KAAO,IAAY,CACrB,KAGL,GAAI,CACF,MAAM,EAAO,MAAM,kCAAkC,OAC9C,EAAc,CAErB,MADA,EAAuB,EAAO,CACxB,EACJ,KAAK,WACL,4KACA,EACD,GAGN,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,SAAU,EAAmB,CACnE,GAAM,CAAE,SAAQ,UAAS,UAAS,WAAU,WAAY,EAClD,EAAY,EAAuB,EAAO,CAahD,OAAO,EAAiD,EAXzC,IAAI,aAAa,CAC9B,SACA,UACA,UACA,WACA,UACA,qBAAsB,EAAO,qBAC7B,sBAAuB,EAAO,sBAC9B,YACD,CAAC,CAEqE"}
|
|
1
|
+
{"version":3,"file":"pglite.mjs","names":[],"sources":["../src/drivers/pglite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\n/**\n * PGlite Driver\n *\n * Driver implementation for PGlite (PostgreSQL in WebAssembly).\n * Supports optional pgvector and PostGIS extensions.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n PGlite,\n type PGliteOptions,\n type Transaction,\n} from \"@electric-sql/pglite\";\nimport { QueryError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport { type AnyDriver, Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n assertNormalizedQueryResult,\n createNormalizedResultMeta,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\nimport {\n assertPositionalRows,\n type ProjectionExecutionResult,\n registerPositionalResultDriver,\n} from \"../positional-result\";\nimport {\n nestedTransactionDispatchError,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport {\n condemnPhysicalSession,\n type PinnedSessionReservation,\n unprovenLockStateError,\n} from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type { QueryResult } from \"../types\";\n\nconst temporalParsers = Object.freeze(\n Object.fromEntries(\n [1082, 1114, 1184, 1115, 1182, 1185].map((oid) => [\n oid,\n (value: string) => value,\n ])\n )\n);\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PGliteOptions } from \"@electric-sql/pglite\";\n\nexport interface PGliteDriverOptions {\n client?: PGlite;\n dataDir?: string;\n options?: PGliteOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. Set 256 for PlanetScale Neki, which refuses more. Absent: unbounded. Only where relation bodies are shared. */\n relationsPerStatement?: number;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type PGliteConfig<C extends DriverConfig> = PGliteDriverOptions & C;\n\nconst PGLITE_CONFIG_KEYS: Record<keyof PGliteDriverOptions, true> = {\n client: true,\n dataDir: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n namespace: true,\n};\n\n/**\n * The database, as opposed to a transaction handle, which has no `transaction`\n * method. Not `instanceof PGlite`: a PGlite built by another copy of\n * `@electric-sql/pglite` (its CommonJS build beside the ESM one, or a second\n * installed version) has another class, and every transaction and pinned\n * command on it used to fail as \"nested provider state\".\n */\nfunction isPGliteDatabase(client: PGlite | Transaction): client is PGlite {\n return \"transaction\" in client;\n}\n\n// === ======================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PGliteDriver extends Driver<PGlite, Transaction> {\n static readonly #executeEntry = PGliteDriver.prototype._execute;\n static readonly #execute = PGliteDriver.prototype.execute;\n static readonly #typedStatement =\n PGliteDriver.prototype.executeTypedStatement;\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 32_767;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: PGliteDriverOptions;\n /** The adapter and its parsers as installed, which positional rows require. */\n readonly #installed: readonly unknown[];\n /**\n * The EXACT database the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's database while believing it had made its own.\n */\n private readonly suppliedClient: PGlite | undefined;\n\n constructor(options: PGliteDriverOptions = {}) {\n super(\"postgresql\", \"pglite\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n\n installPostgresAdapter(this, namespace, options);\n this.#installed = PGliteDriver.#surface(this);\n registerPositionalResultDriver(\n this,\n (query, context) => this.#executePositional(query, context),\n PGliteDriver.isPositionalCandidate\n );\n }\n\n /**\n * The database this driver runs on.\n *\n * A caller's database is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second, EMPTY in-memory PGlite behind their\n * back — a database they never asked for, holding none of their data, while\n * the one they handed over stayed open and unused.\n */\n protected async initClient(): Promise<PGlite> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const dataDir = this.driverOptions.dataDir;\n const userOptions = this.driverOptions.options ?? {};\n const options: PGliteOptions = {\n ...userOptions,\n parsers: {\n // TIMESTAMP WITHOUT TIME ZONE: PGlite builds process-local Dates,\n // shifting the stored UTC wall clock. Keep the raw string — the\n // shared result parser builds a UTC Date, matching other drivers.\n 1114: (value: string) => value,\n ...userOptions.parsers,\n },\n };\n\n // PGlite.create accepts dataDir as first argument or in options\n return dataDir\n ? await PGlite.create(dataDir, options)\n : await PGlite.create(options);\n }\n\n /**\n * A supplied database belongs to the caller, who may be running two\n * schema-scoped estates over it — the documented shape — and closing it here\n * would take the sibling's data down with this one's `$disconnect()`, on an\n * in-memory database for good.\n *\n * The test is on the client's IDENTITY against what construction captured, so\n * it answers for the database actually being closed rather than for whatever\n * the caller's record says now.\n */\n protected async closeClient(client: PGlite): Promise<void> {\n if (client === this.suppliedClient) {\n return;\n }\n await client.close();\n }\n\n protected async execute<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"execute\");\n }\n\n protected async executeRaw<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const result = await client.query<T>(sql, params, {\n parsers: temporalParsers,\n });\n const affectedRows = normalizeProviderRowCount(result.affectedRows, {\n provider: \"pglite\",\n operation,\n });\n return {\n rows: result.rows,\n rowCount: result.rows.length > 0 ? result.rows.length : affectedRows,\n };\n }\n\n /**\n * A collection read as positional rows: PGlite's `rowMode: \"array\"` hands\n * each row over as an array and the column list once, instead of building an\n * object keyed by every column name for every row.\n */\n #executePositional(\n query: Sql,\n context: QueryExecutionContext\n ): Promise<ProjectionExecutionResult> {\n return this.executeTypedStatement(\n query,\n context,\n async (\n client,\n sql,\n params,\n executionContext\n ): Promise<ProjectionExecutionResult> => {\n const resultContext = {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n };\n if (!PGliteDriver.isPositionalCandidate(this)) {\n const result = await this.execute<unknown>(\n client,\n sql,\n params,\n executionContext\n );\n assertNormalizedQueryResult(result, resultContext);\n return { kind: \"borrowed\", result };\n }\n const result = await client.query<unknown[]>(sql, params, {\n parsers: temporalParsers,\n rowMode: \"array\",\n });\n const affectedRows = normalizeProviderRowCount(\n result.affectedRows,\n resultContext\n );\n const rows: unknown[] = result.rows;\n if (rows.length > 0 && !Array.isArray(rows[0])) {\n const borrowed = { rows, rowCount: rows.length };\n assertNormalizedQueryResult(borrowed, resultContext);\n return { kind: \"borrowed\", result: borrowed };\n }\n if (!Array.isArray(result.fields)) {\n if (rows.length === 0) {\n return {\n kind: \"borrowed\",\n result: { rows, rowCount: affectedRows },\n };\n }\n throw new QueryError(\n `Driver \"${resultContext.provider}\" malformed positional rows for \"${resultContext.operation}\".`,\n { meta: createNormalizedResultMeta(resultContext) }\n );\n }\n const columns = result.fields.map((field) => field.name);\n assertPositionalRows(rows, columns, resultContext);\n return { kind: \"positional\", rows, columns };\n }\n );\n }\n\n private static isPositionalCandidate(driver: AnyDriver): boolean {\n if (!(driver instanceof PGliteDriver)) return false;\n const installed = driver.#installed;\n const { adapter } = driver;\n const { result } = adapter;\n return (\n Object.getPrototypeOf(driver) === PGliteDriver.prototype &&\n driver._execute === PGliteDriver.#executeEntry &&\n driver.execute === PGliteDriver.#execute &&\n driver.executeTypedStatement === PGliteDriver.#typedStatement &&\n driver.result === undefined &&\n installed[0] === adapter &&\n installed[1] === result &&\n installed[2] === result.parseField &&\n installed[3] === result.parseRelation &&\n installed[4] === result.parseResult\n );\n }\n\n /** The adapter and the parsers positional rows are decoded by. */\n static #surface(driver: PGliteDriver): readonly unknown[] {\n const { adapter } = driver;\n const { result } = adapter;\n return [\n adapter,\n result,\n result.parseField,\n result.parseRelation,\n result.parseResult,\n ];\n }\n\n /**\n * PGlite is a full PostgreSQL, so the isolation level is a real post-BEGIN\n * statement. It is also single-connection, so top-level transactions queue —\n * and that queue wait is exactly what `maxWait` bounds.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"queue\",\n };\n }\n\n protected transaction<T>(\n client: PGlite | Transaction,\n fn: (tx: Transaction) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n if (!isPGliteDatabase(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return runProviderManagedTransaction({\n run: (callback) => client.transaction(callback),\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n /**\n * The PGlite instance itself — the physical session a pinned command runs on.\n *\n * A caller may hand ONE PGlite to several drivers (two schema-scoped estates\n * over one database is the documented shape), and each of those drivers owns\n * its own connection queue. The client is what they all agree on, so it is\n * what serializes their pinned commands; without it the second command\n * re-acquires the reentrant session advisory lock the first is holding and\n * runs inside the first command's session.\n */\n protected override async physicalPinnedSession(): Promise<object> {\n return await this.getClient({ operation: \"pinnedSession\" });\n }\n\n /**\n * PGlite's single client, under the queue it already owns — plan §3.5's\n * pinned producer here. There is nothing to reserve and nothing to return:\n * one connection IS the session, which is exactly what a session lock needs.\n *\n * A condemned session can be neither destroyed nor abandoned: closing this\n * client closes the DATABASE, which for an in-memory one takes the caller's\n * data with it and for a supplied one is not VibORM's to do at all. So the\n * session is reset with `pg_advisory_unlock_all()`, and when that reset FAILS\n * the CLIENT is condemned instead — the subject of an unknown lock state is\n * the session, so the condemnation is recorded on it and refuses the next\n * pinned command through every driver over it. Ordinary queries keep working\n * — the data was never in doubt. Swallowing that reset failure was the\n * alternative, and it left the next migration command running inside a\n * session that may still hold the lock, on the one transport where the lock\n * is reentrant and would not stop it.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PGlite | Transaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!isPGliteDatabase(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return {\n session: client,\n release: async (discard) => {\n if (!discard) {\n return;\n }\n try {\n await client.query(\"SELECT pg_advisory_unlock_all()\");\n } catch (resetFailure) {\n condemnPhysicalSession(client);\n throw unprovenLockStateError(\n this.driverName,\n \"No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.\",\n resetFailure\n );\n }\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PGliteConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PGliteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PGliteDriver }\n >]: LinkedClientConfig<C & { driver: PGliteDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pglite\", PGLITE_CONFIG_KEYS);\n const { client, dataDir, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new PGliteDriver({\n client,\n dataDir,\n options,\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, PGliteDriver>(config, driver);\n}\n"],"mappings":"kcAmDA,MAAM,EAAkB,OAAO,OAC7B,OAAO,YACL,CAAC,KAAM,KAAM,KAAM,KAAM,KAAM,KAAK,CAAC,IAAK,GAAQ,CAChD,EACC,GAAkB,EACpB,CAAA,CACH,CACD,CAwBK,EAA8D,CAClE,OAAQ,GACR,QAAS,GACT,QAAS,GACT,SAAU,GACV,QAAS,GACT,qBAAsB,GACtB,sBAAuB,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,EAAO,CACxB,EACJ,KAAK,WACL,4KACA,EACD,GAGN,GAQL,SAAgB,EACd,EAOC,CACD,EAA8B,EAAQ,SAAU,EAAmB,CACnE,GAAM,CAAE,SAAQ,UAAS,UAAS,WAAU,WAAY,EAClD,EAAY,EAAuB,EAAO,CAahD,OAAO,EAAiD,EAXzC,IAAI,EAAa,CAC9B,SACA,UACA,UACA,WACA,UACA,qBAAsB,EAAO,qBAC7B,sBAAuB,EAAO,sBAC9B,YACD,CAAC,CAEqE"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"physical-DO4PEYcc.mjs","names":[],"sources":["../src/schema/scalars/datetime/physical.ts"],"sourcesContent":["import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport { type NativeTypeDeclaration, nativeTypeFor } from \"../native-types\";\n\n/**\n * The physical vocabulary SQLite assigns to one DateTime native declaration.\n *\n * A missing declaration, a declaration that selects nothing on SQLite, and\n * explicit TEXT all use SQLite's default timestamp text. INTEGER is epoch milliseconds and\n * REAL is a Julian day. Schema validation, query lowering, result parsing, and\n * migration defaults consume this same interpretation.\n */\nexport function sqliteDateTimePhysicalForm(\n declaration: NativeTypeDeclaration | undefined\n): DateTimePhysicalForm {\n const nativeType = nativeTypeFor(declaration, \"sqlite\");\n if (nativeType === undefined) return \"text\";\n if (nativeType.type === \"INTEGER\") return \"epochMillis\";\n return nativeType.type === \"REAL\" ? \"julianDay\" : \"text\";\n}\n"],"mappings":"gDAWA,SAAgB,EACd,EACsB,CACtB,IAAM,EAAa,EAAc,EAAa,SAAS,CAGvD,OAFI,IAAe,IAAA,GAAkB,OACjC,EAAW,OAAS,UAAkB,cACnC,EAAW,OAAS,OAAS,YAAc"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as e}from"./base-17NSFtrA.mjs";import{i as t}from"./validation-ATmgN5RE.mjs";import{n}from"./suppressed-failure-CFUDJrUw.mjs";import{t as r}from"./settle-Pui-1tfJ.mjs";const i=`SELECT pg_advisory_unlock_all()`,a=`"${i}" failed; lock state unknown.`,o=5e3;function s(t,n,r){return c(t,a,n,e(r))}function c(e,n,r,i){return new t(`Driver "${e}" ${n} ${r}`,{code:`V1003`,cause:i,meta:{driver:e,operation:`pinnedSession`}})}function l(e){return new t(`Driver "${e}" condemned after failed "${i}".`,{code:`V1003`,meta:{driver:e,operation:`pinnedSession`}})}const u=`Abandoned (caller-owned).`;async function d(e){if(e.lost===!0){let{uu:t,driverName:n}=e;if(t===void 0)throw c(n,`lost reserved migration session.`,u,void 0);t().catch(()=>void 0);return}if(!e.discard){e.release();return}try{await r(e.reset(),o,()=>Error(`Advisory-lock reset timed out after ${o}ms.`))}catch(t){await f(e,a,t)}e.release()}async function f(t,r,i){let{uu:a,driverName:o}=t;if(a===void 0)throw c(o,r,u,e(i));try{await a()}catch(t){throw n(c(o,r,`Abandoned; close failed, locks may remain.`,e(i)),t)}throw c(o,r,`Abandoned; transport closed.`,e(i))}const p=new WeakMap;function m(e,t){if(t.zq)throw l(e)}function h(e,t,n){let r=_(t);m(e,r);let i=r.queued.then(()=>(m(e,r),n()));return r.queued=i.then(()=>void 0,()=>void 0),i}function g(e){_(e).zq=!0}function _(e){let t=p.get(e);if(t)return t;let n={queued:Promise.resolve(),zq:!1};return p.set(e,n),n}export{s as a,d as i,g as n,h as r,o as t};
|
|
2
|
+
//# sourceMappingURL=pinned-session-Y7-2pRBJ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pinned-session-Y7-2pRBJ.mjs","names":[],"sources":["../src/drivers/shared/pinned-session.ts"],"sourcesContent":["import { ConnectionError, VibORMErrorCode } from \"@errors\";\nimport { errorCause } from \"../../errors/diagnostic-safety\";\nimport { settleWithin } from \"./settle\";\nimport { withSuppressedFailure } from \"./suppressed-failure\";\n\n/** The PostgreSQL statement that resets a session's advisory-lock state. */\nconst ADVISORY_RESET = \"SELECT pg_advisory_unlock_all()\";\n\n/** Why a reserved session is abandoned, in the refusal's own words. */\nconst LOST_SESSION = \"lost reserved migration session.\";\nconst ADVISORY_RESET_FAILED = `\"${ADVISORY_RESET}\" failed; lock state unknown.`;\n\n/**\n * How long one cleanup statement — `ROLLBACK`, the unlock, the limits reset,\n * the advisory reset — may take before its session is treated as lost.\n *\n * A healthy server answers each of them in milliseconds. A session that does\n * not answer one within this bound is a half-open socket or a dying backend,\n * and waiting on it longer only keeps the caller from the failure it already\n * has (plan S2: \"bound every cleanup statement\").\n */\nexport const CLEANUP_BOUND_MS = 5000;\n\n/**\n * One reserved physical session, as a provider hands it back.\n *\n * The plan's requirement (§3.5) is \"one physical producer across decisions and\n * commit boundaries\": a session lock is session-scoped, so acquiring it through\n * one pooled connection and running the protected work through another protects\n * nothing and can strand the lock. A reservation is therefore a connection the\n * provider has taken OUT of its pool, plus the exact way to give it back.\n */\nexport interface PinnedSessionReservation<TSession> {\n /** The reserved producer. Every statement of the session runs on it. */\n readonly session: TSession;\n /**\n * The failure the provider itself saw end this session's connection, or\n * `undefined` while it has seen none.\n *\n * Only a provider that observes its connection has one (`pg`, through the\n * client's `error` event). Elsewhere a lost connection is recognized by the\n * failure that reported it.\n */\n readonly lost?: () => unknown;\n /**\n * Returns the producer to the provider.\n *\n * `discard` is true when the session's state is unknown — a failed unlock, a\n * failed cleanup, or a thrown body — and the provider must then destroy the\n * connection rather than hand a session carrying unknown state back to a\n * pool. A provider whose session can never be made clean again (MySQL2, which\n * has executed `USE` and possibly author-owned statements) destroys\n * unconditionally and ignores the flag.\n *\n * `lost` is true when the connection itself is gone or stopped answering:\n * the provider must send nothing more on it — not even the reset a discard\n * otherwise runs — and abandon or destroy it.\n */\n release(discard: boolean, lost?: boolean): Promise<void>;\n}\n\n/**\n * The handle the pinned body uses to condemn its own producer.\n *\n * A thrown body already condemns the session. This exists for the case that\n * does not throw: an unlock statement that RETURNS a result proving the lock\n * was not released. That session is still usable in the provider's eyes and\n * would be returned to the pool holding a lock nobody owns.\n */\nexport interface PinnedSessionControl {\n /** Condemn this producer; it will be destroyed instead of released. */\n discard(): void;\n /**\n * Whether this session's connection is gone: the provider saw it end,\n * `failure` reports it, or a cleanup statement went unanswered. Once true it\n * stays true, and nothing more is sent on the session (plan S2).\n */\n lost(failure?: unknown): boolean;\n /** Runs one cleanup statement within `CLEANUP_BOUND_MS`; past it, the session is lost. */\n cleanup<T>(run: () => Promise<T>): Promise<T>;\n}\n\n/**\n * The refusal a discarded session whose reset FAILED raises.\n *\n * A session is discarded because its state is unknown, and the reset is what\n * makes it known again. When the reset fails too, the session may still hold\n * the migration lock every other command is excluded by — so it must not go\n * back to the provider, and saying nothing about that is not an option either:\n * a swallowed cleanup failure is how a pool ends up serving a connection that\n * blocks the next migration forever.\n *\n * The reset's own failure is the evidence, and it is the PROVIDER's value: it\n * goes through the one total normalizer rather than a bare `instanceof`, which\n * a rejection whose `getPrototypeOf` trap throws turns into a throw inside this\n * constructor — replacing the whole typed refusal with the trap's error.\n */\nexport function unprovenLockStateError(\n driverName: string,\n containment: string,\n cause: unknown\n): ConnectionError {\n return abandonedSessionError(\n driverName,\n ADVISORY_RESET_FAILED,\n containment,\n errorCause(cause)\n );\n}\n\nfunction abandonedSessionError(\n driverName: string,\n reason: string,\n containment: string,\n cause: Error | undefined\n): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" ${reason} ${containment}`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n cause,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * The refusal raised afterwards by EVERY driver whose one client was condemned.\n *\n * A transport that pools connections recovers by reserving a different one, so\n * this is only for the driver whose single client IS the session: there is no\n * other connection to reach for, and running the next migration command on a\n * session that may still hold the lock is precisely what the condemnation\n * exists to prevent. Two drivers over that one client are two callers of this\n * same refusal, because the session they would both pin is the same session.\n */\nexport function condemnedSessionError(driverName: string): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" condemned after failed \"${ADVISORY_RESET}\".`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\nconst CALLER_OWNED_CONTAINMENT = \"Abandoned (caller-owned).\";\nconst CLOSED_CONTAINMENT = \"Abandoned; transport closed.\";\nconst CLOSE_FAILED_CONTAINMENT = \"Abandoned; close failed, locks may remain.\";\n\n/**\n * Returns a reserved PostgreSQL session to its pool, or condemns it — the ONE\n * rule for every provider that reserves a connection it cannot destroy.\n *\n * postgres.js and Bun SQL both expose `release()` and nothing else: there is no\n * destructive return to reach for, so a session whose reset failed is ABANDONED\n * — never released — which is the only way it stops being a connection the pool\n * will hand to the next caller.\n *\n * Abandoning it leaves the lock held until that backend goes away, so a\n * transport VibORM created is closed too: ending it terminates the backend, and\n * PostgreSQL frees every advisory lock the session held. A transport the CALLER\n * supplied is never closed for this — it is theirs, may be serving their own\n * code, and closing it to tidy up VibORM's cleanup failure would be a far\n * larger effect than the one being contained.\n *\n * A LOST session (plan S2) is abandoned the same way without the reset: its\n * connection is gone or stopped answering, and a statement written to it is,\n * on postgres.js, an uncaught crash from inside the provider's write loop. Its\n * owned transport is closed; a supplied one is reported, since abandoning is\n * all VibORM may do with it.\n */\nexport async function releaseReservedPostgresSession(reservation: {\n readonly driverName: string;\n readonly discard: boolean;\n readonly lost?: boolean | undefined;\n /** Runs `SELECT pg_advisory_unlock_all()` on the reserved session. */\n readonly reset: () => Promise<unknown>;\n /** Hands the reserved session back to the provider's pool. */\n readonly release: () => void;\n /** Closes the transport, or absent when the CALLER owns it. */\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n}): Promise<void> {\n if (reservation.lost === true) {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n LOST_SESSION,\n CALLER_OWNED_CONTAINMENT,\n undefined\n );\n }\n // Not awaited: the connection failure the caller holds is already the\n // answer, and the close lets the transport's other queries finish first\n // (postgres.js waits on the dead connection's unsettled query until its\n // bound). The transport is withdrawn before it closes, and a session the\n // close cannot end is ended by the server's idle limit.\n closeOwnedTransport().catch(() => undefined);\n return;\n }\n if (!reservation.discard) {\n reservation.release();\n return;\n }\n\n try {\n await settleWithin(\n reservation.reset(),\n CLEANUP_BOUND_MS,\n () =>\n new Error(`Advisory-lock reset timed out after ${CLEANUP_BOUND_MS}ms.`)\n );\n } catch (resetFailure) {\n await abandon(reservation, ADVISORY_RESET_FAILED, resetFailure);\n }\n reservation.release();\n}\n\n/**\n * Abandons a reserved session: never released, its owned transport closed,\n * and the refusal that says so thrown. A transport the caller supplied is only\n * abandoned.\n */\nasync function abandon(\n reservation: {\n readonly driverName: string;\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n },\n reason: string,\n cause: unknown\n): Promise<void> {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n reason,\n CALLER_OWNED_CONTAINMENT,\n errorCause(cause)\n );\n }\n try {\n await closeOwnedTransport();\n } catch (closeFailure) {\n // The reason stays primary — it is what the caller acts on — and the\n // close's own failure is cleanup evidence beside it.\n throw withSuppressedFailure(\n abandonedSessionError(\n driverName,\n reason,\n CLOSE_FAILED_CONTAINMENT,\n errorCause(cause)\n ),\n closeFailure\n );\n }\n throw abandonedSessionError(\n driverName,\n reason,\n CLOSED_CONTAINMENT,\n errorCause(cause)\n );\n}\n\n/** What VibORM knows about one PHYSICAL session it pins commands on. */\ninterface PhysicalSessionState {\n /**\n * The pinned commands already queued on this session. It never rejects, so\n * one command's failure cannot poison the queue — the next command runs\n * either way, exactly as it would after a success.\n */\n queued: Promise<void>;\n /**\n * Set when a discarded session's advisory-lock reset failed, and never\n * cleared: nothing that happens later can prove a lock was released.\n */\n condemned: boolean;\n}\n\n/**\n * What is known about each PHYSICAL session, keyed on the session itself.\n *\n * A driver's connection queue serializes the commands of THAT driver. Two\n * drivers built over one supplied client — the documented shape for two\n * schema-scoped estates over one PGlite — own two queues and one session, so\n * the queue arbitrates nothing between them, and a PostgreSQL session advisory\n * lock is REENTRANT: the second command re-acquires the lock the first is\n * holding instead of waiting for it, then reads and writes inside the first\n * command's session. The client is the only thing both drivers agree on, so it\n * is what this is keyed on.\n *\n * The condemnation shares that key because it answers for the same subject: a\n * failed reset leaves the CLIENT's lock state unknown, not the wrapper's. Kept\n * on the driver instead, it was a fact the other wrappers over that client\n * never consulted, and their next command ran inside the session it condemned.\n *\n * Weak by construction: the entry dies with the client, and a client nobody\n * holds keeps nothing alive here.\n */\nconst PHYSICAL_SESSIONS = new WeakMap<object, PhysicalSessionState>();\n\n/**\n * Refuses a command on a session whose advisory-lock state was condemned.\n *\n * One refusal, read at two moments, and each covers what the other cannot. At\n * ADMISSION, so a session condemned before this command arrived refuses now\n * rather than behind a queue whose head may itself be waiting on the very lock\n * nobody can account for. At the FRONT of the queue, because condemnation lands\n * BETWEEN the two: the command ahead of this one is the one whose reset fails,\n * and this one was admitted while that session still looked accountable.\n */\nfunction refuseCondemnedSession(\n driverName: string,\n state: PhysicalSessionState\n): void {\n if (state.condemned) {\n throw condemnedSessionError(driverName);\n }\n}\n\n/**\n * Runs `command` exclusively on this physical session, when it may still be\n * pinned at all.\n *\n * The refusal is here rather than beside it because this is the one path every\n * pinned command over a shared session takes, and it lands before `command` —\n * so no body and no statement of the refused command reaches the client.\n */\nexport function leasePinnedCommand<T>(\n driverName: string,\n session: object,\n command: () => Promise<T>\n): Promise<T> {\n const state = physicalSessionState(session);\n refuseCondemnedSession(driverName, state);\n const next = state.queued.then(() => {\n refuseCondemnedSession(driverName, state);\n return command();\n });\n state.queued = next.then(\n () => undefined,\n () => undefined\n );\n return next;\n}\n\n/**\n * Records that this physical session's advisory-lock state can no longer be\n * accounted for — for every driver that reaches it, not only the one whose\n * reset failed.\n */\nexport function condemnPhysicalSession(session: object): void {\n physicalSessionState(session).condemned = true;\n}\n\n/** This session's state, created on first use and mutated in place after. */\nfunction physicalSessionState(session: object): PhysicalSessionState {\n const existing = PHYSICAL_SESSIONS.get(session);\n if (existing) {\n return existing;\n }\n const created: PhysicalSessionState = {\n queued: Promise.resolve(),\n condemned: false,\n };\n PHYSICAL_SESSIONS.set(session, created);\n return created;\n}\n"],"mappings":"iLAMA,MAAM,EAAiB,kCAIjB,EAAwB,IAAI,EAAe,+BAWpC,EAAmB,IA4EhC,SAAgB,EACd,EACA,EACA,EACiB,CACjB,OAAO,EACL,EACA,EACA,EACA,EAAW,EAAK,CACjB,CAGH,SAAS,EACP,EACA,EACA,EACA,EACiB,CACjB,OAAO,IAAI,EACT,WAAW,EAAW,IAAI,EAAO,GAAG,IACpC,CACE,KAAM,QACN,QACA,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CAC1D,CACD,CAaH,SAAgB,EAAsB,EAAqC,CACzE,OAAO,IAAI,EACT,WAAW,EAAW,4BAA4B,EAAe,IACjE,CACE,KAAM,QACN,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CAC1D,CACD,CAGH,MAAM,EAA2B,4BA0BjC,eAAsB,EAA+B,EAUnC,CAChB,GAAI,EAAY,OAAS,GAAM,CAC7B,GAAM,CAAE,sBAAqB,cAAe,EAC5C,GAAI,IAAwB,IAAA,GAC1B,MAAM,EACJ,EACA,mCACA,EACA,IAAA,GACD,CAOH,GAAqB,CAAC,UAAY,IAAA,GAAU,CAC5C,OAEF,GAAI,CAAC,EAAY,QAAS,CACxB,EAAY,SAAS,CACrB,OAGF,GAAI,CACF,MAAM,EACJ,EAAY,OAAO,CACnB,MAEM,MAAM,uCAAuC,EAAiB,KAAI,CACzE,OACM,EAAc,CACrB,MAAM,EAAQ,EAAa,EAAuB,EAAa,CAEjE,EAAY,SAAS,CAQvB,eAAe,EACb,EAIA,EACA,EACe,CACf,GAAM,CAAE,sBAAqB,cAAe,EAC5C,GAAI,IAAwB,IAAA,GAC1B,MAAM,EACJ,EACA,EACA,EACA,EAAW,EAAK,CACjB,CAEH,GAAI,CACF,MAAM,GAAqB,OACpB,EAAc,CAGrB,MAAM,EACJ,EACE,EACA,EACA,6CACA,EAAW,EAAK,CACjB,CACD,EACD,CAEH,MAAM,EACJ,EACA,EACA,+BACA,EAAW,EAAK,CACjB,CAsCH,MAAM,EAAoB,IAAI,QAY9B,SAAS,EACP,EACA,EACM,CACN,GAAI,EAAM,UACR,MAAM,EAAsB,EAAW,CAY3C,SAAgB,EACd,EACA,EACA,EACY,CACZ,IAAM,EAAQ,EAAqB,EAAQ,CAC3C,EAAuB,EAAY,EAAM,CACzC,IAAM,EAAO,EAAM,OAAO,UACxB,EAAuB,EAAY,EAAM,CAClC,GAAS,EAChB,CAKF,MAJA,GAAM,OAAS,EAAK,SACZ,IAAA,OACA,IAAA,GACP,CACM,EAQT,SAAgB,EAAuB,EAAuB,CAC5D,EAAqB,EAAQ,CAAC,UAAY,GAI5C,SAAS,EAAqB,EAAuC,CACnE,IAAM,EAAW,EAAkB,IAAI,EAAQ,CAC/C,GAAI,EACF,OAAO,EAET,IAAM,EAAgC,CACpC,OAAQ,QAAQ,SAAS,CACzB,UAAW,GACZ,CAED,OADA,EAAkB,IAAI,EAAS,EAAQ,CAChC"}
|
package/dist/planetscale.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { $a as QueryExecutionContext, Di as LinkedClientConfig, Gr as Schema, Ja as TransactionOptionSupport, eo as QueryResult, h as Driver, pt as VibORMClient, qa as DriverTransactionOptions, st as DriverConfig, t as DatabaseAdapter, ut as NoExtraDriverConfigKeys } from "./database-adapter-BMjJiBFm.mjs";
|
|
2
2
|
import { Client, Config, Connection } from "@planetscale/database";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/planetscale/index.d.ts
|