viborm 1.1.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-namespace-DMhEF6my.mjs → adapter-namespace-DqkJQdrD.mjs} +2 -2
- package/dist/{adapter-namespace-DMhEF6my.mjs.map → adapter-namespace-DqkJQdrD.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-DcEm5tt_.mjs → array-literal-BsbbSLw3.mjs} +1 -1
- package/dist/{array-literal-DcEm5tt_.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
- package/dist/base-AdXAoy6l.mjs +2 -0
- package/dist/base-AdXAoy6l.mjs.map +1 -0
- package/dist/batch-refs-4L8ECdPU.mjs +2 -0
- package/dist/batch-refs-4L8ECdPU.mjs.map +1 -0
- package/dist/bind-parameter-capacity-CjPgqnmx.mjs +2 -0
- package/dist/{bind-parameter-capacity-DzMcIB95.mjs.map → bind-parameter-capacity-CjPgqnmx.mjs.map} +1 -1
- package/dist/builder-Ycvq3ETg.mjs +2 -0
- package/dist/builder-Ycvq3ETg.mjs.map +1 -0
- package/dist/bun-sql.d.mts +19 -2
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +9 -8
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/bun-sqlite.mjs.map +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache/memory.mjs.map +1 -1
- package/dist/cache-BO57X0TT.mjs +2 -0
- package/dist/cache-BO57X0TT.mjs.map +1 -0
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/canonical-json-rfC2Dg0X.mjs +2 -0
- package/dist/canonical-json-rfC2Dg0X.mjs.map +1 -0
- package/dist/chain-Dh0FV72b.mjs +2 -0
- package/dist/chain-Dh0FV72b.mjs.map +1 -0
- package/dist/cli.mjs +5 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-BLiBmykn.mjs +2 -0
- package/dist/client-BLiBmykn.mjs.map +1 -0
- package/dist/client-CCgfcp5A.mjs +52 -0
- package/dist/client-CCgfcp5A.mjs.map +1 -0
- package/dist/client-XQSEkF90.d.mts +610 -0
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-W8H2Khng.mjs → clock-CK41KO7t.mjs} +1 -1
- package/dist/{clock-W8H2Khng.mjs.map → clock-CK41KO7t.mjs.map} +1 -1
- package/dist/config.d.mts +3 -3
- package/dist/config.mjs +1 -1
- package/dist/controls-DXgIn4zh.mjs +2 -0
- package/dist/controls-DXgIn4zh.mjs.map +1 -0
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/datetime-physical-codec-oIhiYZEP.mjs +2 -0
- package/dist/{datetime-physical-codec-BK93pJGW.mjs.map → datetime-physical-codec-oIhiYZEP.mjs.map} +1 -1
- package/dist/driver-B19QlFqn.mjs +2 -0
- package/dist/{driver-ZIbkciaz.mjs.map → driver-B19QlFqn.mjs.map} +1 -1
- package/dist/driver-BlnKXPFF.mjs +2 -0
- package/dist/driver-BlnKXPFF.mjs.map +1 -0
- package/dist/driver.d.mts +2 -2
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-CnPCv1dm.mjs +2 -0
- package/dist/error-mapping-CnPCv1dm.mjs.map +1 -0
- package/dist/every-4KE0p2Gw.mjs +2 -0
- package/dist/every-4KE0p2Gw.mjs.map +1 -0
- package/dist/{execution-context-Bm_qTp1i.mjs → execution-context-BKR3bgES.mjs} +1 -1
- package/dist/{execution-context-Bm_qTp1i.mjs.map → execution-context-BKR3bgES.mjs.map} +1 -1
- package/dist/fs-estate-CAhDg7nY.mjs +2 -0
- package/dist/fs-estate-CAhDg7nY.mjs.map +1 -0
- package/dist/{geo-area-codec-B4DRInvA.mjs → geo-area-codec-1SY9im7O.mjs} +2 -2
- package/dist/{geo-area-codec-B4DRInvA.mjs.map → geo-area-codec-1SY9im7O.mjs.map} +1 -1
- package/dist/geo-point-codec-lhxH42SK.mjs +2 -0
- package/dist/geo-point-codec-lhxH42SK.mjs.map +1 -0
- package/dist/{hydration-D6JICBQG.mjs → hydration-CAxOL4aI.mjs} +2 -2
- package/dist/{hydration-D6JICBQG.mjs.map → hydration-CAxOL4aI.mjs.map} +1 -1
- package/dist/identifier-conversion-GgbwHc2G.mjs +2 -0
- package/dist/identifier-conversion-GgbwHc2G.mjs.map +1 -0
- package/dist/{identifier-EsWKVHXi.mjs → identifier-hQCs8M1n.mjs} +2 -2
- package/dist/{identifier-EsWKVHXi.mjs.map → identifier-hQCs8M1n.mjs.map} +1 -1
- package/dist/identity-CLFhCTZx.mjs +2 -0
- package/dist/identity-CLFhCTZx.mjs.map +1 -0
- package/dist/{index-BbcE-gyl.d.mts → index-Likdf5qP.d.mts} +638 -351
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/instrumentation.mjs.map +1 -1
- package/dist/{invariant-DCsftyml.mjs → invariant-BnLYqsHO.mjs} +1 -1
- package/dist/{invariant-DCsftyml.mjs.map → invariant-BnLYqsHO.mjs.map} +1 -1
- package/dist/{json-number-TpD-pfqt.mjs → json-number-CGXpPu4D.mjs} +1 -1
- package/dist/{json-number-TpD-pfqt.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
- package/dist/key-BeoOwGr3.mjs +2 -0
- package/dist/key-BeoOwGr3.mjs.map +1 -0
- package/dist/libsql-Bu_IdFU1.mjs +11 -0
- package/dist/libsql-Bu_IdFU1.mjs.map +1 -0
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/memory-D4yxtCPK.mjs +2 -0
- package/dist/memory-D4yxtCPK.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +6 -0
- package/dist/migrations/mysql.mjs +2 -0
- package/dist/migrations/mysql.mjs.map +1 -0
- package/dist/migrations/postgres.d.mts +6 -0
- package/dist/migrations/postgres.mjs +2 -0
- package/dist/migrations/postgres.mjs.map +1 -0
- package/dist/migrations/sqlite.d.mts +6 -0
- package/dist/migrations/sqlite.mjs +2 -0
- package/dist/migrations/sqlite.mjs.map +1 -0
- package/dist/migrations/storage/durable-object.d.mts +17 -0
- package/dist/migrations/storage/durable-object.mjs +2 -0
- package/dist/migrations/storage/durable-object.mjs.map +1 -0
- package/dist/migrations/storage/fs.d.mts +6 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +14 -0
- package/dist/migrations/storage/r2.mjs +2 -0
- package/dist/migrations/storage/r2.mjs.map +1 -0
- package/dist/migrations/tenant.d.mts +92 -0
- package/dist/migrations/tenant.mjs +2 -0
- package/dist/migrations/tenant.mjs.map +1 -0
- package/dist/{migrations-BWZSBMZh.mjs → migrations-DTObIjAm.mjs} +2 -2
- package/dist/migrations-DTObIjAm.mjs.map +1 -0
- package/dist/migrations.d.mts +6 -561
- package/dist/migrations.mjs +1 -1
- package/dist/migrations.mjs.map +1 -1
- package/dist/mysql-CibPaHSp.mjs +99 -0
- package/dist/mysql-CibPaHSp.mjs.map +1 -0
- package/dist/mysql-adapter-DkJPfoGf.mjs +2 -0
- package/dist/mysql-adapter-DkJPfoGf.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -3
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/object-store-CbjhsBQ3.d.mts +156 -0
- package/dist/object-store-DQR6bTBY.mjs +2 -0
- package/dist/object-store-DQR6bTBY.mjs.map +1 -0
- package/dist/observation-DUSm7oXK.mjs +2 -0
- package/dist/observation-DUSm7oXK.mjs.map +1 -0
- package/dist/pg.d.mts +37 -12
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +2 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/physical-6V_LNU3L.mjs +2 -0
- package/dist/{physical-BkelResN.mjs.map → physical-6V_LNU3L.mjs.map} +1 -1
- package/dist/pinned-session-CLxj5M5e.mjs +2 -0
- package/dist/pinned-session-CLxj5M5e.mjs.map +1 -0
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-Bbw8W81b.d.mts → planner-CwFUkNHP.d.mts} +57 -3
- package/dist/postgres-adapter-B3SQvcV1.mjs +2 -0
- package/dist/postgres-adapter-B3SQvcV1.mjs.map +1 -0
- package/dist/postgres-adapter-CQD2oGuD.mjs +2 -0
- package/dist/postgres-adapter-CQD2oGuD.mjs.map +1 -0
- package/dist/postgres-oqNW9xqo.mjs +415 -0
- package/dist/postgres-oqNW9xqo.mjs.map +1 -0
- package/dist/{postgres-result-Dc_iW3Hb.mjs → postgres-result-7F0DllQe.mjs} +2 -2
- package/dist/{postgres-result-Dc_iW3Hb.mjs.map → postgres-result-7F0DllQe.mjs.map} +1 -1
- package/dist/postgres.d.mts +11 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-DXj_pOT0.mjs → provider-limits-BHATED_m.mjs} +2 -2
- package/dist/{provider-limits-DXj_pOT0.mjs.map → provider-limits-BHATED_m.mjs.map} +1 -1
- package/dist/registration-preflight-DEjv050M.mjs +4 -0
- package/dist/registration-preflight-DEjv050M.mjs.map +1 -0
- package/dist/result-shape-CTNdNSW3.mjs +2 -0
- package/dist/result-shape-CTNdNSW3.mjs.map +1 -0
- package/dist/scalar-U0wD5bKy.mjs +2 -0
- package/dist/{scalar-BTktMqvO.mjs.map → scalar-U0wD5bKy.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema/json.mjs.map +1 -1
- package/dist/schema-Cjem1-0f.mjs +2 -0
- package/dist/{schema-BFNcMdO6.mjs.map → schema-Cjem1-0f.mjs.map} +1 -1
- package/dist/schema-introspection-DEYGC2qg.mjs +6 -0
- package/dist/schema-introspection-DEYGC2qg.mjs.map +1 -0
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-BgqlrePH.mjs → select-assembly-f1UGoblh.mjs} +2 -2
- package/dist/select-assembly-f1UGoblh.mjs.map +1 -0
- package/dist/settle-B9Vg1FnP.mjs +2 -0
- package/dist/settle-B9Vg1FnP.mjs.map +1 -0
- package/dist/soft-delete.d.mts +1 -1
- package/dist/{sql--69HUgel.mjs → sql-Bp7jicEX.mjs} +1 -1
- package/dist/{sql--69HUgel.mjs.map → sql-Bp7jicEX.mjs.map} +1 -1
- package/dist/{sql-statement-tokens-CykxFmOJ.mjs → sql-statement-tokens-BBcoGmJb.mjs} +1 -1
- package/dist/{sql-statement-tokens-CykxFmOJ.mjs.map → sql-statement-tokens-BBcoGmJb.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-CW_3l6ea.mjs +2 -0
- package/dist/sqlite-adapter-CW_3l6ea.mjs.map +1 -0
- package/dist/sqlite-utils-DlgokMJN.mjs +2 -0
- package/dist/sqlite-utils-DlgokMJN.mjs.map +1 -0
- package/dist/sqlite3.d.mts +2 -8
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/standard-sql-Bk4RZPqJ.mjs +6 -0
- package/dist/standard-sql-Bk4RZPqJ.mjs.map +1 -0
- package/dist/{suppressed-failure-BPxfHTMc.mjs → suppressed-failure-BwULh-8h.mjs} +1 -1
- package/dist/{suppressed-failure-BPxfHTMc.mjs.map → suppressed-failure-BwULh-8h.mjs.map} +1 -1
- package/dist/{terminal-BbRi0CNZ.mjs → terminal-C8cq1WWX.mjs} +2 -2
- package/dist/{terminal-BbRi0CNZ.mjs.map → terminal-C8cq1WWX.mjs.map} +1 -1
- package/dist/{transaction-oskVwmsf.mjs → transaction-Bnl6ULTw.mjs} +2 -2
- package/dist/transaction-Bnl6ULTw.mjs.map +1 -0
- package/dist/{transaction-operation-BC7aua5V.mjs → transaction-operation-CKK3l_9x.mjs} +2 -2
- package/dist/{transaction-operation-BC7aua5V.mjs.map → transaction-operation-CKK3l_9x.mjs.map} +1 -1
- package/dist/{utils-CRFUUfNn.mjs → utils-CZNaOZR7.mjs} +4 -3
- package/dist/utils-CZNaOZR7.mjs.map +1 -0
- package/dist/v-D5Z06FKN.mjs +2 -0
- package/dist/v-D5Z06FKN.mjs.map +1 -0
- package/dist/validation-Dk9Q_-C7.mjs +2 -0
- package/dist/validation-Dk9Q_-C7.mjs.map +1 -0
- package/dist/validation-PF9-_nKd.mjs +2 -0
- package/dist/{validation-tgjL_9n8.mjs.map → validation-PF9-_nKd.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-X9-bwtRo.mjs +2 -0
- package/dist/{validator-DMlEScV3.mjs.map → validator-X9-bwtRo.mjs.map} +1 -1
- package/dist/value-guards-CK9guf2Z.mjs +2 -0
- package/dist/value-guards-CK9guf2Z.mjs.map +1 -0
- package/dist/version-B4VuToLC.mjs +2 -0
- package/dist/{version-De1l_ZMF.mjs.map → version-B4VuToLC.mjs.map} +1 -1
- package/package.json +76 -33
- package/dist/base-vfur-DaU.mjs +0 -2
- package/dist/base-vfur-DaU.mjs.map +0 -1
- package/dist/batch-refs-Op1fx9Bo.mjs +0 -6
- package/dist/batch-refs-Op1fx9Bo.mjs.map +0 -1
- package/dist/bind-parameter-capacity-DzMcIB95.mjs +0 -2
- package/dist/builder-DkWfNHEV.mjs +0 -2
- package/dist/builder-DkWfNHEV.mjs.map +0 -1
- package/dist/chain-uIFlkkXS.mjs +0 -2
- package/dist/chain-uIFlkkXS.mjs.map +0 -1
- package/dist/client-C8gXvWIA.mjs +0 -2
- package/dist/client-C8gXvWIA.mjs.map +0 -1
- package/dist/client-z9mcpRtA.mjs +0 -435
- package/dist/client-z9mcpRtA.mjs.map +0 -1
- package/dist/controls-BhxRnPYS.mjs +0 -2
- package/dist/controls-BhxRnPYS.mjs.map +0 -1
- package/dist/datetime-physical-codec-BK93pJGW.mjs +0 -2
- package/dist/driver-CHclfK3q.mjs +0 -2
- package/dist/driver-CHclfK3q.mjs.map +0 -1
- package/dist/driver-ZIbkciaz.mjs +0 -2
- package/dist/driver-options-DVxWlZ0s.mjs +0 -2
- package/dist/driver-options-DVxWlZ0s.mjs.map +0 -1
- package/dist/error-mapping-LKqxnw-b.mjs +0 -2
- package/dist/error-mapping-LKqxnw-b.mjs.map +0 -1
- package/dist/fs-estate-3Bu_K9mk.d.mts +0 -7
- package/dist/fs-estate-BLqNdigQ.mjs +0 -2
- package/dist/fs-estate-BLqNdigQ.mjs.map +0 -1
- package/dist/geo-point-codec-DUTTtlav.mjs +0 -2
- package/dist/geo-point-codec-DUTTtlav.mjs.map +0 -1
- package/dist/key-DKaqPb8w.mjs +0 -2
- package/dist/key-DKaqPb8w.mjs.map +0 -1
- package/dist/migrations-BWZSBMZh.mjs.map +0 -1
- package/dist/mysql-adapter-DtZdwqzc.mjs +0 -2
- package/dist/mysql-adapter-DtZdwqzc.mjs.map +0 -1
- package/dist/observation-CLp8ylmL.mjs +0 -2
- package/dist/observation-CLp8ylmL.mjs.map +0 -1
- package/dist/physical-BkelResN.mjs +0 -2
- package/dist/pinned-session-CNANv7bv.mjs +0 -2
- package/dist/pinned-session-CNANv7bv.mjs.map +0 -1
- package/dist/postgres-adapter-ButxrmEa.mjs +0 -2
- package/dist/postgres-adapter-ButxrmEa.mjs.map +0 -1
- package/dist/registration-preflight-BrA3EWvq.mjs +0 -4
- package/dist/registration-preflight-BrA3EWvq.mjs.map +0 -1
- package/dist/result-shape-CKLOBSKl.mjs +0 -2
- package/dist/result-shape-CKLOBSKl.mjs.map +0 -1
- package/dist/scalar-BTktMqvO.mjs +0 -2
- package/dist/schema-BFNcMdO6.mjs +0 -2
- package/dist/schema-introspection-C7P7lwIs.mjs +0 -6
- package/dist/schema-introspection-C7P7lwIs.mjs.map +0 -1
- package/dist/select-assembly-BgqlrePH.mjs.map +0 -1
- package/dist/sqlite-adapter-1krz0OXw.mjs +0 -2
- package/dist/sqlite-adapter-1krz0OXw.mjs.map +0 -1
- package/dist/sqlite-utils-D26BFuJJ.mjs +0 -2
- package/dist/sqlite-utils-D26BFuJJ.mjs.map +0 -1
- package/dist/transaction-oskVwmsf.mjs.map +0 -1
- package/dist/transactions-gjmrWN5W.mjs +0 -2
- package/dist/transactions-gjmrWN5W.mjs.map +0 -1
- package/dist/utils-CRFUUfNn.mjs.map +0 -1
- package/dist/v-B2WwtcRz.mjs +0 -2
- package/dist/v-B2WwtcRz.mjs.map +0 -1
- package/dist/validation-Du6j0Q38.mjs +0 -2
- package/dist/validation-Du6j0Q38.mjs.map +0 -1
- package/dist/validation-tgjL_9n8.mjs +0 -2
- package/dist/validator-DMlEScV3.mjs +0 -2
- package/dist/version-De1l_ZMF.mjs +0 -2
- /package/dist/{contract-BHUOUAZ-.d.mts → contract-CIIqgFyb.d.mts} +0 -0
- /package/dist/{sql--yhoVvRM.d.mts → sql-BvfwUKIh.d.mts} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,n}from"./base-AdXAoy6l.mjs";import{i as r}from"./validation-Dk9Q_-C7.mjs";import{n as i}from"./suppressed-failure-BwULh-8h.mjs";import{t as a}from"./settle-B9Vg1FnP.mjs";const o=`SELECT pg_advisory_unlock_all()`,s=`could not prove the advisory-lock state of a discarded migration session: its "${o}" reset failed.`,c=5e3;function unprovenLockStateError(e,n,r){return abandonedSessionError(e,s,n,t(r))}function abandonedSessionError(e,t,i,a){return new r(`Driver "${e}" ${t} ${i}`,{code:n.CONNECTION_CLOSED,cause:a,meta:{driver:e,operation:`pinnedSession`}})}function condemnedSessionError(e){return new r(`Driver "${e}" will pin no further migration session: an earlier session's "${o}" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,{code:n.CONNECTION_CLOSED,meta:{driver:e,operation:`pinnedSession`}})}const l=`The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.`;async function releaseReservedPostgresSession(e){if(e.lost===!0){let{closeOwnedTransport:t,driverName:n}=e;if(t===void 0)throw abandonedSessionError(n,`lost the connection of a reserved migration session and sent nothing more on it.`,l,void 0);t().catch(()=>void 0);return}if(!e.discard){e.release();return}try{await a(e.reset(),c,()=>Error(`The advisory-lock reset went unanswered for ${c} ms.`))}catch(t){await abandon(e,s,t)}e.release()}async function abandon(e,n,r){let{closeOwnedTransport:a,driverName:o}=e;if(a===void 0)throw abandonedSessionError(o,n,l,t(r));try{await a()}catch(e){throw i(abandonedSessionError(o,n,`The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.`,t(r)),e)}throw abandonedSessionError(o,n,`The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.`,t(r))}const u=new WeakMap;function refuseCondemnedSession(e,t){if(t.condemned)throw condemnedSessionError(e)}function leasePinnedCommand(e,t,n){let r=physicalSessionState(t);refuseCondemnedSession(e,r);let i=r.queued.then(()=>(refuseCondemnedSession(e,r),n()));return r.queued=i.then(()=>void 0,()=>void 0),i}function condemnPhysicalSession(e){physicalSessionState(e).condemned=!0}function physicalSessionState(e){let t=u.get(e);if(t)return t;let n={queued:Promise.resolve(),condemned:!1};return u.set(e,n),n}export{unprovenLockStateError as a,releaseReservedPostgresSession as i,condemnPhysicalSession as n,leasePinnedCommand as r,c as t};
|
|
2
|
+
//# sourceMappingURL=pinned-session-CLxj5M5e.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pinned-session-CLxj5M5e.mjs","names":[],"sources":["../src/drivers/shared/pinned-session.ts"],"sourcesContent":["import { ConnectionError, VibORMErrorCode } from \"@errors\";\nimport { errorCause } from \"../../errors/diagnostic-safety\";\nimport { settleWithin } from \"./settle\";\nimport { withSuppressedFailure } from \"./suppressed-failure\";\n\n/** The PostgreSQL statement that resets a session's advisory-lock state. */\nconst ADVISORY_RESET = \"SELECT pg_advisory_unlock_all()\";\n\n/** Why a reserved session is abandoned, in the refusal's own words. */\nconst LOST_SESSION =\n \"lost the connection of a reserved migration session and sent nothing more on it.\";\nconst ADVISORY_RESET_FAILED = `could not prove the advisory-lock state of a discarded migration session: its \"${ADVISORY_RESET}\" reset failed.`;\n\n/**\n * How long one cleanup statement — `ROLLBACK`, the unlock, the limits reset,\n * the advisory reset — may take before its session is treated as lost.\n *\n * A healthy server answers each of them in milliseconds. A session that does\n * not answer one within this bound is a half-open socket or a dying backend,\n * and waiting on it longer only keeps the caller from the failure it already\n * has (plan S2: \"bound every cleanup statement\").\n */\nexport const CLEANUP_BOUND_MS = 5000;\n\n/**\n * One reserved physical session, as a provider hands it back.\n *\n * The plan's requirement (§3.5) is \"one physical producer across decisions and\n * commit boundaries\": a session lock is session-scoped, so acquiring it through\n * one pooled connection and running the protected work through another protects\n * nothing and can strand the lock. A reservation is therefore a connection the\n * provider has taken OUT of its pool, plus the exact way to give it back.\n */\nexport interface PinnedSessionReservation<TSession> {\n /** The reserved producer. Every statement of the session runs on it. */\n readonly session: TSession;\n /**\n * The failure the provider itself saw end this session's connection, or\n * `undefined` while it has seen none.\n *\n * Only a provider that observes its connection has one (`pg`, through the\n * client's `error` event). Elsewhere a lost connection is recognized by the\n * failure that reported it.\n */\n readonly lost?: () => unknown;\n /**\n * Returns the producer to the provider.\n *\n * `discard` is true when the session's state is unknown — a failed unlock, a\n * failed cleanup, or a thrown body — and the provider must then destroy the\n * connection rather than hand a session carrying unknown state back to a\n * pool. A provider whose session can never be made clean again (MySQL2, which\n * has executed `USE` and possibly author-owned statements) destroys\n * unconditionally and ignores the flag.\n *\n * `lost` is true when the connection itself is gone or stopped answering:\n * the provider must send nothing more on it — not even the reset a discard\n * otherwise runs — and abandon or destroy it.\n */\n release(discard: boolean, lost?: boolean): Promise<void>;\n}\n\n/**\n * The handle the pinned body uses to condemn its own producer.\n *\n * A thrown body already condemns the session. This exists for the case that\n * does not throw: an unlock statement that RETURNS a result proving the lock\n * was not released. That session is still usable in the provider's eyes and\n * would be returned to the pool holding a lock nobody owns.\n */\nexport interface PinnedSessionControl {\n /** Condemn this producer; it will be destroyed instead of released. */\n discard(): void;\n /**\n * Whether this session's connection is gone: the provider saw it end,\n * `failure` reports it, or a cleanup statement went unanswered. Once true it\n * stays true, and nothing more is sent on the session (plan S2).\n */\n lost(failure?: unknown): boolean;\n /** Runs one cleanup statement within `CLEANUP_BOUND_MS`; past it, the session is lost. */\n cleanup<T>(run: () => Promise<T>): Promise<T>;\n}\n\n/**\n * The refusal a discarded session whose reset FAILED raises.\n *\n * A session is discarded because its state is unknown, and the reset is what\n * makes it known again. When the reset fails too, the session may still hold\n * the migration lock every other command is excluded by — so it must not go\n * back to the provider, and saying nothing about that is not an option either:\n * a swallowed cleanup failure is how a pool ends up serving a connection that\n * blocks the next migration forever.\n *\n * The reset's own failure is the evidence, and it is the PROVIDER's value: it\n * goes through the one total normalizer rather than a bare `instanceof`, which\n * a rejection whose `getPrototypeOf` trap throws turns into a throw inside this\n * constructor — replacing the whole typed refusal with the trap's error.\n */\nexport function unprovenLockStateError(\n driverName: string,\n containment: string,\n cause: unknown\n): ConnectionError {\n return abandonedSessionError(\n driverName,\n ADVISORY_RESET_FAILED,\n containment,\n errorCause(cause)\n );\n}\n\nfunction abandonedSessionError(\n driverName: string,\n reason: string,\n containment: string,\n cause: Error | undefined\n): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" ${reason} ${containment}`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n cause,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * The refusal raised afterwards by EVERY driver whose one client was condemned.\n *\n * A transport that pools connections recovers by reserving a different one, so\n * this is only for the driver whose single client IS the session: there is no\n * other connection to reach for, and running the next migration command on a\n * session that may still hold the lock is precisely what the condemnation\n * exists to prevent. Two drivers over that one client are two callers of this\n * same refusal, because the session they would both pin is the same session.\n */\nexport function condemnedSessionError(driverName: string): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" will pin no further migration session: an earlier session's \"${ADVISORY_RESET}\" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * What was actually DONE about the abandoned connection, in the refusal's own\n * words.\n *\n * Three outcomes, three sentences, each chosen once the outcome is known\n * rather than once the ownership is known. A single sentence written before the\n * close was attempted claimed the backend had been ended even when ending it\n * threw — and the one thing a caller does with that claim is stop looking for a\n * connection that is still running, still holding the lock this refusal exists\n * to report.\n */\nconst CALLER_OWNED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.\";\nconst CLOSED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.\";\nconst CLOSE_FAILED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.\";\n\n/**\n * Returns a reserved PostgreSQL session to its pool, or condemns it — the ONE\n * rule for every provider that reserves a connection it cannot destroy.\n *\n * postgres.js and Bun SQL both expose `release()` and nothing else: there is no\n * destructive return to reach for, so a session whose reset failed is ABANDONED\n * — never released — which is the only way it stops being a connection the pool\n * will hand to the next caller.\n *\n * Abandoning it leaves the lock held until that backend goes away, so a\n * transport VibORM created is closed too: ending it terminates the backend, and\n * PostgreSQL frees every advisory lock the session held. A transport the CALLER\n * supplied is never closed for this — it is theirs, may be serving their own\n * code, and closing it to tidy up VibORM's cleanup failure would be a far\n * larger effect than the one being contained.\n *\n * A LOST session (plan S2) is abandoned the same way without the reset: its\n * connection is gone or stopped answering, and a statement written to it is,\n * on postgres.js, an uncaught crash from inside the provider's write loop. Its\n * owned transport is closed; a supplied one is reported, since abandoning is\n * all VibORM may do with it.\n */\nexport async function releaseReservedPostgresSession(reservation: {\n readonly driverName: string;\n readonly discard: boolean;\n readonly lost?: boolean | undefined;\n /** Runs `SELECT pg_advisory_unlock_all()` on the reserved session. */\n readonly reset: () => Promise<unknown>;\n /** Hands the reserved session back to the provider's pool. */\n readonly release: () => void;\n /** Closes the transport, or absent when the CALLER owns it. */\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n}): Promise<void> {\n if (reservation.lost === true) {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n LOST_SESSION,\n CALLER_OWNED_CONTAINMENT,\n undefined\n );\n }\n // Not awaited: the connection failure the caller holds is already the\n // answer, and the close lets the transport's other queries finish first\n // (postgres.js waits on the dead connection's unsettled query until its\n // bound). The transport is withdrawn before it closes, and a session the\n // close cannot end is ended by the server's idle limit.\n closeOwnedTransport().catch(() => undefined);\n return;\n }\n if (!reservation.discard) {\n reservation.release();\n return;\n }\n\n try {\n await settleWithin(\n reservation.reset(),\n CLEANUP_BOUND_MS,\n () =>\n new Error(\n `The advisory-lock reset went unanswered for ${CLEANUP_BOUND_MS} ms.`\n )\n );\n } catch (resetFailure) {\n await abandon(reservation, ADVISORY_RESET_FAILED, resetFailure);\n }\n reservation.release();\n}\n\n/**\n * Abandons a reserved session: never released, its owned transport closed,\n * and the refusal that says so thrown. A transport the caller supplied is only\n * abandoned.\n */\nasync function abandon(\n reservation: {\n readonly driverName: string;\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n },\n reason: string,\n cause: unknown\n): Promise<void> {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n reason,\n CALLER_OWNED_CONTAINMENT,\n errorCause(cause)\n );\n }\n try {\n await closeOwnedTransport();\n } catch (closeFailure) {\n // The reason stays primary — it is what the caller acts on — and the\n // close's own failure is cleanup evidence beside it.\n throw withSuppressedFailure(\n abandonedSessionError(\n driverName,\n reason,\n CLOSE_FAILED_CONTAINMENT,\n errorCause(cause)\n ),\n closeFailure\n );\n }\n throw abandonedSessionError(\n driverName,\n reason,\n CLOSED_CONTAINMENT,\n errorCause(cause)\n );\n}\n\n/** What VibORM knows about one PHYSICAL session it pins commands on. */\ninterface PhysicalSessionState {\n /**\n * The pinned commands already queued on this session. It never rejects, so\n * one command's failure cannot poison the queue — the next command runs\n * either way, exactly as it would after a success.\n */\n queued: Promise<void>;\n /**\n * Set when a discarded session's advisory-lock reset failed, and never\n * cleared: nothing that happens later can prove a lock was released.\n */\n condemned: boolean;\n}\n\n/**\n * What is known about each PHYSICAL session, keyed on the session itself.\n *\n * A driver's connection queue serializes the commands of THAT driver. Two\n * drivers built over one supplied client — the documented shape for two\n * schema-scoped estates over one PGlite — own two queues and one session, so\n * the queue arbitrates nothing between them, and a PostgreSQL session advisory\n * lock is REENTRANT: the second command re-acquires the lock the first is\n * holding instead of waiting for it, then reads and writes inside the first\n * command's session. The client is the only thing both drivers agree on, so it\n * is what this is keyed on.\n *\n * The condemnation shares that key because it answers for the same subject: a\n * failed reset leaves the CLIENT's lock state unknown, not the wrapper's. Kept\n * on the driver instead, it was a fact the other wrappers over that client\n * never consulted, and their next command ran inside the session it condemned.\n *\n * Weak by construction: the entry dies with the client, and a client nobody\n * holds keeps nothing alive here.\n */\nconst PHYSICAL_SESSIONS = new WeakMap<object, PhysicalSessionState>();\n\n/**\n * Refuses a command on a session whose advisory-lock state was condemned.\n *\n * One refusal, read at two moments, and each covers what the other cannot. At\n * ADMISSION, so a session condemned before this command arrived refuses now\n * rather than behind a queue whose head may itself be waiting on the very lock\n * nobody can account for. At the FRONT of the queue, because condemnation lands\n * BETWEEN the two: the command ahead of this one is the one whose reset fails,\n * and this one was admitted while that session still looked accountable.\n */\nfunction refuseCondemnedSession(\n driverName: string,\n state: PhysicalSessionState\n): void {\n if (state.condemned) {\n throw condemnedSessionError(driverName);\n }\n}\n\n/**\n * Runs `command` exclusively on this physical session, when it may still be\n * pinned at all.\n *\n * The refusal is here rather than beside it because this is the one path every\n * pinned command over a shared session takes, and it lands before `command` —\n * so no body and no statement of the refused command reaches the client.\n */\nexport function leasePinnedCommand<T>(\n driverName: string,\n session: object,\n command: () => Promise<T>\n): Promise<T> {\n const state = physicalSessionState(session);\n refuseCondemnedSession(driverName, state);\n const next = state.queued.then(() => {\n refuseCondemnedSession(driverName, state);\n return command();\n });\n state.queued = next.then(\n () => undefined,\n () => undefined\n );\n return next;\n}\n\n/**\n * Records that this physical session's advisory-lock state can no longer be\n * accounted for — for every driver that reaches it, not only the one whose\n * reset failed.\n */\nexport function condemnPhysicalSession(session: object): void {\n physicalSessionState(session).condemned = true;\n}\n\n/** This session's state, created on first use and mutated in place after. */\nfunction physicalSessionState(session: object): PhysicalSessionState {\n const existing = PHYSICAL_SESSIONS.get(session);\n if (existing) {\n return existing;\n }\n const created: PhysicalSessionState = {\n queued: Promise.resolve(),\n condemned: false,\n };\n PHYSICAL_SESSIONS.set(session, created);\n return created;\n}\n"],"mappings":"iOAMA,MAAM,EAAiB,kCA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AoB,IAAI,QAY9B,SAAS,uBACP,EACA,EACM,CACN,GAAI,EAAM,UACR,MAAM,sBAAsB,EAAW,CAY3C,SAAgB,mBACd,EACA,EACA,EACY,CACZ,IAAM,EAAQ,qBAAqB,EAAQ,CAC3C,uBAAuB,EAAY,EAAM,CACzC,IAAM,EAAO,EAAM,OAAO,UACxB,uBAAuB,EAAY,EAAM,CAClC,GAAS,EAChB,CAKF,MAJA,GAAM,OAAS,EAAK,SACZ,IAAA,OACA,IAAA,GACP,CACM,EAQT,SAAgB,uBAAuB,EAAuB,CAC5D,qBAAqB,EAAQ,CAAC,UAAY,GAI5C,SAAS,qBAAqB,EAAuC,CACnE,IAAM,EAAW,EAAkB,IAAI,EAAQ,CAC/C,GAAI,EACF,OAAO,EAET,IAAM,EAAgC,CACpC,OAAQ,QAAQ,SAAS,CACzB,UAAW,GACZ,CAED,OADA,EAAkB,IAAI,EAAS,EAAQ,CAChC"}
|
package/dist/planetscale.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as Schema, B as LinkedClientConfig, Dn as TransactionOptionSupport, En as DriverTransactionOptions, Mn as QueryResult, Pt as DriverConfig, Rt as NoExtraDriverConfigKeys, jn as QueryExecutionContext, s as DatabaseAdapter, u as Driver, zt as VibORMClient } from "./index-Likdf5qP.mjs";
|
|
2
2
|
import { Client, Config, Connection } from "@planetscale/database";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/planetscale/index.d.ts
|
package/dist/planetscale.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./value-guards-CK9guf2Z.mjs";import{c as n,s as r}from"./bind-parameter-capacity-CjPgqnmx.mjs";import{l as i,p as a}from"./error-mapping-CnPCv1dm.mjs";import{f as o}from"./validation-Dk9Q_-C7.mjs";import{s}from"./execution-context-BKR3bgES.mjs";import{n as c}from"./client-BLiBmykn.mjs";import{a as l,c as u,d,o as f,t as p}from"./driver-BlnKXPFF.mjs";import{t as m}from"./sql-statement-tokens-BBcoGmJb.mjs";import{t as h}from"./mysql-adapter-DkJPfoGf.mjs";const g=/^(?:0|[1-9]\d*)$/,_=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,v=new Set([`ANALYZE`,`CALL`,`DESC`,`DESCRIBE`,`EXPLAIN`,`SELECT`,`SHOW`,`VALUES`]),y=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),b=new Set([`ALTER`,`BEGIN`,`COMMIT`,`CREATE`,`DROP`,`LOCK`,`RELEASE`,`RENAME`,`ROLLBACK`,`SAVEPOINT`,`SET`,`TRUNCATE`,`UNLOCK`,`USE`]),x=new Set([...v,...y]),defaultFetch=async(e,t)=>globalThis.fetch(e,t);function isRecord(e){return typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Object]`}function isExecuteEndpoint(e){try{return new URL(e).pathname===`/psdb.v1alpha1.Database/Execute`}catch{return!1}}function getRequestQuery(e){if(typeof e==`string`)try{let t=JSON.parse(e);return isRecord(t)&&typeof t.query==`string`?t.query:void 0}catch{return}}function classifyStatement(e){if(!e)return`unknown`;let t=m(e,{backslashEscapes:!0}),n=t?.[0];if(!(t&&n)||n.kind!==`word`)return`unknown`;let r=0;if(n.value===`WITH`&&(r=t.findIndex((e,t)=>t>0&&e.kind===`word`&&x.has(e.value)),r<0))return`unknown`;let i=t[r]?.value;return i?v.has(i)?`rows`:y.has(i)?t.slice(r+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:b.has(i)?`no-rows`:`unknown`:`unknown`}function malformedPlanetScaleResponse(e){return new o(`Driver "planetscale" returned a malformed successful response: ${e}.`,{meta:{driver:`planetscale`}})}function assertDenseArray(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1)if(!Object.hasOwn(e,t))return!1;return!0}function validateFields(e){if(!assertDenseArray(e))throw malformedPlanetScaleResponse(`result.fields is not a dense array`);let t=[],n=new Set;for(let r of e){if(!isRecord(r)||typeof r.name!=`string`||r.name.length===0||r.type!==void 0&&typeof r.type!=`string`)throw malformedPlanetScaleResponse(`result.fields contains an invalid field descriptor`);if(r.name===`__proto__`||n.has(r.name))throw malformedPlanetScaleResponse(`result.fields contains an unsafe or duplicate field name`);n.add(r.name),t.push(r)}return t}function validateRows(e,t){if(!assertDenseArray(e))throw malformedPlanetScaleResponse(`result.rows is not a dense array`);if(e.length>0&&t.length===0)throw malformedPlanetScaleResponse(`non-empty result.rows has no matching field metadata`);for(let n of e){if(!(isRecord(n)&&assertDenseArray(n.lengths)))throw malformedPlanetScaleResponse(`result.rows contains a row that does not match result.fields`);let e=getExpectedRowByteLength(n.lengths,t.length),r=getBase64ByteLength(n.values);if(e===void 0||r!==e)throw malformedPlanetScaleResponse(`result.rows contains a row that does not match result.fields`)}}function getExpectedRowByteLength(e,t){if(e.length!==t)return;let n=0;for(let t of e){if(t===`-1`)continue;if(typeof t!=`string`||!g.test(t))return;let e=Number(t);if(!Number.isSafeInteger(e)||n>2**53-1-e)return;n+=e}return n}function getBase64ByteLength(e){if(e===void 0)return 0;if(!(typeof e!=`string`||!_.test(e)))try{let t=atob(e);return btoa(t)===e?t.length:void 0}catch{return}}function validateExecuteEnvelope(e,t){if(!isRecord(e))throw malformedPlanetScaleResponse(`the response body is not an object`);if(Object.hasOwn(e,`error`)&&e.error!=null)return;if(!Object.hasOwn(e,`result`))throw malformedPlanetScaleResponse(`the result member is absent`);let n=e.result;if(n===null){if(t===`no-rows`)return;throw malformedPlanetScaleResponse(`a row-producing or unknown statement has a null result member`)}if(!isRecord(n))throw malformedPlanetScaleResponse(`the result member is not an object or null`);let r=[];if(Object.hasOwn(n,`fields`)&&n.fields!==null&&(r=validateFields(n.fields)),t!==`no-rows`&&r.length===0)throw malformedPlanetScaleResponse(`a row-producing or unknown statement has no field metadata`);if(Object.hasOwn(n,`rows`)&&validateRows(n.rows,r),Object.hasOwn(n,`rowsAffected`)&&n.rowsAffected!==null&&(typeof n.rowsAffected!=`string`||!g.test(n.rowsAffected)))throw malformedPlanetScaleResponse(`result.rowsAffected is malformed`);if(Object.hasOwn(n,`insertId`)&&n.insertId!==null&&(typeof n.insertId!=`string`||!g.test(n.insertId)))throw malformedPlanetScaleResponse(`result.insertId is malformed`)}function wrapExecuteResponse(e,t){return new Proxy(e,{get(e,n){if(n===`json`)return async()=>{let n;try{n=await e.json()}catch{throw malformedPlanetScaleResponse(`the response body is not valid JSON`)}return validateExecuteEnvelope(n,t),n};if(n===`text`)return async()=>{let n=await e.text(),r;try{r=JSON.parse(n)}catch{throw malformedPlanetScaleResponse(`the response body is not valid JSON`)}return validateExecuteEnvelope(r,t),n};let r=Reflect.get(e,n,e);return typeof r==`function`?r.bind(e):r}})}function createValidatedPlanetScaleFetch(e){let t=e??defaultFetch;return async(e,n)=>{let r=classifyStatement(getRequestQuery(n?.body)),i=await t(e,n);return isExecuteEndpoint(e)&&i.ok?wrapExecuteResponse(i,r):i}}const S={client:!0,databaseUrl:!0,options:!0,namespace:!0};function toQueryResult(e,t){let i={provider:`planetscale`,operation:t},a=r(e.insertId,i);return{rows:e.rows,rowCount:n(e.rowsAffected,i),...a===void 0?{}:{insertId:a}}}var PlanetScaleDriver=class extends p{maxBindParametersPerStatement=65535;supportsTransactions=!0;driverOptions;constructor(e={}){let t=d(e);super(`mysql`,`planetscale`),this.driverOptions=e,f(this,`adapter`,new h(t))}async initClient(){let{Client:e}=await import(`@planetscale/database`),n=this.driverOptions.client;if(n){if(!t(n.config))return n;let r={...n.config};return r.fetch=createValidatedPlanetScaleFetch(r.fetch),new e(r)}let r={...this.driverOptions.options};return this.driverOptions.databaseUrl&&(r.url=this.driverOptions.databaseUrl),r.fetch=createValidatedPlanetScaleFetch(r.fetch),new e(r)}async closeClient(e){}async execute(e,t,n,r){let i=r?.operation??`execute`;return toQueryResult(await e.execute(t,n),i)}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`;return toQueryResult(await e.execute(t,n),i)}transactionOptionSupport(){return{isolationLevel:`pre-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`each PlanetScale transaction gets its own HTTP connection created without waiting, so there is no acquisition maxWait could bound`}}async transaction(e,t,n,r){if(!(`transaction`in e))throw i(this.driverName);let o=`connection`in e?e.connection():e,c=r?.isolationLevel;return a({begin:async()=>{await o.execute(`SET transaction_mode = 'single'`),c&&await o.execute(l(c)),await o.execute(`BEGIN`)},callback:()=>t(o),commit:()=>o.execute(`COMMIT`),rollback:()=>o.execute(`ROLLBACK`),phases:s(n)})}transactionCleanupFailed(e){this.client&&`connection`in this.client||super.transactionCleanupFailed(e)}};function createClient(e){u(e,`planetscale`,S);let{client:t,databaseUrl:n,options:r}=e;return c(e,new PlanetScaleDriver({client:t,databaseUrl:n,options:r,namespace:d(e)}))}export{PlanetScaleDriver,createClient};
|
|
2
2
|
//# sourceMappingURL=planetscale.mjs.map
|
package/dist/planetscale.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"planetscale.mjs","names":["isRecord","config"],"sources":["../src/drivers/planetscale/response-contract.ts","../src/drivers/planetscale/index.ts"],"sourcesContent":["import { QueryError } from \"@errors\";\nimport type { Config } from \"@planetscale/database\";\nimport { getTopLevelStatementTokens } from \"../shared/sql-statement-tokens\";\n\ntype PlanetScaleFetch = NonNullable<Config[\"fetch\"]>;\ntype PlanetScaleResponse = Awaited<ReturnType<PlanetScaleFetch>>;\n\nconst NON_NEGATIVE_DECIMAL = /^(?:0|[1-9]\\d*)$/;\nconst BASE64_REGEX =\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nconst ROW_COMMANDS = new Set([\n \"ANALYZE\",\n \"CALL\",\n \"DESC\",\n \"DESCRIBE\",\n \"EXPLAIN\",\n \"SELECT\",\n \"SHOW\",\n \"VALUES\",\n]);\nconst MUTATION_COMMANDS = new Set([\"DELETE\", \"INSERT\", \"REPLACE\", \"UPDATE\"]);\nconst NO_ROW_COMMANDS = new Set([\n \"ALTER\",\n \"BEGIN\",\n \"COMMIT\",\n \"CREATE\",\n \"DROP\",\n \"LOCK\",\n \"RELEASE\",\n \"RENAME\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"SET\",\n \"TRUNCATE\",\n \"UNLOCK\",\n \"USE\",\n]);\nconst WITH_COMMANDS = new Set([...ROW_COMMANDS, ...MUTATION_COMMANDS]);\n\ntype StatementResultKind = \"rows\" | \"no-rows\" | \"unknown\";\n\nconst defaultFetch: PlanetScaleFetch = async (input, init) => {\n return globalThis.fetch(input, init);\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\nfunction isExecuteEndpoint(input: string): boolean {\n try {\n return new URL(input).pathname === \"/psdb.v1alpha1.Database/Execute\";\n } catch {\n return false;\n }\n}\n\nfunction getRequestQuery(body: unknown): string | undefined {\n if (typeof body !== \"string\") return undefined;\n try {\n const value: unknown = JSON.parse(body);\n return isRecord(value) && typeof value.query === \"string\"\n ? value.query\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction classifyStatement(sql: string | undefined): StatementResultKind {\n if (!sql) return \"unknown\";\n const tokens = getTopLevelStatementTokens(sql, { backslashEscapes: true });\n const first = tokens?.[0];\n if (!(tokens && first) || first.kind !== \"word\") return \"unknown\";\n\n let commandIndex = 0;\n if (first.value === \"WITH\") {\n commandIndex = tokens.findIndex(\n (token, index) =>\n index > 0 && token.kind === \"word\" && WITH_COMMANDS.has(token.value)\n );\n if (commandIndex < 0) return \"unknown\";\n }\n\n const command = tokens[commandIndex]?.value;\n if (!command) return \"unknown\";\n if (ROW_COMMANDS.has(command)) return \"rows\";\n if (MUTATION_COMMANDS.has(command)) {\n return tokens\n .slice(commandIndex + 1)\n .some((token) => token.kind === \"word\" && token.value === \"RETURNING\")\n ? \"rows\"\n : \"no-rows\";\n }\n return NO_ROW_COMMANDS.has(command) ? \"no-rows\" : \"unknown\";\n}\n\nfunction malformedPlanetScaleResponse(reason: string): QueryError {\n return new QueryError(\n `Driver \"planetscale\" returned a malformed successful response: ${reason}.`,\n { meta: { driver: \"planetscale\" } }\n );\n}\n\nfunction assertDenseArray(value: unknown): value is unknown[] {\n if (!Array.isArray(value)) return false;\n for (let index = 0; index < value.length; index += 1) {\n if (!Object.hasOwn(value, index)) return false;\n }\n return true;\n}\n\nfunction validateFields(value: unknown): Record<string, unknown>[] {\n if (!assertDenseArray(value)) {\n throw malformedPlanetScaleResponse(\"result.fields is not a dense array\");\n }\n const fields: Record<string, unknown>[] = [];\n const fieldNames = new Set<string>();\n for (const field of value) {\n if (\n !isRecord(field) ||\n typeof field.name !== \"string\" ||\n field.name.length === 0 ||\n (field.type !== undefined && typeof field.type !== \"string\")\n ) {\n throw malformedPlanetScaleResponse(\n \"result.fields contains an invalid field descriptor\"\n );\n }\n if (field.name === \"__proto__\" || fieldNames.has(field.name)) {\n throw malformedPlanetScaleResponse(\n \"result.fields contains an unsafe or duplicate field name\"\n );\n }\n fieldNames.add(field.name);\n fields.push(field);\n }\n return fields;\n}\n\nfunction validateRows(\n value: unknown,\n fields: readonly Record<string, unknown>[]\n): void {\n if (!assertDenseArray(value)) {\n throw malformedPlanetScaleResponse(\"result.rows is not a dense array\");\n }\n if (value.length > 0 && fields.length === 0) {\n throw malformedPlanetScaleResponse(\n \"non-empty result.rows has no matching field metadata\"\n );\n }\n for (const row of value) {\n if (!(isRecord(row) && assertDenseArray(row.lengths))) {\n throw malformedPlanetScaleResponse(\n \"result.rows contains a row that does not match result.fields\"\n );\n }\n const expectedBytes = getExpectedRowByteLength(row.lengths, fields.length);\n const actualBytes = getBase64ByteLength(row.values);\n if (expectedBytes === undefined || actualBytes !== expectedBytes) {\n throw malformedPlanetScaleResponse(\n \"result.rows contains a row that does not match result.fields\"\n );\n }\n }\n}\n\nfunction getExpectedRowByteLength(\n lengths: readonly unknown[],\n fieldCount: number\n): number | undefined {\n if (lengths.length !== fieldCount) return undefined;\n let total = 0;\n for (const length of lengths) {\n if (length === \"-1\") continue;\n if (typeof length !== \"string\" || !NON_NEGATIVE_DECIMAL.test(length)) {\n return undefined;\n }\n const parsed = Number(length);\n if (\n !Number.isSafeInteger(parsed) ||\n total > Number.MAX_SAFE_INTEGER - parsed\n ) {\n return undefined;\n }\n total += parsed;\n }\n return total;\n}\n\nfunction getBase64ByteLength(value: unknown): number | undefined {\n if (value === undefined) return 0;\n if (typeof value !== \"string\" || !BASE64_REGEX.test(value)) return undefined;\n try {\n const decoded = atob(value);\n return btoa(decoded) === value ? decoded.length : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction validateExecuteEnvelope(\n value: unknown,\n statementKind: StatementResultKind\n): void {\n if (!isRecord(value)) {\n throw malformedPlanetScaleResponse(\"the response body is not an object\");\n }\n\n // The SDK owns database-error translation. HTTP-200 error envelopes may omit\n // result, so leave them intact for its existing DatabaseError path.\n if (Object.hasOwn(value, \"error\") && value.error != null) return;\n\n if (!Object.hasOwn(value, \"result\")) {\n throw malformedPlanetScaleResponse(\"the result member is absent\");\n }\n const result = value.result;\n if (result === null) {\n if (statementKind === \"no-rows\") return;\n throw malformedPlanetScaleResponse(\n \"a row-producing or unknown statement has a null result member\"\n );\n }\n if (!isRecord(result)) {\n throw malformedPlanetScaleResponse(\n \"the result member is not an object or null\"\n );\n }\n\n let fields: Record<string, unknown>[] = [];\n if (Object.hasOwn(result, \"fields\") && result.fields !== null) {\n fields = validateFields(result.fields);\n }\n if (statementKind !== \"no-rows\" && fields.length === 0) {\n throw malformedPlanetScaleResponse(\n \"a row-producing or unknown statement has no field metadata\"\n );\n }\n if (Object.hasOwn(result, \"rows\")) {\n validateRows(result.rows, fields);\n }\n if (\n Object.hasOwn(result, \"rowsAffected\") &&\n result.rowsAffected !== null &&\n (typeof result.rowsAffected !== \"string\" ||\n !NON_NEGATIVE_DECIMAL.test(result.rowsAffected))\n ) {\n throw malformedPlanetScaleResponse(\"result.rowsAffected is malformed\");\n }\n if (\n Object.hasOwn(result, \"insertId\") &&\n result.insertId !== null &&\n (typeof result.insertId !== \"string\" ||\n !NON_NEGATIVE_DECIMAL.test(result.insertId))\n ) {\n throw malformedPlanetScaleResponse(\"result.insertId is malformed\");\n }\n}\n\nfunction wrapExecuteResponse(\n response: PlanetScaleResponse,\n statementKind: StatementResultKind\n): PlanetScaleResponse {\n return new Proxy(response, {\n get(target, property) {\n if (property === \"json\") {\n return async () => {\n let value: unknown;\n try {\n value = await target.json();\n } catch {\n throw malformedPlanetScaleResponse(\n \"the response body is not valid JSON\"\n );\n }\n validateExecuteEnvelope(value, statementKind);\n return value;\n };\n }\n if (property === \"text\") {\n return async () => {\n const body = await target.text();\n let value: unknown;\n try {\n value = JSON.parse(body);\n } catch {\n throw malformedPlanetScaleResponse(\n \"the response body is not valid JSON\"\n );\n }\n validateExecuteEnvelope(value, statementKind);\n return body;\n };\n }\n const member = Reflect.get(target, property, target);\n return typeof member === \"function\" ? member.bind(target) : member;\n },\n });\n}\n\nexport function createValidatedPlanetScaleFetch(\n fetchOption: Config[\"fetch\"]\n): PlanetScaleFetch {\n const fetchImpl = fetchOption ?? defaultFetch;\n return async (input, init) => {\n const statementKind = classifyStatement(getRequestQuery(init?.body));\n const response = await fetchImpl(input, init);\n return isExecuteEndpoint(input) && response.ok\n ? wrapExecuteResponse(response, statementKind)\n : response;\n };\n}\n","/**\n * PlanetScale Driver (Vitess MySQL)\n *\n * Driver implementation for @planetscale/database - PlanetScale's serverless MySQL driver.\n * Transactions pin one Connection and enable Vitess SINGLE mode before BEGIN;\n * Client.transaction() is intentionally not used because it hides that setup.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { MySQLAdapter } from \"@adapters/databases/mysql/mysql-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 type { Client, Config, Connection } from \"@planetscale/database\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n normalizeProviderInsertId,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\nimport {\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n isolationLevelStatement,\n nestedTransactionDispatchError,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport type { QueryResult } from \"../types\";\nimport { createValidatedPlanetScaleFetch } from \"./response-contract\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type PlanetScaleOptions = Omit<Config, \"url\">;\n\nexport interface PlanetScaleDriverOptions {\n client?: Client;\n databaseUrl?: string;\n options?: PlanetScaleOptions;\n /**\n * The Vitess keyspace qualifier this driver submits before VTGate applies\n * routing rules. It is never inferred from the PlanetScale database\n * resource, the SDK config, the URL, or a `@primary`/`@replica` selector,\n * and an omitted value leaves routing entirely with PlanetScale.\n */\n namespace?: string;\n}\n\nexport type PlanetScaleClientConfig<C extends DriverConfig> =\n PlanetScaleDriverOptions & C;\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\ntype PlanetScaleClient = Client | Connection;\ntype PlanetScaleTransaction = Pick<Connection, \"execute\">;\n\n/** PlanetScale reports insertId as a string; \"0\" means none was generated. */\nfunction toQueryResult<T>(\n result: {\n rows: unknown[];\n rowsAffected: number;\n insertId: string;\n },\n operation: string\n): QueryResult<T> {\n const context = { provider: \"planetscale\", operation };\n const insertId = normalizeProviderInsertId(result.insertId, context);\n return {\n rows: result.rows as T[],\n rowCount: normalizeProviderRowCount(result.rowsAffected, context),\n ...(insertId === undefined ? {} : { insertId }),\n };\n}\n\nexport class PlanetScaleDriver extends Driver<\n PlanetScaleClient,\n PlanetScaleTransaction\n> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n readonly supportsTransactions = true;\n\n private readonly driverOptions: PlanetScaleDriverOptions;\n\n constructor(options: PlanetScaleDriverOptions = {}) {\n // Only the explicit option records a qualifier here. This driver exposes no\n // attestation option and never reads one, so its base fact stays an\n // immutable `undefined` whatever the caller's object carries.\n const namespace = resolveNamespaceOption(options);\n super(\"mysql\", \"planetscale\");\n this.driverOptions = options;\n defineImmutableDriverFact(this, \"adapter\", new MySQLAdapter(namespace));\n }\n\n protected async initClient(): Promise<PlanetScaleClient> {\n const { Client } = await import(\"@planetscale/database\");\n\n const providedClient = this.driverOptions.client;\n if (providedClient) {\n if (!isRecord(providedClient.config)) return providedClient;\n const config: Config = { ...providedClient.config };\n config.fetch = createValidatedPlanetScaleFetch(config.fetch);\n return new Client(config);\n }\n\n const config: Config = { ...this.driverOptions.options };\n\n if (this.driverOptions.databaseUrl) {\n config.url = this.driverOptions.databaseUrl;\n }\n\n config.fetch = createValidatedPlanetScaleFetch(config.fetch);\n\n return new Client(config);\n }\n\n protected async closeClient(_client: PlanetScaleClient): Promise<void> {\n // PlanetScale HTTP client doesn't need to be closed\n }\n\n protected async execute<T>(\n client: PlanetScaleClient | PlanetScaleTransaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const result = await client.execute(sql, params);\n return toQueryResult<T>(result, operation);\n }\n\n protected async executeRaw<T>(\n client: PlanetScaleClient | PlanetScaleTransaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const result = await client.execute(sql, params);\n return toQueryResult<T>(result, operation);\n }\n\n /**\n * MySQL semantics: the level must be set before BEGIN, and this driver owns\n * both statements on one `Connection`. Every transaction gets a fresh HTTP\n * `Connection` created synchronously, so there is no slot to wait for.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"pre-begin\",\n timeout: true,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"each PlanetScale transaction gets its own HTTP connection created without waiting, so there is no acquisition maxWait could bound\",\n };\n }\n\n protected async transaction<T>(\n client: PlanetScaleClient | PlanetScaleTransaction,\n fn: (tx: PlanetScaleTransaction) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (!(\"transaction\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n const connection: Connection =\n \"connection\" in client ? client.connection() : client;\n const isolationLevel = options?.isolationLevel;\n\n return runTransactionLifecycle({\n begin: async () => {\n // Vitess SINGLE mode rejects cross-shard transactions instead of using\n // best-effort multi-shard commit semantics.\n await connection.execute(\"SET transaction_mode = 'single'\");\n // Session-scoped-next-transaction: must precede BEGIN on this same\n // connection to bind to the transaction it opens.\n if (isolationLevel) {\n await connection.execute(isolationLevelStatement(isolationLevel));\n }\n await connection.execute(\"BEGIN\");\n },\n callback: () => fn(connection),\n commit: () => connection.execute(\"COMMIT\"),\n rollback: () => connection.execute(\"ROLLBACK\"),\n phases: getExecutionTransactionPhases(context),\n });\n }\n\n protected override transactionCleanupFailed(error: Error): void {\n if (this.client && \"connection\" in this.client) {\n // Each transaction used a fresh Connection that is now discarded.\n return;\n }\n super.transactionCleanupFailed(error);\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PlanetScaleClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PlanetScaleDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PlanetScaleDriver }\n >]: LinkedClientConfig<C & { driver: PlanetScaleDriver }>[P];\n}> {\n const { client, databaseUrl, options } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new PlanetScaleDriver({\n client,\n databaseUrl,\n options,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, PlanetScaleDriver>(config, driver);\n}\n"],"mappings":"ogBAOA,MAAM,EAAuB,mBACvB,EACJ,mEACI,EAAe,IAAI,IAAI,CAC3B,UACA,OACA,OACA,WACA,UACA,SACA,OACA,SACD,CAAC,CACI,EAAoB,IAAI,IAAI,CAAC,SAAU,SAAU,UAAW,SAAS,CAAC,CACtE,EAAkB,IAAI,IAAI,CAC9B,QACA,QACA,SACA,SACA,OACA,OACA,UACA,SACA,WACA,YACA,MACA,WACA,SACA,MACD,CAAC,CACI,EAAgB,IAAI,IAAI,CAAC,GAAG,EAAc,GAAG,EAAkB,CAAC,CAIhE,aAAiC,MAAO,EAAO,IAC5C,WAAW,MAAM,EAAO,EAAK,CAGtC,SAAS,SAAS,EAAkD,CAClE,OACE,OAAO,GAAU,YACjB,GACA,OAAO,UAAU,SAAS,KAAK,EAAM,GAAK,kBAI9C,SAAS,kBAAkB,EAAwB,CACjD,GAAI,CACF,OAAO,IAAI,IAAI,EAAM,CAAC,WAAa,uCAC7B,CACN,MAAO,IAIX,SAAS,gBAAgB,EAAmC,CACtD,UAAO,GAAS,SACpB,GAAI,CACF,IAAM,EAAiB,KAAK,MAAM,EAAK,CACvC,OAAO,SAAS,EAAM,EAAI,OAAO,EAAM,OAAU,SAC7C,EAAM,MACN,IAAA,QACE,CACN,QAIJ,SAAS,kBAAkB,EAA8C,CACvE,GAAI,CAAC,EAAK,MAAO,UACjB,IAAM,EAAS,EAA2B,EAAK,CAAE,iBAAkB,GAAM,CAAC,CACpE,EAAQ,IAAS,GACvB,GAAI,EAAE,GAAU,IAAU,EAAM,OAAS,OAAQ,MAAO,UAExD,IAAI,EAAe,EACnB,GAAI,EAAM,QAAU,SAClB,EAAe,EAAO,WACnB,EAAO,IACN,EAAQ,GAAK,EAAM,OAAS,QAAU,EAAc,IAAI,EAAM,MAAM,CACvE,CACG,EAAe,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AChB,QAAS,GACT,QAAS,cACT,cACE,oIACH,CAGH,MAAgB,YACd,EACA,EACA,EACA,EACY,CACZ,GAAI,EAAE,gBAAiB,GACrB,MAAM,EAA+B,KAAK,WAAW,CAGvD,IAAM,EACJ,eAAgB,EAAS,EAAO,YAAY,CAAG,EAC3C,EAAiB,GAAS,eAEhC,OAAO,EAAwB,CAC7B,MAAO,SAAY,CAGjB,MAAM,EAAW,QAAQ,kCAAkC,CAGvD,GACF,MAAM,EAAW,QAAQ,EAAwB,EAAe,CAAC,CAEnE,MAAM,EAAW,QAAQ,QAAQ,EAEnC,aAAgB,EAAG,EAAW,CAC9B,WAAc,EAAW,QAAQ,SAAS,CAC1C,aAAgB,EAAW,QAAQ,WAAW,CAC9C,OAAQ,EAA8B,EAAQ,CAC/C,CAAC,CAGJ,yBAA4C,EAAoB,CAC1D,KAAK,QAAU,eAAgB,KAAK,QAIxC,MAAM,yBAAyB,EAAM,GAQzC,SAAgB,aACd,EAOC,CACD,GAAM,CAAE,SAAQ,cAAa,WAAY,EAUzC,OAAO,EAAsD,EAP9C,IAAI,kBAAkB,CACnC,SACA,cACA,UACA,UANgB,EAAuB,EAAO,CAO/C,CAAC,CAE0E"}
|
|
1
|
+
{"version":3,"file":"planetscale.mjs","names":["isRecord","config"],"sources":["../src/drivers/planetscale/response-contract.ts","../src/drivers/planetscale/index.ts"],"sourcesContent":["import { QueryError } from \"@errors\";\nimport type { Config } from \"@planetscale/database\";\nimport { getTopLevelStatementTokens } from \"../shared/sql-statement-tokens\";\n\ntype PlanetScaleFetch = NonNullable<Config[\"fetch\"]>;\ntype PlanetScaleResponse = Awaited<ReturnType<PlanetScaleFetch>>;\n\nconst NON_NEGATIVE_DECIMAL = /^(?:0|[1-9]\\d*)$/;\nconst BASE64_REGEX =\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nconst ROW_COMMANDS = new Set([\n \"ANALYZE\",\n \"CALL\",\n \"DESC\",\n \"DESCRIBE\",\n \"EXPLAIN\",\n \"SELECT\",\n \"SHOW\",\n \"VALUES\",\n]);\nconst MUTATION_COMMANDS = new Set([\"DELETE\", \"INSERT\", \"REPLACE\", \"UPDATE\"]);\nconst NO_ROW_COMMANDS = new Set([\n \"ALTER\",\n \"BEGIN\",\n \"COMMIT\",\n \"CREATE\",\n \"DROP\",\n \"LOCK\",\n \"RELEASE\",\n \"RENAME\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"SET\",\n \"TRUNCATE\",\n \"UNLOCK\",\n \"USE\",\n]);\nconst WITH_COMMANDS = new Set([...ROW_COMMANDS, ...MUTATION_COMMANDS]);\n\ntype StatementResultKind = \"rows\" | \"no-rows\" | \"unknown\";\n\nconst defaultFetch: PlanetScaleFetch = async (input, init) => {\n return globalThis.fetch(input, init);\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\nfunction isExecuteEndpoint(input: string): boolean {\n try {\n return new URL(input).pathname === \"/psdb.v1alpha1.Database/Execute\";\n } catch {\n return false;\n }\n}\n\nfunction getRequestQuery(body: unknown): string | undefined {\n if (typeof body !== \"string\") return undefined;\n try {\n const value: unknown = JSON.parse(body);\n return isRecord(value) && typeof value.query === \"string\"\n ? value.query\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction classifyStatement(sql: string | undefined): StatementResultKind {\n if (!sql) return \"unknown\";\n const tokens = getTopLevelStatementTokens(sql, { backslashEscapes: true });\n const first = tokens?.[0];\n if (!(tokens && first) || first.kind !== \"word\") return \"unknown\";\n\n let commandIndex = 0;\n if (first.value === \"WITH\") {\n commandIndex = tokens.findIndex(\n (token, index) =>\n index > 0 && token.kind === \"word\" && WITH_COMMANDS.has(token.value)\n );\n if (commandIndex < 0) return \"unknown\";\n }\n\n const command = tokens[commandIndex]?.value;\n if (!command) return \"unknown\";\n if (ROW_COMMANDS.has(command)) return \"rows\";\n if (MUTATION_COMMANDS.has(command)) {\n return tokens\n .slice(commandIndex + 1)\n .some((token) => token.kind === \"word\" && token.value === \"RETURNING\")\n ? \"rows\"\n : \"no-rows\";\n }\n return NO_ROW_COMMANDS.has(command) ? \"no-rows\" : \"unknown\";\n}\n\nfunction malformedPlanetScaleResponse(reason: string): QueryError {\n return new QueryError(\n `Driver \"planetscale\" returned a malformed successful response: ${reason}.`,\n { meta: { driver: \"planetscale\" } }\n );\n}\n\nfunction assertDenseArray(value: unknown): value is unknown[] {\n if (!Array.isArray(value)) return false;\n for (let index = 0; index < value.length; index += 1) {\n if (!Object.hasOwn(value, index)) return false;\n }\n return true;\n}\n\nfunction validateFields(value: unknown): Record<string, unknown>[] {\n if (!assertDenseArray(value)) {\n throw malformedPlanetScaleResponse(\"result.fields is not a dense array\");\n }\n const fields: Record<string, unknown>[] = [];\n const fieldNames = new Set<string>();\n for (const field of value) {\n if (\n !isRecord(field) ||\n typeof field.name !== \"string\" ||\n field.name.length === 0 ||\n (field.type !== undefined && typeof field.type !== \"string\")\n ) {\n throw malformedPlanetScaleResponse(\n \"result.fields contains an invalid field descriptor\"\n );\n }\n if (field.name === \"__proto__\" || fieldNames.has(field.name)) {\n throw malformedPlanetScaleResponse(\n \"result.fields contains an unsafe or duplicate field name\"\n );\n }\n fieldNames.add(field.name);\n fields.push(field);\n }\n return fields;\n}\n\nfunction validateRows(\n value: unknown,\n fields: readonly Record<string, unknown>[]\n): void {\n if (!assertDenseArray(value)) {\n throw malformedPlanetScaleResponse(\"result.rows is not a dense array\");\n }\n if (value.length > 0 && fields.length === 0) {\n throw malformedPlanetScaleResponse(\n \"non-empty result.rows has no matching field metadata\"\n );\n }\n for (const row of value) {\n if (!(isRecord(row) && assertDenseArray(row.lengths))) {\n throw malformedPlanetScaleResponse(\n \"result.rows contains a row that does not match result.fields\"\n );\n }\n const expectedBytes = getExpectedRowByteLength(row.lengths, fields.length);\n const actualBytes = getBase64ByteLength(row.values);\n if (expectedBytes === undefined || actualBytes !== expectedBytes) {\n throw malformedPlanetScaleResponse(\n \"result.rows contains a row that does not match result.fields\"\n );\n }\n }\n}\n\nfunction getExpectedRowByteLength(\n lengths: readonly unknown[],\n fieldCount: number\n): number | undefined {\n if (lengths.length !== fieldCount) return undefined;\n let total = 0;\n for (const length of lengths) {\n if (length === \"-1\") continue;\n if (typeof length !== \"string\" || !NON_NEGATIVE_DECIMAL.test(length)) {\n return undefined;\n }\n const parsed = Number(length);\n if (\n !Number.isSafeInteger(parsed) ||\n total > Number.MAX_SAFE_INTEGER - parsed\n ) {\n return undefined;\n }\n total += parsed;\n }\n return total;\n}\n\nfunction getBase64ByteLength(value: unknown): number | undefined {\n if (value === undefined) return 0;\n if (typeof value !== \"string\" || !BASE64_REGEX.test(value)) return undefined;\n try {\n const decoded = atob(value);\n return btoa(decoded) === value ? decoded.length : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction validateExecuteEnvelope(\n value: unknown,\n statementKind: StatementResultKind\n): void {\n if (!isRecord(value)) {\n throw malformedPlanetScaleResponse(\"the response body is not an object\");\n }\n\n // The SDK owns database-error translation. HTTP-200 error envelopes may omit\n // result, so leave them intact for its existing DatabaseError path.\n if (Object.hasOwn(value, \"error\") && value.error != null) return;\n\n if (!Object.hasOwn(value, \"result\")) {\n throw malformedPlanetScaleResponse(\"the result member is absent\");\n }\n const result = value.result;\n if (result === null) {\n if (statementKind === \"no-rows\") return;\n throw malformedPlanetScaleResponse(\n \"a row-producing or unknown statement has a null result member\"\n );\n }\n if (!isRecord(result)) {\n throw malformedPlanetScaleResponse(\n \"the result member is not an object or null\"\n );\n }\n\n let fields: Record<string, unknown>[] = [];\n if (Object.hasOwn(result, \"fields\") && result.fields !== null) {\n fields = validateFields(result.fields);\n }\n if (statementKind !== \"no-rows\" && fields.length === 0) {\n throw malformedPlanetScaleResponse(\n \"a row-producing or unknown statement has no field metadata\"\n );\n }\n if (Object.hasOwn(result, \"rows\")) {\n validateRows(result.rows, fields);\n }\n if (\n Object.hasOwn(result, \"rowsAffected\") &&\n result.rowsAffected !== null &&\n (typeof result.rowsAffected !== \"string\" ||\n !NON_NEGATIVE_DECIMAL.test(result.rowsAffected))\n ) {\n throw malformedPlanetScaleResponse(\"result.rowsAffected is malformed\");\n }\n if (\n Object.hasOwn(result, \"insertId\") &&\n result.insertId !== null &&\n (typeof result.insertId !== \"string\" ||\n !NON_NEGATIVE_DECIMAL.test(result.insertId))\n ) {\n throw malformedPlanetScaleResponse(\"result.insertId is malformed\");\n }\n}\n\nfunction wrapExecuteResponse(\n response: PlanetScaleResponse,\n statementKind: StatementResultKind\n): PlanetScaleResponse {\n return new Proxy(response, {\n get(target, property) {\n if (property === \"json\") {\n return async () => {\n let value: unknown;\n try {\n value = await target.json();\n } catch {\n throw malformedPlanetScaleResponse(\n \"the response body is not valid JSON\"\n );\n }\n validateExecuteEnvelope(value, statementKind);\n return value;\n };\n }\n if (property === \"text\") {\n return async () => {\n const body = await target.text();\n let value: unknown;\n try {\n value = JSON.parse(body);\n } catch {\n throw malformedPlanetScaleResponse(\n \"the response body is not valid JSON\"\n );\n }\n validateExecuteEnvelope(value, statementKind);\n return body;\n };\n }\n const member = Reflect.get(target, property, target);\n return typeof member === \"function\" ? member.bind(target) : member;\n },\n });\n}\n\nexport function createValidatedPlanetScaleFetch(\n fetchOption: Config[\"fetch\"]\n): PlanetScaleFetch {\n const fetchImpl = fetchOption ?? defaultFetch;\n return async (input, init) => {\n const statementKind = classifyStatement(getRequestQuery(init?.body));\n const response = await fetchImpl(input, init);\n return isExecuteEndpoint(input) && response.ok\n ? wrapExecuteResponse(response, statementKind)\n : response;\n };\n}\n","/**\n * PlanetScale Driver (Vitess MySQL)\n *\n * Driver implementation for @planetscale/database - PlanetScale's serverless MySQL driver.\n * Transactions pin one Connection and enable Vitess SINGLE mode before BEGIN;\n * Client.transaction() is intentionally not used because it hides that setup.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { MySQLAdapter } from \"@adapters/databases/mysql/mysql-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 type { Client, Config, Connection } from \"@planetscale/database\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n normalizeProviderInsertId,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\nimport {\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n isolationLevelStatement,\n nestedTransactionDispatchError,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport type { QueryResult } from \"../types\";\nimport { createValidatedPlanetScaleFetch } from \"./response-contract\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type PlanetScaleOptions = Omit<Config, \"url\">;\n\nexport interface PlanetScaleDriverOptions {\n client?: Client;\n databaseUrl?: string;\n options?: PlanetScaleOptions;\n /**\n * The Vitess keyspace qualifier this driver submits before VTGate applies\n * routing rules. It is never inferred from the PlanetScale database\n * resource, the SDK config, the URL, or a `@primary`/`@replica` selector,\n * and an omitted value leaves routing entirely with PlanetScale.\n */\n namespace?: string;\n}\n\nexport type PlanetScaleClientConfig<C extends DriverConfig> =\n PlanetScaleDriverOptions & C;\n\nconst PLANETSCALE_CONFIG_KEYS: Record<keyof PlanetScaleDriverOptions, true> = {\n client: true,\n databaseUrl: true,\n options: true,\n namespace: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\ntype PlanetScaleClient = Client | Connection;\ntype PlanetScaleTransaction = Pick<Connection, \"execute\">;\n\n/** PlanetScale reports insertId as a string; \"0\" means none was generated. */\nfunction toQueryResult<T>(\n result: {\n rows: unknown[];\n rowsAffected: number;\n insertId: string;\n },\n operation: string\n): QueryResult<T> {\n const context = { provider: \"planetscale\", operation };\n const insertId = normalizeProviderInsertId(result.insertId, context);\n return {\n rows: result.rows as T[],\n rowCount: normalizeProviderRowCount(result.rowsAffected, context),\n ...(insertId === undefined ? {} : { insertId }),\n };\n}\n\nexport class PlanetScaleDriver extends Driver<\n PlanetScaleClient,\n PlanetScaleTransaction\n> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n readonly supportsTransactions = true;\n\n private readonly driverOptions: PlanetScaleDriverOptions;\n\n constructor(options: PlanetScaleDriverOptions = {}) {\n // Only the explicit option records a qualifier here. This driver exposes no\n // attestation option and never reads one, so its base fact stays an\n // immutable `undefined` whatever the caller's object carries.\n const namespace = resolveNamespaceOption(options);\n super(\"mysql\", \"planetscale\");\n this.driverOptions = options;\n defineImmutableDriverFact(this, \"adapter\", new MySQLAdapter(namespace));\n }\n\n protected async initClient(): Promise<PlanetScaleClient> {\n const { Client } = await import(\"@planetscale/database\");\n\n const providedClient = this.driverOptions.client;\n if (providedClient) {\n if (!isRecord(providedClient.config)) return providedClient;\n const config: Config = { ...providedClient.config };\n config.fetch = createValidatedPlanetScaleFetch(config.fetch);\n return new Client(config);\n }\n\n const config: Config = { ...this.driverOptions.options };\n\n if (this.driverOptions.databaseUrl) {\n config.url = this.driverOptions.databaseUrl;\n }\n\n config.fetch = createValidatedPlanetScaleFetch(config.fetch);\n\n return new Client(config);\n }\n\n protected async closeClient(_client: PlanetScaleClient): Promise<void> {\n // PlanetScale HTTP client doesn't need to be closed\n }\n\n protected async execute<T>(\n client: PlanetScaleClient | PlanetScaleTransaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const result = await client.execute(sql, params);\n return toQueryResult<T>(result, operation);\n }\n\n protected async executeRaw<T>(\n client: PlanetScaleClient | PlanetScaleTransaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const result = await client.execute(sql, params);\n return toQueryResult<T>(result, operation);\n }\n\n /**\n * MySQL semantics: the level must be set before BEGIN, and this driver owns\n * both statements on one `Connection`. Every transaction gets a fresh HTTP\n * `Connection` created synchronously, so there is no slot to wait for.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"pre-begin\",\n timeout: true,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"each PlanetScale transaction gets its own HTTP connection created without waiting, so there is no acquisition maxWait could bound\",\n };\n }\n\n protected async transaction<T>(\n client: PlanetScaleClient | PlanetScaleTransaction,\n fn: (tx: PlanetScaleTransaction) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (!(\"transaction\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n const connection: Connection =\n \"connection\" in client ? client.connection() : client;\n const isolationLevel = options?.isolationLevel;\n\n return runTransactionLifecycle({\n begin: async () => {\n // Vitess SINGLE mode rejects cross-shard transactions instead of using\n // best-effort multi-shard commit semantics.\n await connection.execute(\"SET transaction_mode = 'single'\");\n // Session-scoped-next-transaction: must precede BEGIN on this same\n // connection to bind to the transaction it opens.\n if (isolationLevel) {\n await connection.execute(isolationLevelStatement(isolationLevel));\n }\n await connection.execute(\"BEGIN\");\n },\n callback: () => fn(connection),\n commit: () => connection.execute(\"COMMIT\"),\n rollback: () => connection.execute(\"ROLLBACK\"),\n phases: getExecutionTransactionPhases(context),\n });\n }\n\n protected override transactionCleanupFailed(error: Error): void {\n if (this.client && \"connection\" in this.client) {\n // Each transaction used a fresh Connection that is now discarded.\n return;\n }\n super.transactionCleanupFailed(error);\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PlanetScaleClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PlanetScaleDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PlanetScaleDriver }\n >]: LinkedClientConfig<C & { driver: PlanetScaleDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"planetscale\", PLANETSCALE_CONFIG_KEYS);\n const { client, databaseUrl, options } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new PlanetScaleDriver({\n client,\n databaseUrl,\n options,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, PlanetScaleDriver>(config, driver);\n}\n"],"mappings":"qgBAOA,MAAM,EAAuB,mBACvB,EACJ,mEACI,EAAe,IAAI,IAAI,CAC3B,UACA,OACA,OACA,WACA,UACA,SACA,OACA,SACD,CAAC,CACI,EAAoB,IAAI,IAAI,CAAC,SAAU,SAAU,UAAW,SAAS,CAAC,CACtE,EAAkB,IAAI,IAAI,CAC9B,QACA,QACA,SACA,SACA,OACA,OACA,UACA,SACA,WACA,YACA,MACA,WACA,SACA,MACD,CAAC,CACI,EAAgB,IAAI,IAAI,CAAC,GAAG,EAAc,GAAG,EAAkB,CAAC,CAIhE,aAAiC,MAAO,EAAO,IAC5C,WAAW,MAAM,EAAO,EAAK,CAGtC,SAAS,SAAS,EAAkD,CAClE,OACE,OAAO,GAAU,YACjB,GACA,OAAO,UAAU,SAAS,KAAK,EAAM,GAAK,kBAI9C,SAAS,kBAAkB,EAAwB,CACjD,GAAI,CACF,OAAO,IAAI,IAAI,EAAM,CAAC,WAAa,uCAC7B,CACN,MAAO,IAIX,SAAS,gBAAgB,EAAmC,CACtD,UAAO,GAAS,SACpB,GAAI,CACF,IAAM,EAAiB,KAAK,MAAM,EAAK,CACvC,OAAO,SAAS,EAAM,EAAI,OAAO,EAAM,OAAU,SAC7C,EAAM,MACN,IAAA,QACE,CACN,QAIJ,SAAS,kBAAkB,EAA8C,CACvE,GAAI,CAAC,EAAK,MAAO,UACjB,IAAM,EAAS,EAA2B,EAAK,CAAE,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
|
|
2
2
|
|
|
3
|
+
//#region src/migrations/limits.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The limits of one migration command (plans S1, T5a): their type, their
|
|
7
|
+
* defaults and the one resolver. Only migration code imports this module, so
|
|
8
|
+
* an application bundle carries none of it.
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* The limits of one migration command's pinned session (plan S1), and the
|
|
12
|
+
* table size it may rewrite in-request (plan T5a).
|
|
13
|
+
*
|
|
14
|
+
* Every value but `largeTableRows` is in milliseconds. `lockTimeout`, `statementTimeout` and
|
|
15
|
+
* `idleTimeout` are PostgreSQL server settings, where 0 means "no limit";
|
|
16
|
+
* `lockWait` and `connectionWait` are waits VibORM itself bounds. `lockWait`
|
|
17
|
+
* also bounds SQLite's `BEGIN IMMEDIATE`, and `connectionWait` applies to
|
|
18
|
+
* MySQL as well; the others, `largeTableRows` included, are PostgreSQL-only,
|
|
19
|
+
* and MySQL keeps its fixed named-lock wait.
|
|
20
|
+
*/
|
|
21
|
+
interface MigrationLimits {
|
|
22
|
+
/**
|
|
23
|
+
* `lock_timeout`, for the session and, with `SET LOCAL`, every migration
|
|
24
|
+
* transaction: how long one DDL statement may queue for a table lock.
|
|
25
|
+
*/
|
|
26
|
+
readonly lockTimeout?: number;
|
|
27
|
+
/**
|
|
28
|
+
* `statement_timeout`, for every migration transaction and for the session
|
|
29
|
+
* around the lock and stepwise programs. 0, or longer than `lockWait`.
|
|
30
|
+
*/
|
|
31
|
+
readonly statementTimeout?: number;
|
|
32
|
+
/**
|
|
33
|
+
* `idle_in_transaction_session_timeout` and, on PostgreSQL 14+,
|
|
34
|
+
* `idle_session_timeout`: how long the server keeps a migration session
|
|
35
|
+
* whose client stopped talking — the one that vanished holding the lock.
|
|
36
|
+
*/
|
|
37
|
+
readonly idleTimeout?: number;
|
|
38
|
+
/** How long the command waits for the migration lock another one holds. */
|
|
39
|
+
readonly lockWait?: number;
|
|
40
|
+
/** How long the command waits for its pinned connection. */
|
|
41
|
+
readonly connectionWait?: number;
|
|
42
|
+
/**
|
|
43
|
+
* A row count, not milliseconds: the planner's estimate above which a
|
|
44
|
+
* statement that rewrites or scans a table under a lock that blocks it (a
|
|
45
|
+
* column type change, `SET NOT NULL`, a volatile `ADD COLUMN` default, a
|
|
46
|
+
* FOREIGN KEY or CHECK added without `NOT VALID`) is refused before any
|
|
47
|
+
* effect, because it would hold that lock longer than a request should.
|
|
48
|
+
* 0 admits every size.
|
|
49
|
+
*/
|
|
50
|
+
readonly largeTableRows?: number;
|
|
51
|
+
}
|
|
52
|
+
type ResolvedMigrationLimits = Readonly<Required<MigrationLimits>>;
|
|
53
|
+
//#endregion
|
|
3
54
|
//#region src/migrations/types.d.ts
|
|
4
55
|
interface SchemaSnapshot {
|
|
5
56
|
tables: TableDef[];
|
|
@@ -417,6 +468,8 @@ type MigrationTarget = ({
|
|
|
417
468
|
//#endregion
|
|
418
469
|
//#region src/migrations/target.d.ts
|
|
419
470
|
declare const MANAGED_TABLES: unique symbol;
|
|
471
|
+
/** The client's resolved limits (plans S1, T5a), bound with its driver. */
|
|
472
|
+
declare const MIGRATION_LIMITS: unique symbol;
|
|
420
473
|
//#endregion
|
|
421
474
|
//#region src/migrations/push/planner.d.ts
|
|
422
475
|
/**
|
|
@@ -426,7 +479,8 @@ declare const MANAGED_TABLES: unique symbol;
|
|
|
426
479
|
interface MigrationClient {
|
|
427
480
|
$driver: AnyDriver;
|
|
428
481
|
$schema: Record<string, AnyModel>;
|
|
429
|
-
readonly [MANAGED_TABLES]?: readonly string[];
|
|
482
|
+
readonly [MANAGED_TABLES]?: readonly string[] | undefined;
|
|
483
|
+
readonly [MIGRATION_LIMITS]?: ResolvedMigrationLimits | undefined;
|
|
430
484
|
}
|
|
431
485
|
//#endregion
|
|
432
|
-
export { ResolveChange as a, ResolveCallback as i, DiffOperation as n, SchemaSnapshot as o, MigrationTarget as r, MigrationClient as t };
|
|
486
|
+
export { ResolveChange as a, ResolveCallback as i, DiffOperation as n, SchemaSnapshot as o, MigrationTarget as r, MigrationLimits as s, MigrationClient as t };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-AdXAoy6l.mjs";import{f as n,p as r}from"./validation-Dk9Q_-C7.mjs";import{o as i,t as a}from"./sql-Bp7jicEX.mjs";import{r as o}from"./adapter-internals-n3Mf3css.mjs";import{O as s,v as c}from"./geo-point-codec-lhxH42SK.mjs";import{a as l}from"./datetime-physical-codec-oIhiYZEP.mjs";import{t as u}from"./geo-area-codec-1SY9im7O.mjs";import{o as d}from"./native-types-veeTk36s.mjs";import{a as f}from"./physical-6V_LNU3L.mjs";import{t as p}from"./array-literal-BsbbSLw3.mjs";import{A as m,C as ee,D as h,E as g,M as _,S as v,T as y,_ as b,a as x,b as S,c as C,d as w,f as T,h as E,i as D,l as O,m as k,n as A,o as j,p as M,r as N,s as P,v as te,w as F,x as I,y as L}from"./standard-sql-Bk4RZPqJ.mjs";import{r as R}from"./batch-refs-4L8ECdPU.mjs";import{t as z}from"./adapter-namespace-DqkJQdrD.mjs";import{a as B,c as V,g as H,i as U,l as W,m as G,n as K,p as q,r as J,s as Y,t as X}from"./select-assembly-f1UGoblh.mjs";var Z=class JsonParameter{json;constructor(e){this.json=e,Object.freeze(this)}static from(e){let t=JSON.stringify(e);return t===void 0?void 0:new JsonParameter(t)}toString(){return this.json}toJSON(){return JSON.parse(this.json)}};const Q=_(`"`);function postgresLikeLiteral(e){return i`REPLACE(REPLACE(REPLACE(${e}, CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')`}function postgresAsciiCaseFold(e){return i`TRANSLATE(${e}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')`}function postgresJsonObject(e){if(e.length===0)return i.raw`'{}'::json`;let t=[],n=i.raw(e.length>50?`jsonb_build_object`:`json_build_object`);for(let r=0;r<e.length;r+=50){let a=e.slice(r,r+50).flatMap(([e,t])=>[i`${e}::text`,t]);t.push(i`${n}(${i.join(a,`, `)})`)}return t.length===1?t[0]:i`(${i.join(t,` || `)})::json`}const ne=G(e=>`${e}_pkey`);var CastParameter=class extends a{type;constructor(e,t){super([`CAST(`,` AS ${t})`],[e]),this.type=t}},ArrayParameter=class extends a{};const re=g().list;function arrayParameter(e){let t=e[0];if(t===void 0)return;let n=t instanceof CastParameter?t.type:void 0,r=[];for(let t of e){let e=t instanceof CastParameter?t:void 0,[i,a,o]=t.strings;if(e?.type!==n||!e&&(i!==``||a!==``||o!==void 0))return;let s=t.values[0];if(s instanceof Uint8Array)r.push(`\\x${Array.from(s,e=>e.toString(16).padStart(2,`0`)).join(``)}`);else if(typeof s==`string`||typeof s==`number`||typeof s==`bigint`||typeof s==`boolean`)r.push(String(s));else return}let i=p(r);return n===void 0?new ArrayParameter([``,``],[i]):new ArrayParameter([`CAST(`,` AS ${n}[])`],[i])}const $={quotient:(e,t)=>i`div(${e}, ${t})`,remainder:(e,t)=>i`mod(${e}, ${t})`},ie=/^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\(|$)/i;var PostgresAdapter=class{geoPoint;constructor(e=`public`,t=!1){z(this,e,`postgresql`),this.identifiers=T(Q,this.namespace),q(this,t?this.#r():void 0),o(this,{batchRefs:this.#n,constraints:ne,select:this.#e.select})}raw=v();identifiers;literals={...g(),dateTime:e=>i`${l(e)}`,true:()=>i.raw`TRUE`,false:()=>i.raw`FALSE`,json:e=>i`${Z.from(e)}`,decimal:(e,t)=>new CastParameter(s(e,t,`text`),c(`pg`,t)),id:(e,t)=>t===`uuid`?new CastParameter(e,`UUID`):i`${e}`,list:e=>arrayParameter(e)??re(e)};operators={...x(),like:(e,t)=>i`${e} LIKE ${t} ESCAPE '\\'`,notLike:(e,t)=>i`${e} NOT LIKE ${t} ESCAPE '\\'`,ilike:(e,t)=>i`${postgresAsciiCaseFold(e)} LIKE ${postgresAsciiCaseFold(t)} ESCAPE '\\'`,notIlike:(e,t)=>i`${postgresAsciiCaseFold(e)} NOT LIKE ${postgresAsciiCaseFold(t)} ESCAPE '\\'`,containsText:(e,t)=>i`${e} LIKE ('%' || ${postgresLikeLiteral(t)} || '%') ESCAPE '\\'`,startsWithText:(e,t)=>i`${e} LIKE (${postgresLikeLiteral(t)} || '%') ESCAPE '\\'`,endsWithText:(e,t)=>i`${e} LIKE ('%' || ${postgresLikeLiteral(t)}) ESCAPE '\\'`,startsWithPrefix:(e,t,n)=>i`${this.expressions.caseSensitiveText(e,n,!0)} LIKE ${`${m(t)}%`} ESCAPE '\\'`,exactTextEq:(e,t,n)=>i`${this.expressions.caseSensitiveText(e,n,!1)} = ${t}`,exactTextIn:(e,t,n)=>this.operators.in(this.expressions.caseSensitiveText(e,n,!1),t),in:(e,t)=>t instanceof ArrayParameter?i`${e} = ANY(${t})`:i`${e} IN ${t}`,notIn:(e,t)=>t instanceof ArrayParameter?i`${e} <> ALL(${t})`:i`${e} NOT IN ${t}`,...te(),...I(),...E(this.literals.true,this.literals.false),...w()};expressions={...D(),caseSensitiveText:(e,t,n=!1)=>{let a=d(t,`pg`)?.type;if(!n&&a?.toLowerCase()===`xml`)throw new r(`PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.`,{meta:{dialect:`pg`,scalarType:`string`}});return n&&a&&ie.test(a)?i`CAST(${e} AS TEXT)`:e},asciiCaseFold:postgresAsciiCaseFold,concat:(...e)=>e.length===0?i.raw`''`:e.length===1?e[0]:i`(${i.join(e,` || `)})`,greatest:(...e)=>i`GREATEST(${i.join(e,`, `)})`,least:(...e)=>i`LEAST(${i.join(e,`, `)})`,integerDivide:(e,t)=>i`(${e} / ${t})`,decimalCast:(e,t)=>i`CAST(${e} AS ${i.raw(c(`pg`,t))})`,idCast:(e,t)=>t===`bytes`?i`decode(${e}, 'hex')`:i`CAST(${e} AS ${i.raw(t===`uuid`?`UUID`:`TEXT`)})`,cast:N({text:`TEXT`,integer:`INTEGER`,bigint:`BIGINT`,boolean:`BOOLEAN`,numeric:`NUMERIC`}),blobToHex:e=>i`encode(${e}, 'hex')`};aggregates={...A(`'Infinity'::float8`),min:(e,t=!1)=>t?i`BOOL_AND(${e})`:i`MIN(${e})`,max:(e,t=!1)=>t?i`BOOL_OR(${e})`:i`MAX(${e})`,decimalAvg:(e,t)=>Y($,e,t),decimalSumOperandPrecision:C(1e3)};json={equals:(e,t)=>i`(${e})::jsonb = (${t})::jsonb`,boolean:e=>e,document:e=>e,number:e=>e,object:postgresJsonObject,array:e=>e.length===0?i.raw`'[]'::json`:i`json_build_array(${i.join(e,`, `)})`,emptyArray:()=>i.raw`'[]'::json`,agg:e=>i`COALESCE(json_agg(${e}), '[]'::json)`,objectFromColumns:postgresJsonObject,extract:(e,t)=>i`(${e})::jsonb#>${t}::text[]`,extractText:(e,t)=>i`(${e})::jsonb#>>${t}::text[]`,numberAtPath:(e,t)=>i`(CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'number' THEN ((${e})::jsonb#>>${t}::text[])::double precision END)`,stringAtPath:(e,t)=>i`((CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'string' THEN (${e})::jsonb#>>${t}::text[] END) COLLATE "C")`,contains:(e,t)=>i`(${e})::jsonb @> ${t}`,lastElement:e=>i`(${e})::jsonb -> -1`,value:e=>i`${Z.from(e)}`};arrays={literal:e=>e.length===0?i.raw`'{}'`:i`ARRAY[${i.join(e,`, `)}]`,value:(e,t)=>i`${t?e.map(e=>typeof e==`string`?l(e):e):e}`,enumValue:e=>i`${p(e)}`,has:(e,t)=>i`${t} = ANY(${e})`,hasEvery:(e,t)=>i`${e} @> ${t}`,hasSome:(e,t)=>i`${e} && ${t}`,isEmpty:e=>i`(cardinality(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>i`CAST(${e} AS TEXT[])`,length:e=>i`cardinality(${e})`,get:(e,t)=>i`${e}[${t}]`,push:(e,t)=>i`array_append(${e}, ${t})`,set:(e,t,n)=>i`${e}[:${t}-1] || ARRAY[${n}] || ${e}[${t}+1:]`};orderBy={...O(),nullsFirst:(e,t)=>t===`desc`?i`${e} DESC NULLS FIRST`:i`${e} ASC NULLS FIRST`,nullsLast:(e,t)=>t===`desc`?i`${e} DESC NULLS LAST`:i`${e} ASC NULLS LAST`};clauses=y();set={...L(),multiply:(e,t,n)=>n?.decimal?W($,e,t,n.decimal):i`${e} = ${e} * ${t}`,divide:(e,t,n)=>n?.decimal?V($,e,t,n.decimal):i`${e} = ${e} / ${t}`,push:(e,t)=>i`${e} = array_cat(COALESCE(${e}, '{}'), ${t})`,unshift:(e,t)=>i`${e} = array_cat(${t}, COALESCE(${e}, '{}'))`};filters=ee();subqueries=h(Q);#e={select:e=>e.distinct&&e.orderBy?X(e,e.distinct,this.identifiers.escape):K(e.distinct?i`SELECT DISTINCT ON (${e.distinct}) ${e.columns}`:i`SELECT ${e.columns}`,e,{forUpdate:`append`})};cte=P(Q);mutations={skipDuplicatesStrategy:`sql`,insert:M(Q),insertDefault:e=>i`INSERT INTO ${e} DEFAULT VALUES`,...b(),returning:e=>i`RETURNING ${e}`,...S()};assertions={exists:e=>i`SELECT 1 / CASE WHEN EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`,notExists:e=>i`SELECT 1 / CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`};joins={...j(),full:(e,t)=>i`FULL OUTER JOIN ${e} ON ${t}`,...k(Q)};setOperations=F();capabilities={supportsReturning:!0,supportsCteWithMutations:!0,supportsFullOuterJoin:!0,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!0};lastInsertId=()=>i.raw`lastval()`;#t=R({table:i.raw`"__viborm_batch_refs"`,batchIdColumn:i.raw`"batch_id"`,keyColumn:i.raw`"ref_key"`,valueColumn:i.raw`"ref_value"`,createTable:i.raw`CREATE TEMP TABLE IF NOT EXISTS "__viborm_batch_refs" ("batch_id" TEXT NOT NULL, "ref_key" TEXT NOT NULL, "ref_value" TEXT, PRIMARY KEY ("batch_id", "ref_key"))`,castValue:e=>i`CAST((${e}) AS TEXT)`,storeReturning:(e,t,n,r)=>i`WITH "__viborm_inserted" AS (${n} RETURNING ${r}) INSERT INTO "__viborm_batch_refs" ("batch_id", "ref_key", "ref_value") SELECT ${e}, ${t}, CAST(${r} AS TEXT) FROM "__viborm_inserted"`});#n=(()=>{let e=this.#t,t=this.capabilities;return{setup:e.setup,cleanup:e.cleanup,store:e.store,read:e.read,get storeReturning(){return t.supportsCteWithMutations?e.storeReturning:void 0},get storeInsertedKey(){return t.supportsCteWithMutations?e.storeInsertedKey:void 0}}})();vector={literal:e=>{if(e.some(e=>!Number.isFinite(Math.fround(e))))throw new n(`PostgreSQL vector components must fit a finite float32 value.`,{code:t.INVALID_INPUT});return i`${`[${e.join(`,`)}]`}::vector`},l2:(e,t)=>i`${e} <-> ${t}`,cosine:(e,t)=>i`NULLIF(${e} <=> ${t}, 'NaN'::double precision)`};#r(){let longitude=e=>i`ST_X(${e}::geometry)`,latitude=e=>i`ST_Y(${e}::geometry)`;return{value:(e,t)=>i`ST_SetSRID(ST_MakePoint(${e}, ${t}), 4326)::geography`,longitude,latitude,...J(longitude,latitude,this.operators,(e,t)=>{let n=U(t);if(n.length!==0)return this.operators.or(...n.map(t=>i`${e} && ST_SetSRID(ST_GeomFromGeoJSON(${t}), 4326)::geography`))}),withinPolygon:(e,t)=>i`ST_Intersects(${i`ST_SetSRID(ST_GeomFromGeoJSON(${B(t)}), 4326)::geography`}, ${e})`,distance:(e,t)=>{let n=i`RADIANS(ST_X(${e}::geometry))`,r=i`RADIANS(ST_Y(${e}::geometry))`,a=i`RADIANS(ST_X(${t}::geometry))`,o=i`RADIANS(ST_Y(${t}::geometry))`;return i`CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE CAST(${u} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${i`POWER(SIN((${o} - ${r}) / 2), 2) + COS(${r}) * COS(${o}) * POWER(SIN((${a} - ${n}) / 2), 2)`})))) END`}}}result={nativeScalarPassthrough:!0,enumListRepresentation:`arrayText`,idRepresentation:(e,t)=>f(e,t,`pg`)?.representation??`text`,parseResult:H,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()}};export{PostgresAdapter as t};
|
|
2
|
+
//# sourceMappingURL=postgres-adapter-B3SQvcV1.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postgres-adapter-B3SQvcV1.mjs","names":["sql","#createGeoPointSql","#batchRefs","#assemble","#cteBatchRefs"],"sources":["../src/sql/json-parameter.ts","../src/adapters/databases/postgres/postgres-adapter.ts"],"sourcesContent":["/**\n * One JSON document, bound as one statement parameter.\n *\n * PostgreSQL's JSON literals bind CANONICAL JSON TEXT and let the server cast\n * that text from the parameter's column context. Nothing at the driver can\n * tell that text apart from an ordinary string, so every transport that\n * re-serializes a `json`/`jsonb` parameter has to be told not to, and only some\n * of them offer a place to say it: postgres.js takes a `json` type override\n * (`src/drivers/postgres/index.ts`), PGlite's own JSON serializer already\n * passes strings through, and node-postgres/Neon never touch a string. Bun SQL\n * offers no such hook and JSON-ENCODES a string bound to a `json`/`jsonb`\n * parameter, storing the physical document `\"[1,2,3]\"` — a JSON string — where\n * `[1,2,3]` was meant (upstream Drizzle #5287).\n *\n * This carrier is the missing distinction, and it needs no per-transport hook:\n * a PostgreSQL transport can only reach a bound value through string coercion\n * or through JSON serialization, and this renders as its canonical text under\n * BOTH. The text captured at construction is the ONE stored fact: `toJSON`\n * answers it parsed back, and `JSON.stringify` of its own output re-serializes\n * to those exact bytes, so both protocols agree even if the caller mutates the\n * original value after binding.\n * Bun, which serializes an object parameter for a `json`/`jsonb` column with\n * `JSON.stringify`, therefore stores the exact document for every JSON type,\n * including the number, boolean and null primitives that no bare JavaScript\n * value can express to it (a JS number is bound as `integer`, `null` as SQL\n * NULL).\n *\n * `json` is an own property rather than a private field because it is what a\n * parameter snapshot shows: diagnostics read own properties, so an opted-in\n * `includeParams` disclosure keeps the document instead of reporting `{}`.\n */\nexport class JsonParameter {\n /** The canonical JSON text — `JSON.stringify(value)`. */\n readonly json: string;\n\n private constructor(json: string) {\n this.json = json;\n Object.freeze(this);\n }\n\n /**\n * The carrier for `value`, or `undefined` when `JSON.stringify` has no text\n * for it (`undefined`, a function, a symbol). Those bound `undefined`\n * directly before this carrier existed, which providers send as SQL NULL;\n * carrying them would bind the text `\"undefined\"` instead.\n */\n static from(value: unknown): JsonParameter | undefined {\n // The lib signature says `string`, which is only true for the values it can\n // represent.\n const json: string | undefined = JSON.stringify(value);\n return json === undefined ? undefined : new JsonParameter(json);\n }\n\n toString(): string {\n return this.json;\n }\n\n toJSON(): unknown {\n return JSON.parse(this.json);\n }\n}\n","import {\n QueryError,\n UnsupportedOperationError,\n VibORMErrorCode,\n} from \"@errors\";\nimport {\n type NativeTypeDeclaration,\n nativeTypeFor,\n} from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { Sql, sql } from \"@sql\";\nimport { encodePostgresTemporal } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport { JsonParameter } from \"../../../sql/json-parameter\";\nimport type {\n ArithmeticTarget,\n BatchReferenceSqlAdapter,\n} from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport { passThroughParseResult } from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n} from \"../../database-adapter\";\nimport { createOnConflictBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n logicalDecimalAverage,\n logicalDecimalDivide,\n logicalDecimalMultiply,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createOnConflictBuilders,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n} from \"../../shared/standard-sql\";\nimport { arrayLiteralText } from \"./array-literal\";\n\nconst quoteIdent = createIdentifierQuoter('\"');\nfunction postgresLikeLiteral(value: Sql): Sql {\n return sql`REPLACE(REPLACE(REPLACE(${value}, CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')`;\n}\nfunction postgresAsciiCaseFold(expr: Sql): Sql {\n return sql`TRANSLATE(${expr}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')`;\n}\nfunction postgresJsonObject(pairs: [string, Sql][]): Sql {\n if (pairs.length === 0) return sql.raw`'{}'::json`;\n const chunks: Sql[] = [];\n const buildObject = sql.raw(\n pairs.length > 50 ? \"jsonb_build_object\" : \"json_build_object\"\n );\n // PostgreSQL limits a function call to 100 arguments. Chunking preserves\n // the surrounding aggregate scope, unlike moving values into a subquery.\n for (let start = 0; start < pairs.length; start += 50) {\n const args = pairs\n .slice(start, start + 50)\n .flatMap(([key, value]) => [sql`${key}::text`, value]);\n chunks.push(sql`${buildObject}(${sql.join(args, \", \")})`);\n }\n return chunks.length === 1\n ? chunks[0]!\n : sql`(${sql.join(chunks, \" || \")})::json`;\n}\nconst POSTGRES_CONSTRAINTS = createNamedConstraintIdentities(\n (tableName) => `${tableName}_pkey`\n);\n\n/** An operand cast to the type its column holds: `uuid`, `NUMERIC(p,s)`. */\nclass CastParameter extends Sql {\n readonly type: string;\n constructor(value: unknown, type: string) {\n super([\"CAST(\", ` AS ${type})`], [value]);\n this.type = type;\n }\n}\n\n/** A value list bound as ONE array parameter: `= ANY(…)`, `<> ALL(…)`. */\nclass ArrayParameter extends Sql {}\nconst PARENTHESIZED_LIST = createStandardLiterals().list;\n\n/**\n * engine-09: a list whose members are each one parameter — bare, or all cast\n * to one type — as one array parameter: PostgreSQL's own array text, typed by\n * the members' cast or, bare, by the compared column, as a list column's\n * parameter is. Any other list keeps a parameter per member.\n */\nfunction arrayParameter(members: readonly Sql[]): ArrayParameter | undefined {\n const first = members[0];\n if (first === undefined) return;\n const type = first instanceof CastParameter ? first.type : undefined;\n const elements: string[] = [];\n for (const member of members) {\n const cast = member instanceof CastParameter ? member : undefined;\n const [head, tail, extra] = member.strings;\n if (\n cast?.type !== type ||\n (!cast && (head !== \"\" || tail !== \"\" || extra !== undefined))\n )\n return;\n const value = member.values[0];\n if (value instanceof Uint8Array)\n elements.push(\n `\\\\x${Array.from(value, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`\n );\n else if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n )\n elements.push(String(value));\n else return;\n }\n const text = arrayLiteralText(elements);\n return type === undefined\n ? new ArrayParameter([\"\", \"\"], [text])\n : new ArrayParameter([\"CAST(\", ` AS ${type}[])`], [text]);\n}\n\n/**\n * `div`/`mod` rather than `/` and a hand-rolled remainder: both are exact on\n * `numeric` for any operand, including a fractional divisor, and `div`\n * truncates toward zero — which is what the half-even rule's quotient means.\n * `/` on numerics picks its own result scale and would round the last digit.\n */\nconst POSTGRES_INTEGERS: ExactIntegerArithmetic = {\n quotient: (n: Sql, d: Sql): Sql => sql`div(${n}, ${d})`,\n remainder: (n: Sql, d: Sql): Sql => sql`mod(${n}, ${d})`,\n};\n\n/** The two characters PostgreSQL reads structurally inside a quoted member. */\n\n/**\n * PostgreSQL's own text spelling of one list, for a column whose element type\n * the driver cannot serialize.\n *\n * Every member is quoted, so a member that is empty, spells `NULL`, or holds a\n * brace, comma, quote or backslash is still exactly one member: those are the\n * only characters the server reads structurally, and quoting makes the reading\n * unambiguous without a per-member decision.\n */\n\nconst NON_TEXT_STRING_TYPE =\n /^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\\(|$)/i;\n\nexport class PostgresAdapter implements DatabaseAdapter {\n /**\n * The bound schema. PostgreSQL always qualifies, so this adapter has no\n * unbound mode: an omitted or explicitly `undefined` argument means the\n * `public` schema, whatever a connection's `search_path` says.\n */\n declare readonly namespace: string;\n readonly geoPoint: GeoPointSql | undefined;\n\n constructor(namespace = \"public\", postgis = false) {\n installAdapterNamespace(this, namespace, \"postgresql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(quoteIdent, this.namespace);\n installGeoPointSql(this, postgis ? this.#createGeoPointSql() : undefined);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: POSTGRES_CONSTRAINTS,\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n dateTime: (iso: string): Sql => sql`${encodePostgresTemporal(iso)}`,\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // Serialized JSON text — PG casts the param to json/jsonb from the column\n // context. Stringifying (not raw binding) keeps primitives valid: a bare\n // 'hello' is not valid JSON input, '\"hello\"' is. The carrier is what tells\n // a transport that this text is already a document; see json-parameter.ts.\n json: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n\n // Cast into the operand's own `NUMERIC(p,s)` domain, the same type the DDL\n // emits for the field. PostgreSQL would usually infer `numeric` from the\n // column context anyway; saying it makes the comparison independent of what\n // the surrounding expression does to the operand's inferred type, and\n // naming the precision keeps the operand and the column one domain rather\n // than two that happen to agree.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n new CastParameter(\n encodePhysicalDecimal(canonical, descriptor, \"text\"),\n decimalColumnType(\"pg\", descriptor)\n ),\n\n // A `uuid` column takes canonical text and is TYPED: PostgreSQL has no\n // `uuid = text` operator, so an untyped operand raises 42883 rather than\n // comparing. `bytea` takes the payload's bytes as an ordinary binary\n // parameter — the same parameter every blob scalar already binds — and a\n // text-stored domain takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n representation: IdRepresentation\n ): Sql =>\n representation === \"uuid\"\n ? new CastParameter(physical, \"UUID\")\n : sql`${physical}`,\n\n list: (values: Sql[]): Sql =>\n arrayParameter(values) ?? PARENTHESIZED_LIST(values),\n };\n\n operators = {\n ...createComparisonOperators(),\n\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`${postgresAsciiCaseFold(column)} LIKE ${postgresAsciiCaseFold(pattern)} ESCAPE '\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`${postgresAsciiCaseFold(column)} NOT LIKE ${postgresAsciiCaseFold(pattern)} ESCAPE '\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ('%' || ${postgresLikeLiteral(value)} || '%') ESCAPE '\\\\'`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE (${postgresLikeLiteral(value)} || '%') ESCAPE '\\\\'`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ('%' || ${postgresLikeLiteral(value)}) ESCAPE '\\\\'`,\n // PostgreSQL is the one dialect where the escaped LIKE spelling is both\n // exact and index-usable, so it stands alone here: `LIKE` is case- and\n // accent-sensitive natively, which is the contract `startsWithText` holds,\n // and `match_pattern_prefix` extracts `name >= 'x' AND name < 'y'` from the\n // constant-folded pattern even though it arrives as a bound parameter.\n //\n // THE INDEX RANGE HAS A COLLATION PRECONDITION, and the common case does\n // not meet it. Measured, 20k rows, plain btree index:\n // - C-collated database (PGlite, `datcollate = 'C'`): Bitmap Index Scan\n // over 111 rows, where `LEFT(col, LENGTH($1)) = $1` is a Seq Scan over\n // all 20000.\n // - `en_US.utf8` (postgres:16 — the project's own test container, and\n // what a default `initdb` produces): BOTH spellings Seq Scan. Only a\n // `(col text_pattern_ops)` index ranges, and `generateCreateIndex`\n // (src/migrations/drivers/postgres/index.ts) emits no opclass, so\n // viborm cannot create one.\n // What survives on a default-locale cluster — and the reason this spelling\n // still stands there — is the row estimate: `LIKE` tracks the data\n // (202/1010/11111/19998 against truths 111/1111/11111/20000) while\n // `LEFT(...)` is an opaque function estimated at a flat 100 for every\n // prefix width, a 111x error at `name1%` that propagates into the row\n // estimate of any join above it. It is never worse than the spelling it\n // replaced on any measured leg. Full record: Decision 7.3 in\n // docs/architecture/query-performance-plan.md.\n startsWithPrefix: (\n column: Sql,\n value: string,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, true)} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\'`,\n\n // Preserve native equality and indexes; the shared text boundary refuses\n // native types such as XML that cannot express an exact comparison.\n exactTextEq: (\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, false)} = ${value}`,\n exactTextIn: (\n column: Sql,\n values: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n this.operators.in(\n this.expressions.caseSensitiveText(column, nativeType, false),\n values\n ),\n\n // Set membership: a bound list (`literals.list`) is an array, read by\n // ANY/ALL; a parenthesized list or a subquery is read by IN.\n in: (column: Sql, values: Sql): Sql =>\n values instanceof ArrayParameter\n ? sql`${column} = ANY(${values})`\n : sql`${column} IN ${values}`,\n notIn: (column: Sql, values: Sql): Sql =>\n values instanceof ArrayParameter\n ? sql`${column} <> ALL(${values})`\n : sql`${column} NOT IN ${values}`,\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n caseSensitiveText: (\n expr: Sql,\n nativeType?: NativeTypeDeclaration,\n textOperation = false\n ): Sql => {\n const type = nativeTypeFor(nativeType, \"pg\")?.type;\n if (!textOperation && type?.toLowerCase() === \"xml\")\n throw new UnsupportedOperationError(\n \"PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.\",\n { meta: { dialect: \"pg\", scalarType: \"string\" } }\n );\n return textOperation && type && NON_TEXT_STRING_TYPE.test(type)\n ? sql`CAST(${expr} AS TEXT)`\n : expr;\n },\n asciiCaseFold: postgresAsciiCaseFold,\n\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`(${sql.join(parts, \" || \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // PostgreSQL integer division already truncates toward zero, which is why\n // `set.divide` ignores `target.integer` here as well. Casting either side\n // would narrow a `bigint` operand to `int4`.\n integerDivide: (left: Sql, right: Sql): Sql => sql`(${left} / ${right})`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${expr} AS ${sql.raw(decimalColumnType(\"pg\", descriptor))})`,\n\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`decode(${expr}, 'hex')`\n : sql`CAST(${expr} AS ${sql.raw(\n representation === \"uuid\" ? \"UUID\" : \"TEXT\"\n )})`,\n\n cast: createCastExpression({\n text: \"TEXT\",\n integer: \"INTEGER\",\n bigint: \"BIGINT\",\n boolean: \"BOOLEAN\",\n numeric: \"NUMERIC\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`encode(${expr}, 'hex')`,\n };\n\n aggregates = {\n ...createAggregateFunctions(\"'Infinity'::float8\"),\n\n min: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOL_AND(${column})` : sql`MIN(${column})`,\n max: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOL_OR(${column})` : sql`MAX(${column})`,\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n logicalDecimalAverage(POSTGRES_INTEGERS, column, descriptor),\n\n // `sum(numeric)` is itself unbounded on PostgreSQL; 1000 is the widest\n // `NUMERIC(p,s)` an operand can be CAST into to meet it, which is the\n // domain a comparison against that sum is actually limited by.\n decimalSumOperandPrecision: createDecimalSumOperandPrecision(1000),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql =>\n sql`(${left})::jsonb = (${right})::jsonb`,\n boolean: (condition: Sql): Sql => condition,\n document: (expression: Sql): Sql => expression,\n number: (expression: Sql): Sql => expression,\n\n object: postgresJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`'[]'::json`;\n return sql`json_build_array(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw`'[]'::json`,\n\n agg: (expr: Sql): Sql => sql`COALESCE(json_agg(${expr}), '[]'::json)`,\n\n objectFromColumns: postgresJsonObject,\n\n // #>/#>> with a text[] param handles every path shape uniformly:\n // '{}' returns the document root, and integer segments address array\n // elements (a single-segment `-> '0'` would only match an object key)\n extract: (column: Sql, path: string[]): Sql =>\n sql`(${column})::jsonb#>${path}::text[]`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`(${column})::jsonb#>>${path}::text[]`,\n\n // jsonb_typeof gates the cast: a non-number (or an absent path, where\n // jsonb_typeof is NULL) short-circuits to NULL instead of raising\n // \"invalid input syntax for type double precision\"\n numberAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN jsonb_typeof((${column})::jsonb#>${path}::text[]) = 'number' THEN ((${column})::jsonb#>>${path}::text[])::double precision END)`,\n\n // COLLATE \"C\" pins byte (= code point) ordering; the database's default\n // collation (en_US.UTF-8 and friends) orders 'a' before 'B', which would\n // make < / > disagree with MySQL and SQLite\n stringAtPath: (column: Sql, path: string[]): Sql =>\n sql`((CASE WHEN jsonb_typeof((${column})::jsonb#>${path}::text[]) = 'string' THEN (${column})::jsonb#>>${path}::text[] END) COLLATE \"C\")`,\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`(${target})::jsonb @> ${value}`,\n\n lastElement: (target: Sql): Sql => sql`(${target})::jsonb -> -1`,\n\n // Serialized JSON text, same format literals.json writes — PG casts the\n // param to jsonb from the comparison context\n value: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n };\n\n arrays = {\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`'{}'`;\n return sql`ARRAY[${sql.join(items, \", \")}]`;\n },\n\n // Native array parameter; drivers serialize JS arrays to PG array format\n value: (values: unknown[], temporal?: \"date\" | \"datetime\"): Sql =>\n sql`${temporal ? values.map((value) => (typeof value === \"string\" ? encodePostgresTemporal(value) : value)) : values}`,\n\n // One untyped parameter holding PostgreSQL's own array literal. A managed\n // enum's array OID is created by the estate, so no driver has a serializer\n // for it and the native parameter above arrives malformed; an unknown\n // parameter instead takes its type from the column or operand it meets,\n // which is how the enum type is reached without naming it here.\n enumValue: (values: unknown[]): Sql => sql`${arrayLiteralText(values)}`,\n\n has: (column: Sql, value: Sql): Sql => sql`${value} = ANY(${column})`,\n\n hasEvery: (column: Sql, values: Sql): Sql => sql`${column} @> ${values}`,\n\n hasSome: (column: Sql, values: Sql): Sql => sql`${column} && ${values}`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(cardinality(${column}) = 0 OR ${column} IS NULL)`,\n\n // `numeric[]::text[]` casts every ELEMENT. `numeric[]::text` would produce\n // one string holding PostgreSQL's array literal, and `to_json(numeric[])`\n // JSON numbers — the two spellings a decimal list cannot survive.\n exactNumericProjection: (column: Sql): Sql =>\n sql`CAST(${column} AS TEXT[])`,\n\n length: (column: Sql): Sql => sql`cardinality(${column})`,\n\n get: (column: Sql, index: Sql): Sql => sql`${column}[${index}]`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`array_append(${column}, ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`${column}[:${index}-1] || ARRAY[${value}] || ${column}[${index}+1:]`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS FIRST`\n : sql`${column} ASC NULLS FIRST`,\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS LAST`\n : sql`${column} ASC NULLS LAST`,\n };\n\n clauses = createStandardClauses();\n\n set = {\n ...createNumericSetOperations(),\n\n // A decimal target rounds the product/quotient back to the field's scale\n // half-to-even; every other numeric column keeps PostgreSQL's own\n // arithmetic, whose integer division already truncates toward zero.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalMultiply(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalDivide(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} / ${by}`,\n\n // `values` is already the destination field's one complete list crossing:\n // a native array parameter for ordinary lists or an untyped PostgreSQL\n // array literal for managed enums. `array_cat` lets the column resolve that\n // one parameter's exact array type and keeps bind/SQL size constant.\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(COALESCE(${column}, '{}'), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(${values}, COALESCE(${column}, '{}'))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n readonly #assemble = {\n select: (parts: QueryParts): Sql => {\n // DISTINCT ON requires ORDER BY to lead with the distinct columns, which\n // would override the user's ordering — emulate via ROW_NUMBER() instead\n if (parts.distinct && parts.orderBy) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape\n );\n }\n\n // PostgreSQL supports DISTINCT ON (columns)\n const selectClause = parts.distinct\n ? sql`SELECT DISTINCT ON (${parts.distinct}) ${parts.columns}`\n : sql`SELECT ${parts.columns}`;\n\n return assembleSelectQuery(selectClause, parts, { forUpdate: \"append\" });\n },\n };\n\n cte = createCteBuilders(quoteIdent);\n\n mutations = {\n skipDuplicatesStrategy: \"sql\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql =>\n sql`INSERT INTO ${table} DEFAULT VALUES`,\n\n ...createMutationCommands(),\n\n returning: (columns: Sql): Sql => sql`RETURNING ${columns}`,\n\n ...createOnConflictBuilders(),\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n notExists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n };\n\n joins = {\n ...createCoreJoins(),\n\n full: (table: Sql, condition: Sql): Sql =>\n sql`FULL OUTER JOIN ${table} ON ${condition}`,\n\n ...createLateralJoins(quoteIdent),\n };\n\n setOperations = createSetOperations();\n\n capabilities = {\n supportsReturning: true,\n supportsCteWithMutations: true,\n supportsFullOuterJoin: true,\n supportsLateralJoins: true,\n supportsVector: false,\n supportsUpsertWhere: true, // PostgreSQL supports WHERE in ON CONFLICT\n supportsTargetedUpsert: true, // ON CONFLICT (cols) arbitrates on those cols\n supportsMutationTargetInSubquery: true,\n supportsMutationRowLimit: false, // PostgreSQL has no UPDATE/DELETE ... LIMIT\n supportsRowLocks: true,\n };\n\n lastInsertId = (): Sql => sql.raw`lastval()`;\n\n readonly #cteBatchRefs = createOnConflictBatchRefs({\n table: sql.raw`\"__viborm_batch_refs\"`,\n batchIdColumn: sql.raw`\"batch_id\"`,\n keyColumn: sql.raw`\"ref_key\"`,\n valueColumn: sql.raw`\"ref_value\"`,\n // The table is not ON COMMIT DROP, so it survives the native batch that\n // created it (D-50); the scratch itself belongs to the dispatched batch —\n // each batch stores its own reference rows, reads back what it stored at\n // its own end and deletes them there (D-58), so a later batch never names\n // a reference an earlier one stored. The table lingers on the session like\n // the SQLite and MySQL scratch tables do.\n createTable: sql.raw`CREATE TEMP TABLE IF NOT EXISTS \"__viborm_batch_refs\" (\"batch_id\" TEXT NOT NULL, \"ref_key\" TEXT NOT NULL, \"ref_value\" TEXT, PRIMARY KEY (\"batch_id\", \"ref_key\"))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS TEXT)`,\n // The exact identity of an INSERT, carried by the statement that runs it:\n // the INSERT is the data-modifying CTE, its RETURNING feeds the reference\n // row, and nothing session-global (lastval) is read.\n storeReturning: (batchId, key, insert, column) =>\n sql`WITH \"__viborm_inserted\" AS (${insert} RETURNING ${column}) INSERT INTO \"__viborm_batch_refs\" (\"batch_id\", \"ref_key\", \"ref_value\") SELECT ${batchId}, ${key}, CAST(${column} AS TEXT) FROM \"__viborm_inserted\"`,\n });\n\n // Whether this provider can mutate inside a CTE is the capability's fact,\n // read live: the CTE store and the key store it derives are offered only\n // while `capabilities.supportsCteWithMutations` holds, and a PostgreSQL\n // without it offers no exact key store at all (lastval() is not exact).\n readonly #batchRefs: BatchReferenceSqlAdapter = (() => {\n const withCte = this.#cteBatchRefs;\n const capabilities = this.capabilities;\n return {\n setup: withCte.setup,\n cleanup: withCte.cleanup,\n store: withCte.store,\n read: withCte.read,\n get storeReturning() {\n return capabilities.supportsCteWithMutations\n ? withCte.storeReturning\n : undefined;\n },\n get storeInsertedKey() {\n return capabilities.supportsCteWithMutations\n ? withCte.storeInsertedKey\n : undefined;\n },\n };\n })();\n\n vector = {\n literal: (values: number[]): Sql => {\n if (values.some((value) => !Number.isFinite(Math.fround(value))))\n throw new QueryError(\n \"PostgreSQL vector components must fit a finite float32 value.\",\n { code: VibORMErrorCode.INVALID_INPUT }\n );\n return sql`${`[${values.join(\",\")}]`}::vector`;\n },\n\n l2: (column: Sql, vector: Sql): Sql => sql`${column} <-> ${vector}`,\n\n cosine: (column: Sql, vector: Sql): Sql =>\n sql`NULLIF(${column} <=> ${vector}, 'NaN'::double precision)`,\n };\n\n #createGeoPointSql(): GeoPointSql {\n const longitude = (point: Sql): Sql => sql`ST_X(${point}::geometry)`;\n const latitude = (point: Sql): Sql => sql`ST_Y(${point}::geometry)`;\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`ST_SetSRID(ST_MakePoint(${pointLongitude}, ${pointLatitude}), 4326)::geography`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators,\n (point, bounds) => {\n const polygons = geoBoundsIndexPolygons(bounds);\n if (polygons.length === 0) return;\n return this.operators.or(\n ...polygons.map(\n (polygon) =>\n sql`${point} && ST_SetSRID(ST_GeomFromGeoJSON(${polygon}), 4326)::geography`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_SetSRID(ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}), 4326)::geography`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) => {\n const leftLongitude = sql`RADIANS(ST_X(${left}::geometry))`;\n const leftLatitude = sql`RADIANS(ST_Y(${left}::geometry))`;\n const rightLongitude = sql`RADIANS(ST_X(${right}::geometry))`;\n const rightLatitude = sql`RADIANS(ST_Y(${right}::geometry))`;\n const haversine = sql`POWER(SIN((${rightLatitude} - ${leftLatitude}) / 2), 2) + COS(${leftLatitude}) * COS(${rightLatitude}) * POWER(SIN((${rightLongitude} - ${leftLongitude}) / 2), 2)`;\n // PostgreSQL's LEAST/GREATEST ignore NULL operands. The explicit arm is\n // what keeps a nullable source point's distance NULL rather than zero.\n return sql`CASE WHEN ${left} IS NULL OR ${right} IS NULL THEN NULL ELSE CAST(${GEO_POINT_EARTH_RADIUS_METERS} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${haversine})))) END`;\n },\n };\n }\n\n result: DatabaseAdapter[\"result\"] = {\n // PostgreSQL returns native JS scalars and parseField below is a pure\n // passthrough, so the result parser may take the identity fast path for\n // plain string/int/number/boolean columns (byte-identical, guarded).\n nativeScalarPassthrough: true,\n\n // A managed enum's array OID is in no driver's result-type table, so an\n // enum LIST comes back as the array's own text rather than a JS array.\n enumListRepresentation: \"arrayText\",\n\n // The one physical promise an identifier column makes, derived from the\n // ONE storage owner so the column the migration creates, the parameter the\n // write binds and the value this reads back cannot be three decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"pg\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing. This leg used to offer\n // `convertBigIntToNumber(raw)`, but `Queries.decodeResult` hands it the\n // operation's ROW ARRAY, which is never a bigint, and an integer's width\n // is a VALUE's fact that the engine's `int` codec owns - it turns a bigint\n // or an integer text into a number and refuses one outside the safe range\n // (`raptor3/shared/query.ts`). Measured on live PostgreSQL over seven\n // operations and both routes, on `pg` and on `postgres.js`: 40 asks, 40\n // `undefined` (Arnaud's D-40, `g4/rulings/o2/receipts/leg-probe-pg.log`\n // and `leg-probe-postgresjs-2.log`), with `COUNT(*)` arriving as the text\n // `\"2\"` on both transports.\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => {\n // PostgreSQL returns native JSON objects - passthrough\n return next();\n },\n\n parseField: (\n _value: unknown,\n _scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // PostgreSQL has native types - passthrough\n return next();\n },\n };\n}\n"],"mappings":"09BA+BA,IAAa,EAAb,MAAa,aAAc,CAEzB,KAEA,YAAoB,EAAc,CAChC,KAAK,KAAO,EACZ,OAAO,OAAO,KAAK,CASrB,OAAO,KAAK,EAA2C,CAGrD,IAAM,EAA2B,KAAK,UAAU,EAAM,CACtD,OAAO,IAAS,IAAA,GAAY,IAAA,GAAY,IAAI,cAAc,EAAK,CAGjE,UAAmB,CACjB,OAAO,KAAK,KAGd,QAAkB,CAChB,OAAO,KAAK,MAAM,KAAK,KAAK,GCsBhC,MAAM,EAAa,EAAuB,IAAI,CAC9C,SAAS,oBAAoB,EAAiB,CAC5C,MAAO,EAAG,2BAA2B,EAAM,4EAE7C,SAAS,sBAAsB,EAAgB,CAC7C,MAAO,EAAG,aAAa,EAAK,+DAE9B,SAAS,mBAAmB,EAA6B,CACvD,GAAI,EAAM,SAAW,EAAG,MAAO,GAAI,GAAG,aACtC,IAAM,EAAgB,EAAE,CAClB,EAAcA,EAAI,IACtB,EAAM,OAAS,GAAK,qBAAuB,oBAC5C,CAGD,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAM,OAAQ,GAAS,GAAI,CACrD,IAAM,EAAO,EACV,MAAM,EAAO,EAAQ,GAAG,CACxB,SAAS,CAAC,EAAK,KAAW,CAAC,CAAG,GAAG,EAAI,QAAS,EAAM,CAAC,CACxD,EAAO,KAAK,CAAG,GAAG,EAAY,GAAGA,EAAI,KAAK,EAAM,KAAK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AAG,2BAA2B,EAAe,IAAI,EAAc,qBACjE,UACA,SACA,GAAG,EACD,UACA,SACA,KAAK,WACJ,EAAO,IAAW,CACjB,IAAM,EAAW,EAAuB,EAAO,CAC3C,KAAS,SAAW,EACxB,OAAO,KAAK,UAAU,GACpB,GAAG,EAAS,IACT,GACC,CAAG,GAAG,EAAM,oCAAoC,EAAQ,qBAC3D,CACF,EAEJ,CACD,eAAgB,EAAO,IAId,CAAG,iBAHQ,CAAG,iCAAiC,EACpD,EACD,CAAC,qBACmC,IAAI,EAAM,GAEjD,UAAW,EAAM,IAAU,CACzB,IAAM,EAAgB,CAAG,gBAAgB,EAAK,cACxC,EAAe,CAAG,gBAAgB,EAAK,cACvC,EAAiB,CAAG,gBAAgB,EAAM,cAC1C,EAAgB,CAAG,gBAAgB,EAAM,cAI/C,MAAO,EAAG,aAAa,EAAK,cAAc,EAAM,+BAA+B,EAA8B,6DAH3F,CAAG,cAAc,EAAc,KAAK,EAAa,mBAAmB,EAAa,UAAU,EAAc,iBAAiB,EAAe,KAAK,EAAc,YAGM,WAEvL,CAGH,OAAoC,CAIlC,wBAAyB,GAIzB,uBAAwB,YAKxB,kBAAmB,EAAQ,IACzB,EAAY,EAAQ,EAAY,KAAK,EAAE,gBAAkB,OAY3D,YAAa,EAEb,eACE,EACA,IAGO,GAAM,CAGf,YACE,EACA,EACA,IAGO,GAAM,CAEhB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{y as t}from"./validation-Dk9Q_-C7.mjs";import{o as n}from"./driver-BlnKXPFF.mjs";import{t as r}from"./postgres-adapter-B3SQvcV1.mjs";function installPostgresAdapter(e,i,a){let o=new r(i,a.postgis===!0);o.capabilities.supportsVector=a.pgvector===!0,a.pgvector||(o.vector=t),n(e,`adapter`,o)}export{installPostgresAdapter as t};
|
|
2
|
+
//# sourceMappingURL=postgres-adapter-CQD2oGuD.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postgres-adapter-CQD2oGuD.mjs","names":[],"sources":["../src/drivers/shared/postgres-adapter.ts"],"sourcesContent":["import { PostgresAdapter } from \"@adapters/databases/postgres/postgres-adapter\";\nimport { unsupportedVector } from \"@errors\";\nimport { defineImmutableDriverFact } from \"./driver-options\";\n\n/**\n * Install a PostgreSQL driver's adapter: `pgvector` alone decides the vector\n * capability, `postgis` the spatial one.\n */\nexport function installPostgresAdapter(\n driver: object,\n namespace: string | undefined,\n options: { readonly pgvector?: boolean; readonly postgis?: boolean }\n): void {\n const adapter = new PostgresAdapter(namespace, options.postgis === true);\n adapter.capabilities.supportsVector = options.pgvector === true;\n if (!options.pgvector) adapter.vector = unsupportedVector;\n defineImmutableDriverFact(driver, \"adapter\", adapter);\n}\n"],"mappings":"qLAQA,SAAgB,uBACd,EACA,EACA,EACM,CACN,IAAM,EAAU,IAAI,EAAgB,EAAW,EAAQ,UAAY,GAAK,CACxE,EAAQ,aAAa,eAAiB,EAAQ,WAAa,GACtD,EAAQ,WAAU,EAAQ,OAAS,GACxC,EAA0B,EAAQ,UAAW,EAAQ"}
|