viborm 1.2.4 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -1
- package/dist/{adapter-internals-n3Mf3css.mjs → adapter-internals-AGgQRu5t.mjs} +1 -1
- package/dist/{adapter-internals-n3Mf3css.mjs.map → adapter-internals-AGgQRu5t.mjs.map} +1 -1
- package/dist/adapter-namespace-BpMbLKpL.mjs +2 -0
- package/dist/{adapter-namespace-DqkJQdrD.mjs.map → adapter-namespace-BpMbLKpL.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs → array-literal-BKdLfNzM.mjs} +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs.map → array-literal-BKdLfNzM.mjs.map} +1 -1
- package/dist/{base-AdXAoy6l.mjs → base-D3m1S7Uc.mjs} +2 -2
- package/dist/{base-AdXAoy6l.mjs.map → base-D3m1S7Uc.mjs.map} +1 -1
- package/dist/{batch-refs-4L8ECdPU.mjs → batch-refs-B4zn-FAu.mjs} +2 -2
- package/dist/{batch-refs-4L8ECdPU.mjs.map → batch-refs-B4zn-FAu.mjs.map} +1 -1
- package/dist/{bind-parameter-capacity-CjPgqnmx.mjs → bind-parameter-capacity-qfEejeOX.mjs} +2 -2
- package/dist/{bind-parameter-capacity-CjPgqnmx.mjs.map → bind-parameter-capacity-qfEejeOX.mjs.map} +1 -1
- package/dist/builder-Df24l2Bd.mjs +2 -0
- package/dist/builder-Df24l2Bd.mjs.map +1 -0
- package/dist/bun-sql.d.mts +3 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/{cache-BO57X0TT.mjs → cache-CIPRF-pz.mjs} +2 -2
- package/dist/{cache-BO57X0TT.mjs.map → cache-CIPRF-pz.mjs.map} +1 -1
- 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 → canonical-json-BReb5nFO.mjs} +2 -2
- package/dist/{canonical-json-rfC2Dg0X.mjs.map → canonical-json-BReb5nFO.mjs.map} +1 -1
- package/dist/chain-C7c1YTXD.mjs +2 -0
- package/dist/chain-C7c1YTXD.mjs.map +1 -0
- package/dist/cli.mjs +2 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/{client-CUnPXifK.d.mts → client-70MrTq1E.d.mts} +3 -3
- package/dist/client-DM1UHfYG.mjs +49 -0
- package/dist/{client-B3VWFhv_.mjs.map → client-DM1UHfYG.mjs.map} +1 -1
- package/dist/client-_WKrPNmm.mjs +2 -0
- package/dist/client-_WKrPNmm.mjs.map +1 -0
- package/dist/client.d.mts +2 -2
- package/dist/client.mjs +1 -1
- package/dist/{clock-CK41KO7t.mjs → clock-C24RcpwO.mjs} +1 -1
- package/dist/{clock-CK41KO7t.mjs.map → clock-C24RcpwO.mjs.map} +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/controls-Da-efekX.mjs +2 -0
- package/dist/controls-Da-efekX.mjs.map +1 -0
- package/dist/{current-DyzK6OCh.mjs → current-oXcxSCBQ.mjs} +1 -1
- package/dist/{current-DyzK6OCh.mjs.map → current-oXcxSCBQ.mjs.map} +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{datetime-physical-codec-oIhiYZEP.mjs → datetime-physical-codec-BEqQbIP_.mjs} +2 -2
- package/dist/{datetime-physical-codec-oIhiYZEP.mjs.map → datetime-physical-codec-BEqQbIP_.mjs.map} +1 -1
- package/dist/driver-B9fIori_.mjs +2 -0
- package/dist/driver-B9fIori_.mjs.map +1 -0
- package/dist/{driver-B19QlFqn.mjs → driver-CPD0Xxw2.mjs} +2 -2
- package/dist/{driver-B19QlFqn.mjs.map → driver-CPD0Xxw2.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-C9WgitPi.mjs +2 -0
- package/dist/error-mapping-C9WgitPi.mjs.map +1 -0
- package/dist/every-1pKZteeB.mjs +2 -0
- package/dist/{every-o-Nu9Em8.mjs.map → every-1pKZteeB.mjs.map} +1 -1
- package/dist/{execution-context-BKR3bgES.mjs → execution-context-rJXTRVrJ.mjs} +1 -1
- package/dist/{execution-context-BKR3bgES.mjs.map → execution-context-rJXTRVrJ.mjs.map} +1 -1
- package/dist/{fs-estate-CAhDg7nY.mjs → fs-estate-i8Zlr1OQ.mjs} +2 -2
- package/dist/{fs-estate-CAhDg7nY.mjs.map → fs-estate-i8Zlr1OQ.mjs.map} +1 -1
- package/dist/{geo-area-codec-1SY9im7O.mjs → geo-area-codec-CbkmFArQ.mjs} +2 -2
- package/dist/{geo-area-codec-1SY9im7O.mjs.map → geo-area-codec-CbkmFArQ.mjs.map} +1 -1
- package/dist/geo-point-codec-DyEHMdJg.mjs +2 -0
- package/dist/geo-point-codec-DyEHMdJg.mjs.map +1 -0
- package/dist/hydration-DsyHNSDS.mjs +2 -0
- package/dist/{hydration-CAxOL4aI.mjs.map → hydration-DsyHNSDS.mjs.map} +1 -1
- package/dist/identifier-conversion-DaZ9yNpv.mjs +2 -0
- package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-DaZ9yNpv.mjs.map} +1 -1
- package/dist/{identity-CLFhCTZx.mjs → identity-oQvIe7u8.mjs} +2 -2
- package/dist/{identity-CLFhCTZx.mjs.map → identity-oQvIe7u8.mjs.map} +1 -1
- package/dist/{index-B0b7asA4.d.mts → index-VsM29vYN.d.mts} +5257 -4915
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{invariant-BnLYqsHO.mjs → invariant-D57gi_yW.mjs} +1 -1
- package/dist/{invariant-BnLYqsHO.mjs.map → invariant-D57gi_yW.mjs.map} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs → json-number-DvmiNx0n.mjs} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs.map → json-number-DvmiNx0n.mjs.map} +1 -1
- package/dist/key-D_kagnFv.mjs +2 -0
- package/dist/{key-BeoOwGr3.mjs.map → key-D_kagnFv.mjs.map} +1 -1
- package/dist/{libsql-Drp-zaxq.mjs → libsql-DFAoHXrI.mjs} +3 -3
- package/dist/{libsql-Drp-zaxq.mjs.map → libsql-DFAoHXrI.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-CDTUZQWL.mjs → memory-GTWgeDNY.mjs} +2 -2
- package/dist/{memory-CDTUZQWL.mjs.map → memory-GTWgeDNY.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +5 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +5 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +5 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.d.mts +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.d.mts +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/{migrations-DTObIjAm.mjs → migrations-Bn1SatyB.mjs} +2 -2
- package/dist/{migrations-DTObIjAm.mjs.map → migrations-Bn1SatyB.mjs.map} +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/mysql-adapter-C6c5govr.mjs +2 -0
- package/dist/{mysql-adapter-DkJPfoGf.mjs.map → mysql-adapter-C6c5govr.mjs.map} +1 -1
- package/dist/{mysql-D7zC03yD.mjs → mysql-xChEivOe.mjs} +6 -6
- package/dist/{mysql-D7zC03yD.mjs.map → mysql-xChEivOe.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/{native-types-veeTk36s.mjs → native-types-asNCr26n.mjs} +1 -1
- package/dist/{native-types-veeTk36s.mjs.map → native-types-asNCr26n.mjs.map} +1 -1
- package/dist/neon-http.d.mts +3 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/{object-store-DQR6bTBY.mjs → object-store-ChYHlOMD.mjs} +2 -2
- package/dist/{object-store-DQR6bTBY.mjs.map → object-store-ChYHlOMD.mjs.map} +1 -1
- package/dist/{object-store-DMFXXQEC.d.mts → object-store-D9mvOHP4.d.mts} +4 -4
- package/dist/{observation-DUSm7oXK.mjs → observation-Co72iCd1.mjs} +2 -2
- package/dist/{observation-DUSm7oXK.mjs.map → observation-Co72iCd1.mjs.map} +1 -1
- package/dist/permissions.d.mts +424 -0
- package/dist/permissions.mjs +2 -0
- package/dist/permissions.mjs.map +1 -0
- package/dist/pg.d.mts +9 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/{physical-6V_LNU3L.mjs → physical-CAOaNM4R.mjs} +2 -2
- package/dist/{physical-6V_LNU3L.mjs.map → physical-CAOaNM4R.mjs.map} +1 -1
- package/dist/{pinned-session-CLxj5M5e.mjs → pinned-session-BTplL3iZ.mjs} +2 -2
- package/dist/{pinned-session-CLxj5M5e.mjs.map → pinned-session-BTplL3iZ.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-C0Q7ks-V.d.mts → planner-C1NzLBge.d.mts} +1 -1
- package/dist/{postgres-Dv-QnnbD.mjs → postgres-BqAxDWTQ.mjs} +4 -4
- package/dist/{postgres-Dv-QnnbD.mjs.map → postgres-BqAxDWTQ.mjs.map} +1 -1
- package/dist/postgres-adapter-CGthb5yh.mjs +2 -0
- package/dist/postgres-adapter-CGthb5yh.mjs.map +1 -0
- package/dist/postgres-adapter-CxEit2-v.mjs +2 -0
- package/dist/postgres-adapter-CxEit2-v.mjs.map +1 -0
- package/dist/{postgres-result-7F0DllQe.mjs → postgres-result-KyBKBNJr.mjs} +2 -2
- package/dist/{postgres-result-7F0DllQe.mjs.map → postgres-result-KyBKBNJr.mjs.map} +1 -1
- package/dist/postgres.d.mts +3 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-BHATED_m.mjs → provider-limits-Da00ilvv.mjs} +2 -2
- package/dist/{provider-limits-BHATED_m.mjs.map → provider-limits-Da00ilvv.mjs.map} +1 -1
- package/dist/{result-parsing-DRXC89ek.mjs → result-parsing-8wEK3GY1.mjs} +1 -1
- package/dist/{result-parsing-DRXC89ek.mjs.map → result-parsing-8wEK3GY1.mjs.map} +1 -1
- package/dist/result-shape-CDgX_vzn.mjs +2 -0
- package/dist/result-shape-CDgX_vzn.mjs.map +1 -0
- package/dist/scalar-S8yMvdmx.mjs +4 -0
- package/dist/scalar-S8yMvdmx.mjs.map +1 -0
- 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-9N9jQlVL.mjs +2 -0
- package/dist/{schema-Cjem1-0f.mjs.map → schema-9N9jQlVL.mjs.map} +1 -1
- package/dist/{schema-introspection-DEYGC2qg.mjs → schema-introspection-CyXKReK1.mjs} +4 -4
- package/dist/{schema-introspection-DEYGC2qg.mjs.map → schema-introspection-CyXKReK1.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-f1UGoblh.mjs → select-assembly-CkGe2ABs.mjs} +2 -2
- package/dist/{select-assembly-f1UGoblh.mjs.map → select-assembly-CkGe2ABs.mjs.map} +1 -1
- package/dist/{settle-B9Vg1FnP.mjs → settle-CS_k6Ztm.mjs} +2 -2
- package/dist/{settle-B9Vg1FnP.mjs.map → settle-CS_k6Ztm.mjs.map} +1 -1
- package/dist/soft-delete.d.mts +27 -96
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/sql-Bhxq9arK.mjs +2 -0
- package/dist/sql-Bhxq9arK.mjs.map +1 -0
- package/dist/{sql-BvfwUKIh.d.mts → sql-EsoN_7Et.d.mts} +24 -0
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CFi1y3bK.mjs} +1 -1
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CFi1y3bK.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-BXAJy3mI.mjs +2 -0
- package/dist/sqlite-adapter-BXAJy3mI.mjs.map +1 -0
- package/dist/{sqlite-utils-DlgokMJN.mjs → sqlite-utils-D_cypcyW.mjs} +2 -2
- package/dist/{sqlite-utils-DlgokMJN.mjs.map → sqlite-utils-D_cypcyW.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +3 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/{standard-sql-Bk4RZPqJ.mjs → standard-sql-CoGqv-iX.mjs} +3 -3
- package/dist/standard-sql-CoGqv-iX.mjs.map +1 -0
- package/dist/{suppressed-failure-BwULh-8h.mjs → suppressed-failure-Bdo2aK81.mjs} +1 -1
- package/dist/{suppressed-failure-BwULh-8h.mjs.map → suppressed-failure-Bdo2aK81.mjs.map} +1 -1
- package/dist/to-many-C1PuFIpf.mjs +2 -0
- package/dist/to-many-C1PuFIpf.mjs.map +1 -0
- package/dist/{transaction-Bnl6ULTw.mjs → transaction-4dfqals6.mjs} +2 -2
- package/dist/{transaction-Bnl6ULTw.mjs.map → transaction-4dfqals6.mjs.map} +1 -1
- package/dist/{transaction-operation-CKK3l_9x.mjs → transaction-operation-CU1zlxiG.mjs} +2 -2
- package/dist/{transaction-operation-CKK3l_9x.mjs.map → transaction-operation-CU1zlxiG.mjs.map} +1 -1
- package/dist/{types-C4v6iAmY.mjs → types-C5Oxz9yp.mjs} +1 -1
- package/dist/{types-C4v6iAmY.mjs.map → types-C5Oxz9yp.mjs.map} +1 -1
- package/dist/{utils-CZNaOZR7.mjs → utils-CtFUE8UN.mjs} +4 -4
- package/dist/{utils-CZNaOZR7.mjs.map → utils-CtFUE8UN.mjs.map} +1 -1
- package/dist/v-CYTUI0H5.mjs +2 -0
- package/dist/v-CYTUI0H5.mjs.map +1 -0
- package/dist/validation-BQtO6srU.mjs +2 -0
- package/dist/{validation-PF9-_nKd.mjs.map → validation-BQtO6srU.mjs.map} +1 -1
- package/dist/validation-BamBwne9.mjs +2 -0
- package/dist/validation-BamBwne9.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-DgffZq9C.mjs +2 -0
- package/dist/validator-DgffZq9C.mjs.map +1 -0
- package/dist/version-CXuJzC-q.mjs +2 -0
- package/dist/{version-nt0parEY.mjs.map → version-CXuJzC-q.mjs.map} +1 -1
- package/package.json +35 -9
- package/dist/adapter-namespace-DqkJQdrD.mjs +0 -2
- package/dist/builder-Ycvq3ETg.mjs +0 -2
- package/dist/builder-Ycvq3ETg.mjs.map +0 -1
- package/dist/chain-Dh0FV72b.mjs +0 -2
- package/dist/chain-Dh0FV72b.mjs.map +0 -1
- package/dist/client-B3VWFhv_.mjs +0 -49
- package/dist/client-BLiBmykn.mjs +0 -2
- package/dist/client-BLiBmykn.mjs.map +0 -1
- package/dist/controls-DXgIn4zh.mjs +0 -2
- package/dist/controls-DXgIn4zh.mjs.map +0 -1
- package/dist/driver-BlnKXPFF.mjs +0 -2
- package/dist/driver-BlnKXPFF.mjs.map +0 -1
- package/dist/error-mapping-CnPCv1dm.mjs +0 -2
- package/dist/error-mapping-CnPCv1dm.mjs.map +0 -1
- package/dist/every-o-Nu9Em8.mjs +0 -2
- package/dist/geo-point-codec-lhxH42SK.mjs +0 -2
- package/dist/geo-point-codec-lhxH42SK.mjs.map +0 -1
- package/dist/hydration-CAxOL4aI.mjs +0 -2
- package/dist/identifier-conversion-GgbwHc2G.mjs +0 -2
- package/dist/identifier-hQCs8M1n.mjs +0 -2
- package/dist/identifier-hQCs8M1n.mjs.map +0 -1
- package/dist/key-BeoOwGr3.mjs +0 -2
- package/dist/mysql-adapter-DkJPfoGf.mjs +0 -2
- package/dist/postgres-adapter-B3SQvcV1.mjs +0 -2
- package/dist/postgres-adapter-B3SQvcV1.mjs.map +0 -1
- package/dist/postgres-adapter-CQD2oGuD.mjs +0 -2
- package/dist/postgres-adapter-CQD2oGuD.mjs.map +0 -1
- package/dist/registration-preflight-DEjv050M.mjs +0 -4
- package/dist/registration-preflight-DEjv050M.mjs.map +0 -1
- package/dist/result-shape-CTNdNSW3.mjs +0 -2
- package/dist/result-shape-CTNdNSW3.mjs.map +0 -1
- package/dist/scalar-U0wD5bKy.mjs +0 -2
- package/dist/scalar-U0wD5bKy.mjs.map +0 -1
- package/dist/schema-Cjem1-0f.mjs +0 -2
- package/dist/sql-Bp7jicEX.mjs +0 -2
- package/dist/sql-Bp7jicEX.mjs.map +0 -1
- package/dist/sqlite-adapter-CW_3l6ea.mjs +0 -2
- package/dist/sqlite-adapter-CW_3l6ea.mjs.map +0 -1
- package/dist/standard-sql-Bk4RZPqJ.mjs.map +0 -1
- package/dist/terminal-C8cq1WWX.mjs +0 -2
- package/dist/terminal-C8cq1WWX.mjs.map +0 -1
- package/dist/v-D5Z06FKN.mjs +0 -2
- package/dist/v-D5Z06FKN.mjs.map +0 -1
- package/dist/validation-Dk9Q_-C7.mjs +0 -2
- package/dist/validation-Dk9Q_-C7.mjs.map +0 -1
- package/dist/validation-PF9-_nKd.mjs +0 -2
- package/dist/validator-X9-bwtRo.mjs +0 -2
- package/dist/validator-X9-bwtRo.mjs.map +0 -1
- package/dist/version-nt0parEY.mjs +0 -2
- /package/dist/{contract-CIIqgFyb.d.mts → contract-Dw0FR78e.d.mts} +0 -0
package/dist/pglite.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{c as t}from"./bind-parameter-capacity-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{c as t}from"./bind-parameter-capacity-qfEejeOX.mjs";import{d as n,l as r}from"./error-mapping-C9WgitPi.mjs";import{s as i}from"./execution-context-rJXTRVrJ.mjs";import{n as a}from"./client-_WKrPNmm.mjs";import{a as o,n as s}from"./pinned-session-BTplL3iZ.mjs";import{c,d as l,r as u,t as d}from"./driver-B9fIori_.mjs";import{t as f}from"./postgres-adapter-CGthb5yh.mjs";import{PGlite as p}from"@electric-sql/pglite";const m=Object.fromEntries([1082,1114,1184,1115,1182,1185].map(e=>[e,e=>e])),h={client:!0,dataDir:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,namespace:!0};function isPGliteDatabase(e){return`transaction`in e}var PGliteDriver=class extends d{maxBindParametersPerStatement=32767;serializeTransactions=!0;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`pglite`);let t=l(e);this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient&&(this.client=this.suppliedClient,Object.defineProperty(this,`connectionQueue`,{value:u(this.suppliedClient)})),f(this,t,e)}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let e=this.driverOptions.dataDir,t=this.driverOptions.options??{},n={...t,parsers:{1114:e=>e,...t.parsers}};return e?await p.create(e,n):await p.create(n)}async closeClient(e){e!==this.suppliedClient&&await e.close()}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,n,r,i,a){let o=i?.operation??a,s=await e.query(n,r,{parsers:m}),c=t(s.affectedRows,{provider:`pglite`,operation:o});return{rows:s.rows,rowCount:s.rows.length>0?s.rows.length:c}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`queue`}}transaction(e,t,a){if(!isPGliteDatabase(e))throw r(this.driverName);return n({run:t=>e.transaction(t),callback:t,phases:i(a),close:async()=>void 0})}async physicalPinnedSession(){return await this.getClient({operation:`pinnedSession`})}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!isPGliteDatabase(e))throw r(this.driverName);return{session:e,release:async t=>{if(t)try{await e.query(`SELECT pg_advisory_unlock_all()`)}catch(t){throw s(e),o(this.driverName,`No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.`,t)}}}}};function createClient(e){c(e,`pglite`,h);let{client:t,dataDir:n,options:r,pgvector:i,postgis:o}=e,s=l(e);return a(e,new PGliteDriver({client:t,dataDir:n,options:r,pgvector:i,postgis:o,sharedRelationBodies:e.sharedRelationBodies,namespace:s}))}export{PGliteDriver,createClient};
|
|
2
2
|
//# sourceMappingURL=pglite.mjs.map
|
package/dist/pglite.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pglite.mjs","names":[],"sources":["../src/drivers/pglite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\n/**\n * PGlite Driver\n *\n * Driver implementation for PGlite (PostgreSQL in WebAssembly).\n * Supports optional pgvector and PostGIS extensions.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n PGlite,\n type PGliteOptions,\n type Transaction,\n} from \"@electric-sql/pglite\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport { normalizeProviderRowCount } from \"../normalized-result\";\nimport {\n nestedTransactionDispatchError,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport {\n condemnPhysicalSession,\n type PinnedSessionReservation,\n unprovenLockStateError,\n} from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type { QueryResult } from \"../types\";\n\nconst temporalParsers = Object.fromEntries(\n [1082, 1114, 1184, 1115, 1182, 1185].map((oid) => [\n oid,\n (value: string) => value,\n ])\n);\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PGliteOptions } from \"@electric-sql/pglite\";\n\nexport interface PGliteDriverOptions {\n client?: PGlite;\n dataDir?: string;\n options?: PGliteOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type PGliteConfig<C extends DriverConfig> = PGliteDriverOptions & C;\n\nconst PGLITE_CONFIG_KEYS: Record<keyof PGliteDriverOptions, true> = {\n client: true,\n dataDir: true,\n options: true,\n pgvector: true,\n postgis: true,\n namespace: true,\n};\n\n/**\n * The database, as opposed to a transaction handle, which has no `transaction`\n * method. Not `instanceof PGlite`: a PGlite built by another copy of\n * `@electric-sql/pglite` (its CommonJS build beside the ESM one, or a second\n * installed version) has another class, and every transaction and pinned\n * command on it used to fail as \"nested provider state\".\n */\nfunction isPGliteDatabase(client: PGlite | Transaction): client is PGlite {\n return \"transaction\" in client;\n}\n\n// === ======================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PGliteDriver extends Driver<PGlite, Transaction> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 32_767;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: PGliteDriverOptions;\n /**\n * The EXACT database the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's database while believing it had made its own.\n */\n private readonly suppliedClient: PGlite | undefined;\n\n constructor(options: PGliteDriverOptions = {}) {\n super(\"postgresql\", \"pglite\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n\n installPostgresAdapter(this, namespace, options);\n }\n\n /**\n * The database this driver runs on.\n *\n * A caller's database is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second, EMPTY in-memory PGlite behind their\n * back — a database they never asked for, holding none of their data, while\n * the one they handed over stayed open and unused.\n */\n protected async initClient(): Promise<PGlite> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const dataDir = this.driverOptions.dataDir;\n const userOptions = this.driverOptions.options ?? {};\n const options: PGliteOptions = {\n ...userOptions,\n parsers: {\n // TIMESTAMP WITHOUT TIME ZONE: PGlite builds process-local Dates,\n // shifting the stored UTC wall clock. Keep the raw string — the\n // shared result parser builds a UTC Date, matching other drivers.\n 1114: (value: string) => value,\n ...userOptions.parsers,\n },\n };\n\n // PGlite.create accepts dataDir as first argument or in options\n return dataDir\n ? await PGlite.create(dataDir, options)\n : await PGlite.create(options);\n }\n\n /**\n * A supplied database belongs to the caller, who may be running two\n * schema-scoped estates over it — the documented shape — and closing it here\n * would take the sibling's data down with this one's `$disconnect()`, on an\n * in-memory database for good.\n *\n * The test is on the client's IDENTITY against what construction captured, so\n * it answers for the database actually being closed rather than for whatever\n * the caller's record says now.\n */\n protected async closeClient(client: PGlite): Promise<void> {\n if (client === this.suppliedClient) {\n return;\n }\n await client.close();\n }\n\n protected async execute<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"execute\");\n }\n\n protected async executeRaw<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const result = await client.query<T>(sql, params, {\n parsers: temporalParsers,\n });\n const affectedRows = normalizeProviderRowCount(result.affectedRows, {\n provider: \"pglite\",\n operation,\n });\n return {\n rows: result.rows,\n rowCount: result.rows.length > 0 ? result.rows.length : affectedRows,\n };\n }\n\n /**\n * PGlite is a full PostgreSQL, so the isolation level is a real post-BEGIN\n * statement. It is also single-connection, so top-level transactions queue —\n * and that queue wait is exactly what `maxWait` bounds.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"queue\",\n };\n }\n\n protected transaction<T>(\n client: PGlite | Transaction,\n fn: (tx: Transaction) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n if (!isPGliteDatabase(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return runProviderManagedTransaction({\n run: (callback) => client.transaction(callback),\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n /**\n * The PGlite instance itself — the physical session a pinned command runs on.\n *\n * A caller may hand ONE PGlite to several drivers (two schema-scoped estates\n * over one database is the documented shape), and each of those drivers owns\n * its own connection queue. The client is what they all agree on, so it is\n * what serializes their pinned commands; without it the second command\n * re-acquires the reentrant session advisory lock the first is holding and\n * runs inside the first command's session.\n */\n protected override async physicalPinnedSession(): Promise<object> {\n return await this.getClient({ operation: \"pinnedSession\" });\n }\n\n /**\n * PGlite's single client, under the queue it already owns — plan §3.5's\n * pinned producer here. There is nothing to reserve and nothing to return:\n * one connection IS the session, which is exactly what a session lock needs.\n *\n * A condemned session can be neither destroyed nor abandoned: closing this\n * client closes the DATABASE, which for an in-memory one takes the caller's\n * data with it and for a supplied one is not VibORM's to do at all. So the\n * session is reset with `pg_advisory_unlock_all()`, and when that reset FAILS\n * the CLIENT is condemned instead — the subject of an unknown lock state is\n * the session, so the condemnation is recorded on it and refuses the next\n * pinned command through every driver over it. Ordinary queries keep working\n * — the data was never in doubt. Swallowing that reset failure was the\n * alternative, and it left the next migration command running inside a\n * session that may still hold the lock, on the one transport where the lock\n * is reentrant and would not stop it.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PGlite | Transaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!isPGliteDatabase(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return {\n session: client,\n release: async (discard) => {\n if (!discard) {\n return;\n }\n try {\n await client.query(\"SELECT pg_advisory_unlock_all()\");\n } catch (resetFailure) {\n condemnPhysicalSession(client);\n throw unprovenLockStateError(\n this.driverName,\n \"No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.\",\n resetFailure\n );\n }\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PGliteConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PGliteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PGliteDriver }\n >]: LinkedClientConfig<C & { driver: PGliteDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pglite\", PGLITE_CONFIG_KEYS);\n const { client, dataDir, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new PGliteDriver({\n client,\n dataDir,\n options,\n pgvector,\n postgis,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, PGliteDriver>(config, driver);\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"pglite.mjs","names":[],"sources":["../src/drivers/pglite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\n/**\n * PGlite Driver\n *\n * Driver implementation for PGlite (PostgreSQL in WebAssembly).\n * Supports optional pgvector and PostGIS extensions.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n PGlite,\n type PGliteOptions,\n type Transaction,\n} from \"@electric-sql/pglite\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport { normalizeProviderRowCount } from \"../normalized-result\";\nimport {\n nestedTransactionDispatchError,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport {\n condemnPhysicalSession,\n type PinnedSessionReservation,\n unprovenLockStateError,\n} from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type { QueryResult } from \"../types\";\n\nconst temporalParsers = Object.fromEntries(\n [1082, 1114, 1184, 1115, 1182, 1185].map((oid) => [\n oid,\n (value: string) => value,\n ])\n);\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PGliteOptions } from \"@electric-sql/pglite\";\n\nexport interface PGliteDriverOptions {\n client?: PGlite;\n dataDir?: string;\n options?: PGliteOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type PGliteConfig<C extends DriverConfig> = PGliteDriverOptions & C;\n\nconst PGLITE_CONFIG_KEYS: Record<keyof PGliteDriverOptions, true> = {\n client: true,\n dataDir: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n namespace: true,\n};\n\n/**\n * The database, as opposed to a transaction handle, which has no `transaction`\n * method. Not `instanceof PGlite`: a PGlite built by another copy of\n * `@electric-sql/pglite` (its CommonJS build beside the ESM one, or a second\n * installed version) has another class, and every transaction and pinned\n * command on it used to fail as \"nested provider state\".\n */\nfunction isPGliteDatabase(client: PGlite | Transaction): client is PGlite {\n return \"transaction\" in client;\n}\n\n// === ======================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PGliteDriver extends Driver<PGlite, Transaction> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 32_767;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: PGliteDriverOptions;\n /**\n * The EXACT database the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's database while believing it had made its own.\n */\n private readonly suppliedClient: PGlite | undefined;\n\n constructor(options: PGliteDriverOptions = {}) {\n super(\"postgresql\", \"pglite\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n\n installPostgresAdapter(this, namespace, options);\n }\n\n /**\n * The database this driver runs on.\n *\n * A caller's database is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second, EMPTY in-memory PGlite behind their\n * back — a database they never asked for, holding none of their data, while\n * the one they handed over stayed open and unused.\n */\n protected async initClient(): Promise<PGlite> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const dataDir = this.driverOptions.dataDir;\n const userOptions = this.driverOptions.options ?? {};\n const options: PGliteOptions = {\n ...userOptions,\n parsers: {\n // TIMESTAMP WITHOUT TIME ZONE: PGlite builds process-local Dates,\n // shifting the stored UTC wall clock. Keep the raw string — the\n // shared result parser builds a UTC Date, matching other drivers.\n 1114: (value: string) => value,\n ...userOptions.parsers,\n },\n };\n\n // PGlite.create accepts dataDir as first argument or in options\n return dataDir\n ? await PGlite.create(dataDir, options)\n : await PGlite.create(options);\n }\n\n /**\n * A supplied database belongs to the caller, who may be running two\n * schema-scoped estates over it — the documented shape — and closing it here\n * would take the sibling's data down with this one's `$disconnect()`, on an\n * in-memory database for good.\n *\n * The test is on the client's IDENTITY against what construction captured, so\n * it answers for the database actually being closed rather than for whatever\n * the caller's record says now.\n */\n protected async closeClient(client: PGlite): Promise<void> {\n if (client === this.suppliedClient) {\n return;\n }\n await client.close();\n }\n\n protected async execute<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"execute\");\n }\n\n protected async executeRaw<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const result = await client.query<T>(sql, params, {\n parsers: temporalParsers,\n });\n const affectedRows = normalizeProviderRowCount(result.affectedRows, {\n provider: \"pglite\",\n operation,\n });\n return {\n rows: result.rows,\n rowCount: result.rows.length > 0 ? result.rows.length : affectedRows,\n };\n }\n\n /**\n * PGlite is a full PostgreSQL, so the isolation level is a real post-BEGIN\n * statement. It is also single-connection, so top-level transactions queue —\n * and that queue wait is exactly what `maxWait` bounds.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"queue\",\n };\n }\n\n protected transaction<T>(\n client: PGlite | Transaction,\n fn: (tx: Transaction) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n if (!isPGliteDatabase(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return runProviderManagedTransaction({\n run: (callback) => client.transaction(callback),\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n /**\n * The PGlite instance itself — the physical session a pinned command runs on.\n *\n * A caller may hand ONE PGlite to several drivers (two schema-scoped estates\n * over one database is the documented shape), and each of those drivers owns\n * its own connection queue. The client is what they all agree on, so it is\n * what serializes their pinned commands; without it the second command\n * re-acquires the reentrant session advisory lock the first is holding and\n * runs inside the first command's session.\n */\n protected override async physicalPinnedSession(): Promise<object> {\n return await this.getClient({ operation: \"pinnedSession\" });\n }\n\n /**\n * PGlite's single client, under the queue it already owns — plan §3.5's\n * pinned producer here. There is nothing to reserve and nothing to return:\n * one connection IS the session, which is exactly what a session lock needs.\n *\n * A condemned session can be neither destroyed nor abandoned: closing this\n * client closes the DATABASE, which for an in-memory one takes the caller's\n * data with it and for a supplied one is not VibORM's to do at all. So the\n * session is reset with `pg_advisory_unlock_all()`, and when that reset FAILS\n * the CLIENT is condemned instead — the subject of an unknown lock state is\n * the session, so the condemnation is recorded on it and refuses the next\n * pinned command through every driver over it. Ordinary queries keep working\n * — the data was never in doubt. Swallowing that reset failure was the\n * alternative, and it left the next migration command running inside a\n * session that may still hold the lock, on the one transport where the lock\n * is reentrant and would not stop it.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PGlite | Transaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!isPGliteDatabase(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return {\n session: client,\n release: async (discard) => {\n if (!discard) {\n return;\n }\n try {\n await client.query(\"SELECT pg_advisory_unlock_all()\");\n } catch (resetFailure) {\n condemnPhysicalSession(client);\n throw unprovenLockStateError(\n this.driverName,\n \"No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.\",\n resetFailure\n );\n }\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PGliteConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PGliteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PGliteDriver }\n >]: LinkedClientConfig<C & { driver: PGliteDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pglite\", PGLITE_CONFIG_KEYS);\n const { client, dataDir, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new PGliteDriver({\n client,\n dataDir,\n options,\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, PGliteDriver>(config, driver);\n}\n"],"mappings":"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"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{
|
|
2
|
-
//# sourceMappingURL=physical-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{lt as t,st as n}from"./geo-point-codec-DyEHMdJg.mjs";import{i as r,o as i,r as a,t as o}from"./native-types-asNCr26n.mjs";const s=new WeakMap;function idDomainOfState(e){return e?.array===!0?void 0:idMemberDomainOfState(e)}function idMemberDomainOfState(e){if(e===void 0||e.type!==`string`)return;let n=s.get(e);if(n)return n;let r=e.autoGenerate;if(r===void 0||!t(r.kind)||r.implicit===!0)return;let i={format:r.kind,prefix:r.prefix,length:r.length};return s.set(e,i),i}const c=/^(?:text|citext|varchar\(\d+\))$/,l=/^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\(\d+\)|CHAR\(\d+\))$/,u=/^TEXT$/,d=/^(?:BINARY|VARBINARY)\((\d+)\)$/;function defaultIdStorage(e,t){let i=n(e);if(i===void 0)switch(t){case`pg`:return{representation:`text`,columnType:a.STRING.TEXT.type};case`mysql`:return{representation:`text`,columnType:`TEXT`};default:return{representation:`text`,columnType:r.STRING.TEXT.type}}switch(t){case`pg`:return e===`uuid`||e===`uuidv7`?{representation:`uuid`,columnType:a.STRING.UUID.type}:{representation:`bytes`,columnType:a.BLOB.BYTEA.type};case`mysql`:return{representation:`bytes`,columnType:o.BLOB.BINARY(i).type};default:return{representation:`bytes`,columnType:r.BLOB.BLOB.type}}}function isTextColumnType(e,t){switch(t){case`pg`:return c.test(e);case`mysql`:return l.test(e);default:return u.test(e)}}function binaryRepresentation(e,t,i){let s=n(t);if(s===void 0)return;if(i===`pg`)return e===a.BLOB.BYTEA.type?`bytes`:e===a.STRING.UUID.type&&(t===`uuid`||t===`uuidv7`)?`uuid`:void 0;if(i===`sqlite`)return e===r.BLOB.BLOB.type?`bytes`:void 0;if(e===o.BLOB.BLOB.type)return`bytes`;let c=d.exec(e);return c&&Number(c[1])===s?`bytes`:void 0}function idStorageOf(e,t,n){let r=i(t,n);if(r===void 0)return defaultIdStorage(e.format,n);let a=r.type;if(isTextColumnType(a,n))return{representation:`text`,columnType:a};let o=binaryRepresentation(a,e.format,n);return o===void 0?void 0:{representation:o,columnType:a}}function describeIdNativeTypes(e,t){let r=n(e),i=t===`pg`?`text, citext, varchar(n)`:t===`mysql`?`TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)`:`TEXT`;return r===void 0?i:`${t===`pg`?e===`uuid`||e===`uuidv7`?`uuid, bytea`:`bytea`:t===`mysql`?`BINARY(${r}), VARBINARY(${r}), BLOB`:`BLOB`}, ${i}`}function sqliteDateTimePhysicalForm(e){let t=i(e,`sqlite`);return t===void 0?`text`:t.type===`INTEGER`?`epochMillis`:t.type===`REAL`?`julianDay`:`text`}export{idStorageOf as a,idMemberDomainOfState as i,describeIdNativeTypes as n,idDomainOfState as r,sqliteDateTimePhysicalForm as t};
|
|
2
|
+
//# sourceMappingURL=physical-CAOaNM4R.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"physical-6V_LNU3L.mjs","names":[],"sources":["../src/schema/scalars/string/id-domain.ts","../src/schema/scalars/datetime/physical.ts"],"sourcesContent":["/**\n * Where a DECLARED identifier domain is read from, and how it becomes a column.\n *\n * There is no second declaration: `ScalarState.autoGenerate` — the same record\n * `.uuid()`, `.ulid()`, `.ksuid()`, `.nanoid()` and `.cuid()` already write —\n * IS the domain. This module only projects it into the shape the codec takes,\n * and answers the one storage question the projection cannot: which physical\n * representation and which column spelling this domain has on a given dialect,\n * with a native type override taken into account.\n *\n * Storage lives HERE rather than in the codec because it is the only part of\n * the identifier language that speaks a dialect's vocabulary. The codec below\n * it stays pure — it takes a representation, never a provider — so the\n * validation schemas, which run long before any adapter exists, can use it.\n */\n\nimport {\n type IdDomain,\n type IdFormat,\n type IdRepresentation,\n idByteLength,\n isIdFormat,\n} from \"@validation/primitives/id-codec\";\nimport type { AutoGenerate, ScalarState } from \"../common\";\nimport {\n MYSQL,\n type NativeDialect,\n type NativeTypeDeclaration,\n nativeTypeFor,\n PG,\n SQLITE,\n} from \"../native-types\";\n\n// =============================================================================\n// THE DECLARED DOMAIN\n// =============================================================================\n\nconst DOMAINS = new WeakMap<ScalarState, IdDomain>();\n\n/**\n * The identifier domain a scalar state declares, or `undefined`.\n *\n * Only a NAMED format declares one. `.id()` installs a ULID generator without\n * naming a format (see {@link AutoGenerate.implicit}), so a `.id()` key has no\n * domain: nothing admits its values and nothing narrows its storage.\n *\n * A LIST answers `undefined` deliberately, exactly as the decimal descriptor\n * lookup does: physical parameter encoding, projection, decode and DDL must\n * not bind a whole container as one compact identifier. List admission reads\n * the same declaration through idMemberDomainOfState instead.\n *\n * The projection is memoized per state so the hot write path compares and\n * encodes against one object instead of allocating a domain per value.\n */\nexport function idDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n return state?.array === true ? undefined : idMemberDomainOfState(state);\n}\n\n/** The named member domain, also used by lists with plain string storage. */\nexport function idMemberDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n if (state === undefined || state.type !== \"string\") return undefined;\n const existing = DOMAINS.get(state);\n if (existing) return existing;\n const generate = state.autoGenerate;\n if (generate === undefined || !isIdFormat(generate.kind)) return undefined;\n // A format the caller did not NAME is not a domain the caller asserted:\n // `.id()` declares a key and carries a generator for convenience, and its\n // values stay whatever a string column holds. `.ulid().id()` names the\n // format and gets the domain, the admission and the compact column.\n if (generate.implicit === true) return undefined;\n const domain: IdDomain = {\n format: generate.kind,\n prefix: generate.prefix,\n length: generate.length,\n };\n DOMAINS.set(state, domain);\n return domain;\n}\n\n// =============================================================================\n// PHYSICAL STORAGE\n// =============================================================================\n\n/** The three dialects a column spelling is asked for. */\nexport type IdDialect = NativeDialect;\n\n/** What one domain is physically, on one dialect. */\nexport interface IdStorage {\n readonly representation: IdRepresentation;\n /** The column type this dialect spells it with. */\n readonly columnType: string;\n}\n\n// `char(n)` is absent deliberately. PostgreSQL BLANK-PADS `character(n)` to its\n// full width, so a 36-character uuid in a `char(40)` column reads back with four\n// trailing spaces and no value of the domain is ever returned — the column is\n// unusable from the moment it is created, for every n wider than the format's\n// own public spelling. MySQL's `CHAR(n)` pads on the way in and STRIPS on the\n// way out, so it keeps its place in that dialect's list.\nconst PG_TEXT_FAMILY = /^(?:text|citext|varchar\\(\\d+\\))$/;\nconst MYSQL_TEXT_FAMILY =\n /^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\\(\\d+\\)|CHAR\\(\\d+\\))$/;\nconst SQLITE_TEXT_FAMILY = /^TEXT$/;\nconst MYSQL_SIZED_BINARY = /^(?:BINARY|VARBINARY)\\((\\d+)\\)$/;\n\n/** The default column spelling and representation, before any override. */\nfunction defaultIdStorage(format: IdFormat, dialect: IdDialect): IdStorage {\n const width = idByteLength(format);\n if (width === undefined) {\n // `nanoid` and `cuid` keep the text column the dialect already gave them.\n switch (dialect) {\n case \"pg\":\n return { representation: \"text\", columnType: PG.STRING.TEXT.type };\n case \"mysql\":\n return { representation: \"text\", columnType: \"TEXT\" };\n default:\n return {\n representation: \"text\",\n columnType: SQLITE.STRING.TEXT.type,\n };\n }\n }\n switch (dialect) {\n case \"pg\":\n // A UUID gets PostgreSQL's own 16-byte type, which the wire spells as\n // canonical text. A ULID is never spelled `uuid`: its bytes are not a\n // UUID's and a database that formatted them as one would publish a\n // version nibble the value does not have.\n return format === \"uuid\" || format === \"uuidv7\"\n ? { representation: \"uuid\", columnType: PG.STRING.UUID.type }\n : { representation: \"bytes\", columnType: PG.BLOB.BYTEA.type };\n case \"mysql\":\n return {\n representation: \"bytes\",\n columnType: MYSQL.BLOB.BINARY(width).type,\n };\n default:\n return { representation: \"bytes\", columnType: SQLITE.BLOB.BLOB.type };\n }\n}\n\n/** Whether this dialect spells `type` as one of its text column types. */\nfunction isTextColumnType(type: string, dialect: IdDialect): boolean {\n switch (dialect) {\n case \"pg\":\n return PG_TEXT_FAMILY.test(type);\n case \"mysql\":\n return MYSQL_TEXT_FAMILY.test(type);\n default:\n return SQLITE_TEXT_FAMILY.test(type);\n }\n}\n\n/**\n * The representation a BINARY-family override names for this format, or\n * `undefined` when the override is not a binary column this domain fits.\n *\n * A sized MySQL column must be the format's exact width: `BINARY(16)` holds a\n * KSUID's first sixteen bytes and pads a ULID that was never short, and both\n * are silent corruptions rather than storage choices. `bytea` and `BLOB` carry\n * no declared width, so the codec's exact-width encoding is the only promise\n * they need.\n */\nfunction binaryRepresentation(\n type: string,\n format: IdFormat,\n dialect: IdDialect\n): IdRepresentation | undefined {\n const width = idByteLength(format);\n if (width === undefined) return undefined;\n if (dialect === \"pg\") {\n if (type === PG.BLOB.BYTEA.type) return \"bytes\";\n return type === PG.STRING.UUID.type &&\n (format === \"uuid\" || format === \"uuidv7\")\n ? \"uuid\"\n : undefined;\n }\n if (dialect === \"sqlite\") {\n return type === SQLITE.BLOB.BLOB.type ? \"bytes\" : undefined;\n }\n if (type === MYSQL.BLOB.BLOB.type) return \"bytes\";\n const sized = MYSQL_SIZED_BINARY.exec(type);\n return sized && Number(sized[1]) === width ? \"bytes\" : undefined;\n}\n\n/**\n * The column spelling and representation of one domain on one dialect.\n *\n * The ONE owner of that decision: the migration type mapping, the parameter\n * encoding, the read projection and the result decode all derive from this, so\n * a column cannot be created as one thing and written as another.\n *\n * The declaration is resolved for THIS dialect (`nativeTypeFor`): a tagged\n * native type for another dialect, or a map without this dialect's entry, is\n * not this dialect's column and is ignored exactly as every other scalar's\n * mapping ignores it. An override that IS this\n * dialect's and that this domain cannot live in returns `undefined` — the\n * schema boundary refuses it by name long before a query is built, and this\n * answering `undefined` rather than guessing is what keeps that refusal the\n * only place the question is decided.\n */\nexport function idStorageOf(\n domain: IdDomain,\n declaration: NativeTypeDeclaration | undefined,\n dialect: IdDialect\n): IdStorage | undefined {\n const nativeType = nativeTypeFor(declaration, dialect);\n if (nativeType === undefined) {\n return defaultIdStorage(domain.format, dialect);\n }\n const type = nativeType.type;\n if (isTextColumnType(type, dialect)) {\n // The opt-out for a column that already holds text: the domain is still\n // admitted and normalized, only its storage stays as it was.\n return { representation: \"text\", columnType: type };\n }\n const representation = binaryRepresentation(type, domain.format, dialect);\n return representation === undefined\n ? undefined\n : { representation, columnType: type };\n}\n\n/** The overrides this domain accepts on this dialect, for a refusal message. */\nexport function describeIdNativeTypes(\n format: IdFormat,\n dialect: IdDialect\n): string {\n const width = idByteLength(format);\n const text =\n dialect === \"pg\"\n ? \"text, citext, varchar(n)\"\n : dialect === \"mysql\"\n ? \"TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)\"\n : \"TEXT\";\n if (width === undefined) return text;\n const binary =\n dialect === \"pg\"\n ? format === \"uuid\" || format === \"uuidv7\"\n ? \"uuid, bytea\"\n : \"bytea\"\n : dialect === \"mysql\"\n ? `BINARY(${width}), VARBINARY(${width}), BLOB`\n : \"BLOB\";\n return `${binary}, ${text}`;\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport { type NativeTypeDeclaration, nativeTypeFor } from \"../native-types\";\n\n/**\n * The physical vocabulary SQLite assigns to one DateTime native declaration.\n *\n * A missing declaration, a declaration that selects nothing on SQLite, and\n * explicit TEXT all use SQLite's default timestamp text. INTEGER is epoch milliseconds and\n * REAL is a Julian day. Schema validation, query lowering, result parsing, and\n * migration defaults consume this same interpretation.\n */\nexport function sqliteDateTimePhysicalForm(\n declaration: NativeTypeDeclaration | undefined\n): DateTimePhysicalForm {\n const nativeType = nativeTypeFor(declaration, \"sqlite\");\n if (nativeType === undefined) return \"text\";\n if (nativeType.type === \"INTEGER\") return \"epochMillis\";\n return nativeType.type === \"REAL\" ? \"julianDay\" : \"text\";\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"physical-CAOaNM4R.mjs","names":[],"sources":["../src/schema/scalars/string/id-domain.ts","../src/schema/scalars/datetime/physical.ts"],"sourcesContent":["/**\n * Where a DECLARED identifier domain is read from, and how it becomes a column.\n *\n * There is no second declaration: `ScalarState.autoGenerate` — the same record\n * `.uuid()`, `.ulid()`, `.ksuid()`, `.nanoid()` and `.cuid()` already write —\n * IS the domain. This module only projects it into the shape the codec takes,\n * and answers the one storage question the projection cannot: which physical\n * representation and which column spelling this domain has on a given dialect,\n * with a native type override taken into account.\n *\n * Storage lives HERE rather than in the codec because it is the only part of\n * the identifier language that speaks a dialect's vocabulary. The codec below\n * it stays pure — it takes a representation, never a provider — so the\n * validation schemas, which run long before any adapter exists, can use it.\n */\n\nimport {\n type IdDomain,\n type IdFormat,\n type IdRepresentation,\n idByteLength,\n isIdFormat,\n} from \"@validation/primitives/id-codec\";\nimport type { AutoGenerate, ScalarState } from \"../common\";\nimport {\n MYSQL,\n type NativeDialect,\n type NativeTypeDeclaration,\n nativeTypeFor,\n PG,\n SQLITE,\n} from \"../native-types\";\n\n// =============================================================================\n// THE DECLARED DOMAIN\n// =============================================================================\n\nconst DOMAINS = new WeakMap<ScalarState, IdDomain>();\n\n/**\n * The identifier domain a scalar state declares, or `undefined`.\n *\n * Only a NAMED format declares one. `.id()` installs a ULID generator without\n * naming a format (see {@link AutoGenerate.implicit}), so a `.id()` key has no\n * domain: nothing admits its values and nothing narrows its storage.\n *\n * A LIST answers `undefined` deliberately, exactly as the decimal descriptor\n * lookup does: physical parameter encoding, projection, decode and DDL must\n * not bind a whole container as one compact identifier. List admission reads\n * the same declaration through idMemberDomainOfState instead.\n *\n * The projection is memoized per state so the hot write path compares and\n * encodes against one object instead of allocating a domain per value.\n */\nexport function idDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n return state?.array === true ? undefined : idMemberDomainOfState(state);\n}\n\n/** The named member domain, also used by lists with plain string storage. */\nexport function idMemberDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n if (state === undefined || state.type !== \"string\") return undefined;\n const existing = DOMAINS.get(state);\n if (existing) return existing;\n const generate = state.autoGenerate;\n if (generate === undefined || !isIdFormat(generate.kind)) return undefined;\n // A format the caller did not NAME is not a domain the caller asserted:\n // `.id()` declares a key and carries a generator for convenience, and its\n // values stay whatever a string column holds. `.ulid().id()` names the\n // format and gets the domain, the admission and the compact column.\n if (generate.implicit === true) return undefined;\n const domain: IdDomain = {\n format: generate.kind,\n prefix: generate.prefix,\n length: generate.length,\n };\n DOMAINS.set(state, domain);\n return domain;\n}\n\n// =============================================================================\n// PHYSICAL STORAGE\n// =============================================================================\n\n/** The three dialects a column spelling is asked for. */\nexport type IdDialect = NativeDialect;\n\n/** What one domain is physically, on one dialect. */\nexport interface IdStorage {\n readonly representation: IdRepresentation;\n /** The column type this dialect spells it with. */\n readonly columnType: string;\n}\n\n// `char(n)` is absent deliberately. PostgreSQL BLANK-PADS `character(n)` to its\n// full width, so a 36-character uuid in a `char(40)` column reads back with four\n// trailing spaces and no value of the domain is ever returned — the column is\n// unusable from the moment it is created, for every n wider than the format's\n// own public spelling. MySQL's `CHAR(n)` pads on the way in and STRIPS on the\n// way out, so it keeps its place in that dialect's list.\nconst PG_TEXT_FAMILY = /^(?:text|citext|varchar\\(\\d+\\))$/;\nconst MYSQL_TEXT_FAMILY =\n /^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\\(\\d+\\)|CHAR\\(\\d+\\))$/;\nconst SQLITE_TEXT_FAMILY = /^TEXT$/;\nconst MYSQL_SIZED_BINARY = /^(?:BINARY|VARBINARY)\\((\\d+)\\)$/;\n\n/** The default column spelling and representation, before any override. */\nfunction defaultIdStorage(format: IdFormat, dialect: IdDialect): IdStorage {\n const width = idByteLength(format);\n if (width === undefined) {\n // `nanoid` and `cuid` keep the text column the dialect already gave them.\n switch (dialect) {\n case \"pg\":\n return { representation: \"text\", columnType: PG.STRING.TEXT.type };\n case \"mysql\":\n return { representation: \"text\", columnType: \"TEXT\" };\n default:\n return {\n representation: \"text\",\n columnType: SQLITE.STRING.TEXT.type,\n };\n }\n }\n switch (dialect) {\n case \"pg\":\n // A UUID gets PostgreSQL's own 16-byte type, which the wire spells as\n // canonical text. A ULID is never spelled `uuid`: its bytes are not a\n // UUID's and a database that formatted them as one would publish a\n // version nibble the value does not have.\n return format === \"uuid\" || format === \"uuidv7\"\n ? { representation: \"uuid\", columnType: PG.STRING.UUID.type }\n : { representation: \"bytes\", columnType: PG.BLOB.BYTEA.type };\n case \"mysql\":\n return {\n representation: \"bytes\",\n columnType: MYSQL.BLOB.BINARY(width).type,\n };\n default:\n return { representation: \"bytes\", columnType: SQLITE.BLOB.BLOB.type };\n }\n}\n\n/** Whether this dialect spells `type` as one of its text column types. */\nfunction isTextColumnType(type: string, dialect: IdDialect): boolean {\n switch (dialect) {\n case \"pg\":\n return PG_TEXT_FAMILY.test(type);\n case \"mysql\":\n return MYSQL_TEXT_FAMILY.test(type);\n default:\n return SQLITE_TEXT_FAMILY.test(type);\n }\n}\n\n/**\n * The representation a BINARY-family override names for this format, or\n * `undefined` when the override is not a binary column this domain fits.\n *\n * A sized MySQL column must be the format's exact width: `BINARY(16)` holds a\n * KSUID's first sixteen bytes and pads a ULID that was never short, and both\n * are silent corruptions rather than storage choices. `bytea` and `BLOB` carry\n * no declared width, so the codec's exact-width encoding is the only promise\n * they need.\n */\nfunction binaryRepresentation(\n type: string,\n format: IdFormat,\n dialect: IdDialect\n): IdRepresentation | undefined {\n const width = idByteLength(format);\n if (width === undefined) return undefined;\n if (dialect === \"pg\") {\n if (type === PG.BLOB.BYTEA.type) return \"bytes\";\n return type === PG.STRING.UUID.type &&\n (format === \"uuid\" || format === \"uuidv7\")\n ? \"uuid\"\n : undefined;\n }\n if (dialect === \"sqlite\") {\n return type === SQLITE.BLOB.BLOB.type ? \"bytes\" : undefined;\n }\n if (type === MYSQL.BLOB.BLOB.type) return \"bytes\";\n const sized = MYSQL_SIZED_BINARY.exec(type);\n return sized && Number(sized[1]) === width ? \"bytes\" : undefined;\n}\n\n/**\n * The column spelling and representation of one domain on one dialect.\n *\n * The ONE owner of that decision: the migration type mapping, the parameter\n * encoding, the read projection and the result decode all derive from this, so\n * a column cannot be created as one thing and written as another.\n *\n * The declaration is resolved for THIS dialect (`nativeTypeFor`): a tagged\n * native type for another dialect, or a map without this dialect's entry, is\n * not this dialect's column and is ignored exactly as every other scalar's\n * mapping ignores it. An override that IS this\n * dialect's and that this domain cannot live in returns `undefined` — the\n * schema boundary refuses it by name long before a query is built, and this\n * answering `undefined` rather than guessing is what keeps that refusal the\n * only place the question is decided.\n */\nexport function idStorageOf(\n domain: IdDomain,\n declaration: NativeTypeDeclaration | undefined,\n dialect: IdDialect\n): IdStorage | undefined {\n const nativeType = nativeTypeFor(declaration, dialect);\n if (nativeType === undefined) {\n return defaultIdStorage(domain.format, dialect);\n }\n const type = nativeType.type;\n if (isTextColumnType(type, dialect)) {\n // The opt-out for a column that already holds text: the domain is still\n // admitted and normalized, only its storage stays as it was.\n return { representation: \"text\", columnType: type };\n }\n const representation = binaryRepresentation(type, domain.format, dialect);\n return representation === undefined\n ? undefined\n : { representation, columnType: type };\n}\n\n/** The overrides this domain accepts on this dialect, for a refusal message. */\nexport function describeIdNativeTypes(\n format: IdFormat,\n dialect: IdDialect\n): string {\n const width = idByteLength(format);\n const text =\n dialect === \"pg\"\n ? \"text, citext, varchar(n)\"\n : dialect === \"mysql\"\n ? \"TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)\"\n : \"TEXT\";\n if (width === undefined) return text;\n const binary =\n dialect === \"pg\"\n ? format === \"uuid\" || format === \"uuidv7\"\n ? \"uuid, bytea\"\n : \"bytea\"\n : dialect === \"mysql\"\n ? `BINARY(${width}), VARBINARY(${width}), BLOB`\n : \"BLOB\";\n return `${binary}, ${text}`;\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport { type NativeTypeDeclaration, nativeTypeFor } from \"../native-types\";\n\n/**\n * The physical vocabulary SQLite assigns to one DateTime native declaration.\n *\n * A missing declaration, a declaration that selects nothing on SQLite, and\n * explicit TEXT all use SQLite's default timestamp text. INTEGER is epoch milliseconds and\n * REAL is a Julian day. Schema validation, query lowering, result parsing, and\n * migration defaults consume this same interpretation.\n */\nexport function sqliteDateTimePhysicalForm(\n declaration: NativeTypeDeclaration | undefined\n): DateTimePhysicalForm {\n const nativeType = nativeTypeFor(declaration, \"sqlite\");\n if (nativeType === undefined) return \"text\";\n if (nativeType.type === \"INTEGER\") return \"epochMillis\";\n return nativeType.type === \"REAL\" ? \"julianDay\" : \"text\";\n}\n"],"mappings":"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"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,n}from"./base-
|
|
2
|
-
//# sourceMappingURL=pinned-session-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,n}from"./base-D3m1S7Uc.mjs";import{i as r}from"./validation-BamBwne9.mjs";import{n as i}from"./suppressed-failure-Bdo2aK81.mjs";import{t as a}from"./settle-CS_k6Ztm.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-BTplL3iZ.mjs.map
|
|
@@ -1 +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,kCAKjB,EAAwB,kFAAkF,EAAe,iBAWlH,EAAmB,IA4EhC,SAAgB,uBACd,EACA,EACA,EACiB,CACjB,OAAO,sBACL,EACA,EACA,EACA,EAAW,EAAM,CAClB,CAGH,SAAS,sBACP,EACA,EACA,EACA,EACiB,CACjB,OAAO,IAAI,EACT,WAAW,EAAW,IAAI,EAAO,GAAG,IACpC,CACE,KAAM,EAAgB,kBACtB,QACA,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAaH,SAAgB,sBAAsB,EAAqC,CACzE,OAAO,IAAI,EACT,WAAW,EAAW,iEAAiE,EAAe,4NACtG,CACE,KAAM,EAAgB,kBACtB,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAcH,MAAM,EACJ,yLA4BF,eAAsB,+BAA+B,EAUnC,CAChB,GAAI,EAAY,OAAS,GAAM,CAC7B,GAAM,CAAE,sBAAqB,cAAe,EAC5C,GAAI,IAAwB,IAAA,GAC1B,MAAM,sBACJ,EACA,mFACA,EACA,IAAA,GACD,CAOH,GAAqB,CAAC,UAAY,IAAA,GAAU,CAC5C,OAEF,GAAI,CAAC,EAAY,QAAS,CACxB,EAAY,SAAS,CACrB,OAGF,GAAI,CACF,MAAM,EACJ,EAAY,OAAO,CACnB,MAEM,MACF,+CAA+C,EAAiB,MACjE,CACJ,OACM,EAAc,CACrB,MAAM,QAAQ,EAAa,EAAuB,EAAa,CAEjE,EAAY,SAAS,CAQvB,eAAe,QACb,EAIA,EACA,EACe,CACf,GAAM,CAAE,sBAAqB,cAAe,EAC5C,GAAI,IAAwB,IAAA,GAC1B,MAAM,sBACJ,EACA,EACA,EACA,EAAW,EAAM,CAClB,CAEH,GAAI,CACF,MAAM,GAAqB,OACpB,EAAc,CAGrB,MAAM,EACJ,sBACE,EACA,EACA,8RACA,EAAW,EAAM,CAClB,CACD,EACD,CAEH,MAAM,sBACJ,EACA,EACA,iMACA,EAAW,EAAM,CAClB,CAsCH,MAAM,EAAoB,IAAI,QAY9B,SAAS,uBACP,EACA,EACM,CACN,GAAI,EAAM,UACR,MAAM,sBAAsB,EAAW,CAY3C,SAAgB,mBACd,EACA,EACA,EACY,CACZ,IAAM,EAAQ,qBAAqB,EAAQ,CAC3C,uBAAuB,EAAY,EAAM,CACzC,IAAM,EAAO,EAAM,OAAO,UACxB,uBAAuB,EAAY,EAAM,CAClC,GAAS,EAChB,CAKF,MAJA,GAAM,OAAS,EAAK,SACZ,IAAA,OACA,IAAA,GACP,CACM,EAQT,SAAgB,uBAAuB,EAAuB,CAC5D,qBAAqB,EAAQ,CAAC,UAAY,GAI5C,SAAS,qBAAqB,EAAuC,CACnE,IAAM,EAAW,EAAkB,IAAI,EAAQ,CAC/C,GAAI,EACF,OAAO,EAET,IAAM,EAAgC,CACpC,OAAQ,QAAQ,SAAS,CACzB,UAAW,GACZ,CAED,OADA,EAAkB,IAAI,EAAS,EAAQ,CAChC"}
|
|
1
|
+
{"version":3,"file":"pinned-session-BTplL3iZ.mjs","names":[],"sources":["../src/drivers/shared/pinned-session.ts"],"sourcesContent":["import { ConnectionError, VibORMErrorCode } from \"@errors\";\nimport { errorCause } from \"../../errors/diagnostic-safety\";\nimport { settleWithin } from \"./settle\";\nimport { withSuppressedFailure } from \"./suppressed-failure\";\n\n/** The PostgreSQL statement that resets a session's advisory-lock state. */\nconst ADVISORY_RESET = \"SELECT pg_advisory_unlock_all()\";\n\n/** Why a reserved session is abandoned, in the refusal's own words. */\nconst LOST_SESSION =\n \"lost the connection of a reserved migration session and sent nothing more on it.\";\nconst ADVISORY_RESET_FAILED = `could not prove the advisory-lock state of a discarded migration session: its \"${ADVISORY_RESET}\" reset failed.`;\n\n/**\n * How long one cleanup statement — `ROLLBACK`, the unlock, the limits reset,\n * the advisory reset — may take before its session is treated as lost.\n *\n * A healthy server answers each of them in milliseconds. A session that does\n * not answer one within this bound is a half-open socket or a dying backend,\n * and waiting on it longer only keeps the caller from the failure it already\n * has (plan S2: \"bound every cleanup statement\").\n */\nexport const CLEANUP_BOUND_MS = 5000;\n\n/**\n * One reserved physical session, as a provider hands it back.\n *\n * The plan's requirement (§3.5) is \"one physical producer across decisions and\n * commit boundaries\": a session lock is session-scoped, so acquiring it through\n * one pooled connection and running the protected work through another protects\n * nothing and can strand the lock. A reservation is therefore a connection the\n * provider has taken OUT of its pool, plus the exact way to give it back.\n */\nexport interface PinnedSessionReservation<TSession> {\n /** The reserved producer. Every statement of the session runs on it. */\n readonly session: TSession;\n /**\n * The failure the provider itself saw end this session's connection, or\n * `undefined` while it has seen none.\n *\n * Only a provider that observes its connection has one (`pg`, through the\n * client's `error` event). Elsewhere a lost connection is recognized by the\n * failure that reported it.\n */\n readonly lost?: () => unknown;\n /**\n * Returns the producer to the provider.\n *\n * `discard` is true when the session's state is unknown — a failed unlock, a\n * failed cleanup, or a thrown body — and the provider must then destroy the\n * connection rather than hand a session carrying unknown state back to a\n * pool. A provider whose session can never be made clean again (MySQL2, which\n * has executed `USE` and possibly author-owned statements) destroys\n * unconditionally and ignores the flag.\n *\n * `lost` is true when the connection itself is gone or stopped answering:\n * the provider must send nothing more on it — not even the reset a discard\n * otherwise runs — and abandon or destroy it.\n */\n release(discard: boolean, lost?: boolean): Promise<void>;\n}\n\n/**\n * The handle the pinned body uses to condemn its own producer.\n *\n * A thrown body already condemns the session. This exists for the case that\n * does not throw: an unlock statement that RETURNS a result proving the lock\n * was not released. That session is still usable in the provider's eyes and\n * would be returned to the pool holding a lock nobody owns.\n */\nexport interface PinnedSessionControl {\n /** Condemn this producer; it will be destroyed instead of released. */\n discard(): void;\n /**\n * Whether this session's connection is gone: the provider saw it end,\n * `failure` reports it, or a cleanup statement went unanswered. Once true it\n * stays true, and nothing more is sent on the session (plan S2).\n */\n lost(failure?: unknown): boolean;\n /** Runs one cleanup statement within `CLEANUP_BOUND_MS`; past it, the session is lost. */\n cleanup<T>(run: () => Promise<T>): Promise<T>;\n}\n\n/**\n * The refusal a discarded session whose reset FAILED raises.\n *\n * A session is discarded because its state is unknown, and the reset is what\n * makes it known again. When the reset fails too, the session may still hold\n * the migration lock every other command is excluded by — so it must not go\n * back to the provider, and saying nothing about that is not an option either:\n * a swallowed cleanup failure is how a pool ends up serving a connection that\n * blocks the next migration forever.\n *\n * The reset's own failure is the evidence, and it is the PROVIDER's value: it\n * goes through the one total normalizer rather than a bare `instanceof`, which\n * a rejection whose `getPrototypeOf` trap throws turns into a throw inside this\n * constructor — replacing the whole typed refusal with the trap's error.\n */\nexport function unprovenLockStateError(\n driverName: string,\n containment: string,\n cause: unknown\n): ConnectionError {\n return abandonedSessionError(\n driverName,\n ADVISORY_RESET_FAILED,\n containment,\n errorCause(cause)\n );\n}\n\nfunction abandonedSessionError(\n driverName: string,\n reason: string,\n containment: string,\n cause: Error | undefined\n): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" ${reason} ${containment}`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n cause,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * The refusal raised afterwards by EVERY driver whose one client was condemned.\n *\n * A transport that pools connections recovers by reserving a different one, so\n * this is only for the driver whose single client IS the session: there is no\n * other connection to reach for, and running the next migration command on a\n * session that may still hold the lock is precisely what the condemnation\n * exists to prevent. Two drivers over that one client are two callers of this\n * same refusal, because the session they would both pin is the same session.\n */\nexport function condemnedSessionError(driverName: string): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" will pin no further migration session: an earlier session's \"${ADVISORY_RESET}\" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * What was actually DONE about the abandoned connection, in the refusal's own\n * words.\n *\n * Three outcomes, three sentences, each chosen once the outcome is known\n * rather than once the ownership is known. A single sentence written before the\n * close was attempted claimed the backend had been ended even when ending it\n * threw — and the one thing a caller does with that claim is stop looking for a\n * connection that is still running, still holding the lock this refusal exists\n * to report.\n */\nconst CALLER_OWNED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.\";\nconst CLOSED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.\";\nconst CLOSE_FAILED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.\";\n\n/**\n * Returns a reserved PostgreSQL session to its pool, or condemns it — the ONE\n * rule for every provider that reserves a connection it cannot destroy.\n *\n * postgres.js and Bun SQL both expose `release()` and nothing else: there is no\n * destructive return to reach for, so a session whose reset failed is ABANDONED\n * — never released — which is the only way it stops being a connection the pool\n * will hand to the next caller.\n *\n * Abandoning it leaves the lock held until that backend goes away, so a\n * transport VibORM created is closed too: ending it terminates the backend, and\n * PostgreSQL frees every advisory lock the session held. A transport the CALLER\n * supplied is never closed for this — it is theirs, may be serving their own\n * code, and closing it to tidy up VibORM's cleanup failure would be a far\n * larger effect than the one being contained.\n *\n * A LOST session (plan S2) is abandoned the same way without the reset: its\n * connection is gone or stopped answering, and a statement written to it is,\n * on postgres.js, an uncaught crash from inside the provider's write loop. Its\n * owned transport is closed; a supplied one is reported, since abandoning is\n * all VibORM may do with it.\n */\nexport async function releaseReservedPostgresSession(reservation: {\n readonly driverName: string;\n readonly discard: boolean;\n readonly lost?: boolean | undefined;\n /** Runs `SELECT pg_advisory_unlock_all()` on the reserved session. */\n readonly reset: () => Promise<unknown>;\n /** Hands the reserved session back to the provider's pool. */\n readonly release: () => void;\n /** Closes the transport, or absent when the CALLER owns it. */\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n}): Promise<void> {\n if (reservation.lost === true) {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n LOST_SESSION,\n CALLER_OWNED_CONTAINMENT,\n undefined\n );\n }\n // Not awaited: the connection failure the caller holds is already the\n // answer, and the close lets the transport's other queries finish first\n // (postgres.js waits on the dead connection's unsettled query until its\n // bound). The transport is withdrawn before it closes, and a session the\n // close cannot end is ended by the server's idle limit.\n closeOwnedTransport().catch(() => undefined);\n return;\n }\n if (!reservation.discard) {\n reservation.release();\n return;\n }\n\n try {\n await settleWithin(\n reservation.reset(),\n CLEANUP_BOUND_MS,\n () =>\n new Error(\n `The advisory-lock reset went unanswered for ${CLEANUP_BOUND_MS} ms.`\n )\n );\n } catch (resetFailure) {\n await abandon(reservation, ADVISORY_RESET_FAILED, resetFailure);\n }\n reservation.release();\n}\n\n/**\n * Abandons a reserved session: never released, its owned transport closed,\n * and the refusal that says so thrown. A transport the caller supplied is only\n * abandoned.\n */\nasync function abandon(\n reservation: {\n readonly driverName: string;\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n },\n reason: string,\n cause: unknown\n): Promise<void> {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n reason,\n CALLER_OWNED_CONTAINMENT,\n errorCause(cause)\n );\n }\n try {\n await closeOwnedTransport();\n } catch (closeFailure) {\n // The reason stays primary — it is what the caller acts on — and the\n // close's own failure is cleanup evidence beside it.\n throw withSuppressedFailure(\n abandonedSessionError(\n driverName,\n reason,\n CLOSE_FAILED_CONTAINMENT,\n errorCause(cause)\n ),\n closeFailure\n );\n }\n throw abandonedSessionError(\n driverName,\n reason,\n CLOSED_CONTAINMENT,\n errorCause(cause)\n );\n}\n\n/** What VibORM knows about one PHYSICAL session it pins commands on. */\ninterface PhysicalSessionState {\n /**\n * The pinned commands already queued on this session. It never rejects, so\n * one command's failure cannot poison the queue — the next command runs\n * either way, exactly as it would after a success.\n */\n queued: Promise<void>;\n /**\n * Set when a discarded session's advisory-lock reset failed, and never\n * cleared: nothing that happens later can prove a lock was released.\n */\n condemned: boolean;\n}\n\n/**\n * What is known about each PHYSICAL session, keyed on the session itself.\n *\n * A driver's connection queue serializes the commands of THAT driver. Two\n * drivers built over one supplied client — the documented shape for two\n * schema-scoped estates over one PGlite — own two queues and one session, so\n * the queue arbitrates nothing between them, and a PostgreSQL session advisory\n * lock is REENTRANT: the second command re-acquires the lock the first is\n * holding instead of waiting for it, then reads and writes inside the first\n * command's session. The client is the only thing both drivers agree on, so it\n * is what this is keyed on.\n *\n * The condemnation shares that key because it answers for the same subject: a\n * failed reset leaves the CLIENT's lock state unknown, not the wrapper's. Kept\n * on the driver instead, it was a fact the other wrappers over that client\n * never consulted, and their next command ran inside the session it condemned.\n *\n * Weak by construction: the entry dies with the client, and a client nobody\n * holds keeps nothing alive here.\n */\nconst PHYSICAL_SESSIONS = new WeakMap<object, PhysicalSessionState>();\n\n/**\n * Refuses a command on a session whose advisory-lock state was condemned.\n *\n * One refusal, read at two moments, and each covers what the other cannot. At\n * ADMISSION, so a session condemned before this command arrived refuses now\n * rather than behind a queue whose head may itself be waiting on the very lock\n * nobody can account for. At the FRONT of the queue, because condemnation lands\n * BETWEEN the two: the command ahead of this one is the one whose reset fails,\n * and this one was admitted while that session still looked accountable.\n */\nfunction refuseCondemnedSession(\n driverName: string,\n state: PhysicalSessionState\n): void {\n if (state.condemned) {\n throw condemnedSessionError(driverName);\n }\n}\n\n/**\n * Runs `command` exclusively on this physical session, when it may still be\n * pinned at all.\n *\n * The refusal is here rather than beside it because this is the one path every\n * pinned command over a shared session takes, and it lands before `command` —\n * so no body and no statement of the refused command reaches the client.\n */\nexport function leasePinnedCommand<T>(\n driverName: string,\n session: object,\n command: () => Promise<T>\n): Promise<T> {\n const state = physicalSessionState(session);\n refuseCondemnedSession(driverName, state);\n const next = state.queued.then(() => {\n refuseCondemnedSession(driverName, state);\n return command();\n });\n state.queued = next.then(\n () => undefined,\n () => undefined\n );\n return next;\n}\n\n/**\n * Records that this physical session's advisory-lock state can no longer be\n * accounted for — for every driver that reaches it, not only the one whose\n * reset failed.\n */\nexport function condemnPhysicalSession(session: object): void {\n physicalSessionState(session).condemned = true;\n}\n\n/** This session's state, created on first use and mutated in place after. */\nfunction physicalSessionState(session: object): PhysicalSessionState {\n const existing = PHYSICAL_SESSIONS.get(session);\n if (existing) {\n return existing;\n }\n const created: PhysicalSessionState = {\n queued: Promise.resolve(),\n condemned: false,\n };\n PHYSICAL_SESSIONS.set(session, created);\n return created;\n}\n"],"mappings":"iOAMA,MAAM,EAAiB,kCAKjB,EAAwB,kFAAkF,EAAe,iBAWlH,EAAmB,IA4EhC,SAAgB,uBACd,EACA,EACA,EACiB,CACjB,OAAO,sBACL,EACA,EACA,EACA,EAAW,EAAM,CAClB,CAGH,SAAS,sBACP,EACA,EACA,EACA,EACiB,CACjB,OAAO,IAAI,EACT,WAAW,EAAW,IAAI,EAAO,GAAG,IACpC,CACE,KAAM,EAAgB,kBACtB,QACA,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAaH,SAAgB,sBAAsB,EAAqC,CACzE,OAAO,IAAI,EACT,WAAW,EAAW,iEAAiE,EAAe,4NACtG,CACE,KAAM,EAAgB,kBACtB,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAcH,MAAM,EACJ,yLA4BF,eAAsB,+BAA+B,EAUnC,CAChB,GAAI,EAAY,OAAS,GAAM,CAC7B,GAAM,CAAE,sBAAqB,cAAe,EAC5C,GAAI,IAAwB,IAAA,GAC1B,MAAM,sBACJ,EACA,mFACA,EACA,IAAA,GACD,CAOH,GAAqB,CAAC,UAAY,IAAA,GAAU,CAC5C,OAEF,GAAI,CAAC,EAAY,QAAS,CACxB,EAAY,SAAS,CACrB,OAGF,GAAI,CACF,MAAM,EACJ,EAAY,OAAO,CACnB,MAEM,MACF,+CAA+C,EAAiB,MACjE,CACJ,OACM,EAAc,CACrB,MAAM,QAAQ,EAAa,EAAuB,EAAa,CAEjE,EAAY,SAAS,CAQvB,eAAe,QACb,EAIA,EACA,EACe,CACf,GAAM,CAAE,sBAAqB,cAAe,EAC5C,GAAI,IAAwB,IAAA,GAC1B,MAAM,sBACJ,EACA,EACA,EACA,EAAW,EAAM,CAClB,CAEH,GAAI,CACF,MAAM,GAAqB,OACpB,EAAc,CAGrB,MAAM,EACJ,sBACE,EACA,EACA,8RACA,EAAW,EAAM,CAClB,CACD,EACD,CAEH,MAAM,sBACJ,EACA,EACA,iMACA,EAAW,EAAM,CAClB,CAsCH,MAAM,EAAoB,IAAI,QAY9B,SAAS,uBACP,EACA,EACM,CACN,GAAI,EAAM,UACR,MAAM,sBAAsB,EAAW,CAY3C,SAAgB,mBACd,EACA,EACA,EACY,CACZ,IAAM,EAAQ,qBAAqB,EAAQ,CAC3C,uBAAuB,EAAY,EAAM,CACzC,IAAM,EAAO,EAAM,OAAO,UACxB,uBAAuB,EAAY,EAAM,CAClC,GAAS,EAChB,CAKF,MAJA,GAAM,OAAS,EAAK,SACZ,IAAA,OACA,IAAA,GACP,CACM,EAQT,SAAgB,uBAAuB,EAAuB,CAC5D,qBAAqB,EAAQ,CAAC,UAAY,GAI5C,SAAS,qBAAqB,EAAuC,CACnE,IAAM,EAAW,EAAkB,IAAI,EAAQ,CAC/C,GAAI,EACF,OAAO,EAET,IAAM,EAAgC,CACpC,OAAQ,QAAQ,SAAS,CACzB,UAAW,GACZ,CAED,OADA,EAAkB,IAAI,EAAS,EAAQ,CAChC"}
|
package/dist/planetscale.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as Schema,
|
|
1
|
+
import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-VsM29vYN.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{o as t}from"./value-guards-CK9guf2Z.mjs";import{c as n,s as r}from"./bind-parameter-capacity-
|
|
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-qfEejeOX.mjs";import{l as i,p as a}from"./error-mapping-C9WgitPi.mjs";import{p as o}from"./validation-BamBwne9.mjs";import{s}from"./execution-context-rJXTRVrJ.mjs";import{n as c}from"./client-_WKrPNmm.mjs";import{a as l,c as u,d,o as f,t as p}from"./driver-B9fIori_.mjs";import{t as m}from"./sql-statement-tokens-CFi1y3bK.mjs";import{t as h}from"./mysql-adapter-C6c5govr.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
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Ki as DecimalDescriptor, Un as AnyModel, l as AnyDriver, mn as DateTimePhysicalForm } from "./index-VsM29vYN.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/migrations/limits.d.ts
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,n}from"./base-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,n}from"./base-D3m1S7Uc.mjs";import{t as r}from"./migrations-Bn1SatyB.mjs";import{Ct as i,_ as a,j as o,m as s}from"./geo-point-codec-DyEHMdJg.mjs";import{s as c}from"./scalar-S8yMvdmx.mjs";import{o as l}from"./native-types-asNCr26n.mjs";import{a as u,r as d}from"./physical-CAOaNM4R.mjs";import{a as f}from"./datetime-physical-codec-BEqQbIP_.mjs";import{B as p,J as m,M as h,O as g,P as _,b as v,g as y,m as b,ut as x,v as S,x as C,y as w,z as T}from"./client-DM1UHfYG.mjs";import{n as ee,t as E}from"./array-literal-BKdLfNzM.mjs";import{a as D,n as O}from"./identity-oQvIe7u8.mjs";import{P as te}from"./standard-sql-CoGqv-iX.mjs";import{a as k,i as A,n as ne,o as j,r as ie}from"./identifier-conversion-DaZ9yNpv.mjs";const M=/;\s*$/,N=/-/g;function quoteIdentifier(e){return`"${e.replace(/"/g,`""`)}"`}function quoteLiteral(e){return`'${e.replace(/'/g,`''`)}'`}async function canonicalizeIndexPredicates(e,t,n,r,i){if(n.length===0)return[];let a=i??(async e=>{let t=[];for(let n of e)t.push(await r(n));return t}),deparse=async t=>{let n=[...t.keys()].filter(e=>t[e]!==void 0);if(n.length===0)return t.map(()=>void 0);let r=`viborm_index_predicate_${crypto.randomUUID().replace(N,``)}_`,i=n.map(e=>`${r}${e}`),o=i.map(t=>`${quoteIdentifier(e)}.${quoteIdentifier(t)}`),s=await a([...n.map((e,n)=>`CREATE VIEW ${o[n]} AS ${t[e]}`),`SELECT c.relname AS name, pg_catalog.pg_get_viewdef(c.oid) AS definition FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ${quoteLiteral(e)} AND c.relname IN (${i.map(quoteLiteral).join(`, `)})`,`DROP VIEW ${o.join(`, `)}`]),c=new Map(s[n.length]?.rows.map(e=>[e.name,e.definition]));return t.map((e,t)=>e===void 0?void 0:c.get(`${r}${t}`)??void 0)};return deparse((await deparse(n.map(e=>`SELECT 1 AS c FROM ${t} WHERE ${e}`))).map(e=>e?.replace(M,``)))}const P=/::(?:"(?:[^"]|"")+"|[a-zA-Z_][\w$]*)(?:\.(?:"(?:[^"]|"")+"|[a-zA-Z_][\w$]*))?(?:\s+(?:varying|precision|with time zone|without time zone))?(?:\(\d+(?:,\s*\d+)?\))?(?:\[\])?$/,F=new Set([`pg_catalog`,`information_schema`]),I={supportsVector:[`vector`,`halfvec`,`sparsevec`],geoPoint:[`geometry`,`geography`]};function admittedExtensionTypes(e){let t=e?.adapter;return new Set([...t?.capabilities.supportsVector?I.supportsVector:[],...t?.geoPoint?I.geoPoint:[]])}const L=`
|
|
2
2
|
SELECT tables.table_name, tables.table_name AS name, relation.relkind AS relation_kind, relation.relispartition AS is_partition
|
|
3
3
|
FROM information_schema.tables tables
|
|
4
4
|
JOIN pg_catalog.pg_class relation
|
|
@@ -190,7 +190,7 @@ JOIN pg_enum e ON t.oid = e.enumtypid
|
|
|
190
190
|
JOIN pg_namespace n ON n.oid = t.typnamespace
|
|
191
191
|
WHERE n.nspname = $1
|
|
192
192
|
`,oe=`${J}ORDER BY t.typname, e.enumsortorder;
|
|
193
|
-
`;function baseTypeName(e){return e.startsWith(`_`)?e.slice(1):e}function stripExtensionSchema(e,t){for(let n of[`${t}.`,`"${t.replaceAll(`"`,`""`)}".`])if(e.startsWith(n))return e.slice(n.length);return e}function refuseUnrepresentableType(e,t){throw new r(`Column "${e.table_name}"."${e.column_name}" has type "${e.udt_schema}"."${baseTypeName(e.udt_name)}", which lives in another schema and no installed extension owns it. VibORM manages one schema ("${t.namespace}") and cannot represent that type in a snapshot or regenerate it as DDL.`,n.FEATURE_NOT_SUPPORTED,{meta:{table:e.table_name,column:e.column_name,type:baseTypeName(e.udt_name),feature:`external-type`}})}function formatColumnType(e,t){let i=baseTypeName(e.udt_name);if(e.type_extension===`postgis`&&(i===`geometry`||i===`geography`)&&!t.admittedExtensionTypes.has(i))throw new r(`Column "${e.table_name}"."${e.column_name}" uses PostGIS ${i}, but this PostgreSQL adapter has no GeoPoint protocol. Migration introspection refuses to erase its subtype and SRID into a bare extension type; construct the driver with \`postgis: true\` or use a client that does not manage this estate.`,n.DRIVER_NOT_SUPPORTED,{meta:{dialect:`postgresql`,table:e.table_name,column:e.column_name,type:i,feature:`GeoPoint`}});if(e.type_extension!==null&&e.type_extension_schema!==null&&t.admittedExtensionTypes.has(i))return stripExtensionSchema(e.formatted_type,e.type_extension_schema);e.type_extension===null&&e.udt_schema!==t.namespace&&!F.has(e.udt_schema)&&refuseUnrepresentableType(e,t);let a=baseTypeName(e.udt_name),o=e.udt_name.startsWith(`_`)?`${a}[]`:a;return F.has(e.udt_schema)?e.formatted_type:o}function readDecimalDomain(e){if(e.data_type===`numeric`&&e.numeric_precision!==null)return requireDecimalDomain(e,e.numeric_precision,e.numeric_scale??0);if(e.udt_name!==`_numeric`)return;let t=se.exec(e.formatted_type);if(t)return requireDecimalDomain(e,t[1],t[2])}const se=/^numeric\((-?\d+),(-?\d+)\)\[\]$/;function requireDecimalDomain(e,t,i){let o
|
|
193
|
+
`;function baseTypeName(e){return e.startsWith(`_`)?e.slice(1):e}function stripExtensionSchema(e,t){for(let n of[`${t}.`,`"${t.replaceAll(`"`,`""`)}".`])if(e.startsWith(n))return e.slice(n.length);return e}function refuseUnrepresentableType(e,t){throw new r(`Column "${e.table_name}"."${e.column_name}" has type "${e.udt_schema}"."${baseTypeName(e.udt_name)}", which lives in another schema and no installed extension owns it. VibORM manages one schema ("${t.namespace}") and cannot represent that type in a snapshot or regenerate it as DDL.`,n.FEATURE_NOT_SUPPORTED,{meta:{table:e.table_name,column:e.column_name,type:baseTypeName(e.udt_name),feature:`external-type`}})}function formatColumnType(e,t){let i=baseTypeName(e.udt_name);if(e.type_extension===`postgis`&&(i===`geometry`||i===`geography`)&&!t.admittedExtensionTypes.has(i))throw new r(`Column "${e.table_name}"."${e.column_name}" uses PostGIS ${i}, but this PostgreSQL adapter has no GeoPoint protocol. Migration introspection refuses to erase its subtype and SRID into a bare extension type; construct the driver with \`postgis: true\` or use a client that does not manage this estate.`,n.DRIVER_NOT_SUPPORTED,{meta:{dialect:`postgresql`,table:e.table_name,column:e.column_name,type:i,feature:`GeoPoint`}});if(e.type_extension!==null&&e.type_extension_schema!==null&&t.admittedExtensionTypes.has(i))return stripExtensionSchema(e.formatted_type,e.type_extension_schema);e.type_extension===null&&e.udt_schema!==t.namespace&&!F.has(e.udt_schema)&&refuseUnrepresentableType(e,t);let a=baseTypeName(e.udt_name),o=e.udt_name.startsWith(`_`)?`${a}[]`:a;return F.has(e.udt_schema)?e.formatted_type:o}function readDecimalDomain(e){if(e.data_type===`numeric`&&e.numeric_precision!==null)return requireDecimalDomain(e,e.numeric_precision,e.numeric_scale??0);if(e.udt_name!==`_numeric`)return;let t=se.exec(e.formatted_type);if(t)return requireDecimalDomain(e,t[1],t[2])}const se=/^numeric\((-?\d+),(-?\d+)\)\[\]$/;function requireDecimalDomain(e,t,i){let a=o(t,i,`pg`);if(a!==void 0)return a;throw new r(`PostgreSQL reported column "${e.table_name}"."${e.column_name}" as NUMERIC(${String(t)},${String(i)}), outside VibORM's fixed-decimal domain. Migration introspection is refused rather than publishing an invalid descriptor.`,n.MIGRATION_INVALID_STATE,{meta:{dialect:`postgresql`,table:e.table_name,column:e.column_name,type:`invalid-catalog-decimal-domain`}})}function isAutoIncrement(e){return e?e.includes(`nextval(`)||e.includes(`_seq'::regclass)`):!1}function terminalCastSpellings(t,n){let r=e(e=>`"${e.replaceAll(`"`,`""`)}"`,`quoted`),i=[``,`${t}.`,`${r(t)}.`],a=[n,r(n)],o=[];for(let e of i)for(let t of a)for(let n of[``,`[]`])o.push(`::${e}${t}${n}`);return o.sort((e,t)=>t.length-e.length)}function stripManagedEnumCast(e,t,n,r){let i=baseTypeName(t.udt_name);if(t.udt_schema!==n.namespace||!r.has(i))return e;for(let n of terminalCastSpellings(t.udt_schema,i))if(e.endsWith(n))return e.slice(0,-n.length);return e}function cleanDefault(e,t,n){let r=e.column_default;if(r&&!isAutoIncrement(r))return renderDecimalDefault(stripManagedEnumCast(r,e,t,n).replace(P,``).trim(),readDecimalDomain(e))}function renderDecimalDefault(e,t){if(t===void 0)return e;let n=s(e.startsWith(`'`)&&e.endsWith(`'`)&&e.length>1?e.slice(1,-1):e);return n===void 0?e:a(`pg`,n,t)}function assertNoCrossSchemaForeignKeys(e,t){let i=e.find(e=>t.tables===void 0||e.owning_schema===t.namespace&&t.tables.includes(e.owning_table)||e.referenced_schema===t.namespace&&t.tables.includes(e.referenced_table));if(!i)return;let a=i.owning_schema===t.namespace?`out of`:`into`;throw new r(`Foreign key "${i.constraint_name}" points ${a} the migration estate: "${i.owning_schema}"."${i.owning_table}" references "${i.referenced_schema}"."${i.referenced_table}". VibORM manages one schema ("${t.namespace}") per estate, so a constraint with one side outside it is an unsupported migration topology`+(e.length>1?` (${e.length} such constraints).`:`.`),n.FEATURE_NOT_SUPPORTED,{meta:{constraint:i.constraint_name,table:i.owning_table,relation:i.referenced_table,feature:`cross-schema-foreign-key`}})}async function introspectPostgresSchema(e,t){let i=[t.namespace],read=async(t,n,r=i)=>{try{return await e(n,r)}catch(e){throw y(t,e),e}},a=await read(`tables`,R),o=await read(`columns`,ae),s=await read(`primary keys`,V),c=await read(`indexes`,`${indexesSource((await read(`nulls not distinct`,`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_attribute WHERE attrelid = 'pg_catalog.pg_index'::pg_catalog.regclass AND attname = 'indnullsnotdistinct' AND NOT attisdropped) AS present`,[])).rows[0]?.present===!0?`ix.indnullsnotdistinct`:`false`)}ORDER BY t.relname, i.relname, array_position(ix.indkey, a.attnum);
|
|
194
194
|
`),l=await read(`foreign keys`,U),u=await read(`cross-schema foreign keys`,G),d=await read(`unique constraints`,q),f=await read(`enums`,oe);assertNoCrossSchemaForeignKeys(u.rows,t);let p=A(o.rows,e=>e.table_name),m=A(s.rows,e=>e.table_name),h=k(c.rows,e=>e.table_name,e=>e.index_name),g=k(l.rows,e=>e.table_name,e=>e.constraint_name),_=k(d.rows,e=>e.table_name,e=>e.constraint_name),v=A(f.rows,e=>e.enum_name),b=new Set(v.keys()),x=[];for(let e of a.rows){let i=e.table_name,a=t.tables===void 0||t.tables.includes(i);if(a&&(e.relation_kind===`p`||e.is_partition===!0))throw new r(`PostgreSQL table "${i}" is partitioned or a partition. Synchronization refuses before effects because its physical definition cannot be represented.`,n.MIGRATION_INVALID_STATE,{meta:{table:i,feature:`partitioned table`}});let o=(p.get(i)??[]).find(e=>e.generated_kind!==void 0&&e.generated_kind!==``);if(a&&o)throw new r(`PostgreSQL column "${i}.${o.column_name}" is generated. Synchronization refuses before effects because its expression cannot be represented.`,n.MIGRATION_INVALID_STATE,{meta:{table:i,column:o.column_name,feature:`generated column`}});let s=(p.get(i)||[]).map(e=>({name:e.column_name,type:t.tables!==void 0&&!t.tables.includes(i)?e.udt_name.startsWith(`_`)?`${baseTypeName(e.udt_name)}[]`:e.udt_name:formatColumnType(e,t),nullable:e.is_nullable===`YES`,default:t.tables!==void 0&&!t.tables.includes(i)?void 0:cleanDefault(e,t,b),autoIncrement:isAutoIncrement(e.column_default),decimal:t.tables!==void 0&&!t.tables.includes(i)?void 0:readDecimalDomain(e)})),c,l=m.get(i);if(l&&l.length>0){l.sort((e,t)=>e.ordinal_position-t.ordinal_position);let e=l[0];e&&(c={columns:l.map(e=>e.column_name),name:e.constraint_name})}let u=[],d=h.get(i);if(d)for(let[e,a]of d){a.sort((e,t)=>e.ordinal_position-t.ordinal_position);let o=a[0];if(o){let s=o.index_type,c=t.tables===void 0||t.tables.includes(i);if(c&&o.is_valid===!1)throw new r(`PostgreSQL index "${i}.${e}" is INVALID: a CREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY build of it was interrupted or is still running, and PostgreSQL never reads through it. status() lists it; resolve() repairs it when the unfinished migration attempt's own CONCURRENTLY statement named it, otherwise drop it with DROP INDEX CONCURRENTLY or rebuild it with REINDEX INDEX CONCURRENTLY.`,n.MIGRATION_INVALID_INDEX,{meta:{table:i,indexName:e}});if(c&&(o.unsupported_structure!==!1||s!==`btree`&&s!==`hash`&&s!==`gin`&&s!==`gist`))throw new r(`PostgreSQL index "${i}.${e}" has physical method/order/expression/include/opclass/collation semantics that this index declaration cannot represent. Synchronization refuses before effects and preserves the index. Manage its table outside this synchronization scope until a faithful declaration is available.`,n.FEATURE_NOT_SUPPORTED,{meta:{table:i,indexName:e}});if(s!==`btree`&&s!==`hash`&&s!==`gin`&&s!==`gist`||a.some(e=>e.column_name===null))continue;u.push({name:e,columns:a.flatMap(e=>e.column_name===null?[]:[e.column_name]),unique:o.is_unique,type:s,where:o.filter_condition||void 0})}}let f=[],v=g.get(i);if(v)for(let[e,t]of v){t.sort((e,t)=>e.ordinal_position-t.ordinal_position);let n=t[0];n&&f.push({name:e,columns:t.map(e=>e.column_name),referencedTable:n.foreign_table_name,referencedColumns:t.map(e=>e.foreign_column_name),onDelete:j(n.delete_rule),onUpdate:j(n.update_rule)})}let y=[],S=_.get(i);if(S)for(let[e,t]of S)t.sort((e,t)=>e.ordinal_position-t.ordinal_position),y.push({name:e,columns:t.map(e=>e.column_name)});x.push({name:i,columns:s,primaryKey:c,indexes:u,foreignKeys:f,uniqueConstraints:y})}let S=[];for(let[e,t]of v)t.sort((e,t)=>e.sort_order-t.sort_order),S.push({name:e,values:t.map(e=>e.enum_value)});return{tables:x,enums:S.length>0?S:void 0}}const re=e=>`E'${e.replaceAll(`\\`,`\\\\`).replaceAll(`'`,`''`)}'`,Y=`[\\t\\n\\v\\f\\r \xA0 - \u2028\u2029 ]`,trim=e=>`regexp_replace(${e}, ${re(`^${Y}+|${Y}+$`)}, '', 'g')`,ce=[[`${Y}+`,` `],[`${Y}*,${Y}*`,`,`],[String.raw`${Y}+\[\]`,`[]`],[String.raw`\ycharacter varying\y`,`varchar`],[String.raw`\ycharacter\y`,`char`],[String.raw`\ybit varying\y`,`varbit`],[String.raw`\ytimestamptz(\([0-9]+\))?`,String.raw`timestamp\1 with time zone`],[String.raw`\ytimetz(\([0-9]+\))?`,String.raw`time\1 with time zone`],[String.raw`\y(timestamp|time)(\([0-9]+\))? without time zone`,String.raw`\1\2`],[String.raw`\yint4\y`,`integer`],[String.raw`\yint8\y`,`bigint`],[String.raw`\yint2\y`,`smallint`],[String.raw`\yfloat4\y`,`real`],[String.raw`\yfloat8\y`,`double precision`],[String.raw`\ybool\y`,`boolean`]],normalizeType=e=>ce.reduce((e,[t,n])=>`regexp_replace(${e}, ${re(t)}, ${re(n)}, 'g')`,`lower(${trim(e)} COLLATE "C")`),X=`(?:"(?:[^"]|"")+"|[a-zA-Z_][a-zA-Z0-9_$]*)`,le=String.raw`::${X}(?:\.${X})?(?:${Y}+(?:varying|precision|with time zone|without time zone))?(?:\([0-9]+(?:,${Y}*[0-9]+)?\))?(?:\[\])?$`,ue=String.raw`^(?:now\(\) at time zone 'utc'|timezone\(${Y}*'utc'${Y}*,${Y}*now\(\)${Y}*\))$`,de=String.raw`^timezone\(${Y}*'utc'${Y}*,${Y}*current_time(?:\(3\))?${Y}*\)$`,fe=String.raw`^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:e[+-]?[0-9]+)?$`,quoted=e=>`(left(${e}, 1) = '''' AND right(${e}, 1) = '''')`,inner=e=>`CASE WHEN length(${e}) >= 2 THEN substr(${e}, 2, length(${e}) - 2) ELSE '' END`;function stripParentheses(e){let t=`regexp_replace(${inner(`regexp_replace(${e}, ${re(`'(?:[^']|'')*'|"(?:[^"]|"")*"`)}, 'q', 'g')`)}, '[^()]', '', 'g')`;for(let e=0;e<8;e+=1)t=`replace(${t}, '()', '')`;return`(SELECT CASE WHEN ${e} IS NULL OR NOT (left(${e}, 1) = '(' AND right(${e}, 1) = ')') THEN ${e} WHEN reduced = '' THEN ${trim(inner(e))} WHEN reduced ~ ${re(String.raw`^\)*\(*$`)} THEN ${e} END FROM (SELECT ${t} AS reduced OFFSET 0) parentheses)`}const pe=`(SELECT CASE
|
|
195
195
|
WHEN digits IS NULL THEN NULL
|
|
196
196
|
WHEN whole = '' AND fraction = '' THEN '0'
|
|
@@ -399,7 +399,7 @@ SELECT (
|
|
|
399
399
|
)
|
|
400
400
|
)
|
|
401
401
|
) AS ready
|
|
402
|
-
`)).rows}catch(e){throw new r(`PostGIS GeoPoint preflight could not prove the required extension, types, and functions before migration effects.`,n.MIGRATION_INVALID_STATE,{cause:t(e),meta:{dialect:this.dialect,feature:`GeoPoint`,...S(e)}})}if(y.length!==1||y[0]?.ready!==!0)throw new r(`PostGIS GeoPoint preflight did not prove the required extension, visible types, and exact function signatures. VibORM never installs PostGIS.`,n.MIGRATION_INVALID_STATE,{meta:{dialect:this.dialect,feature:`GeoPoint`}});return u}catch(e){throw e instanceof r?e:new r(`PostgreSQL schema preflight could not prove the required catalog facts before migration effects.`,n.MIGRATION_INVALID_STATE,{cause:t(e),meta:{dialect:this.dialect,feature:`schema catalog`,...S(e)}})}}async proveNamespaceExists(e){let t=this.requireEstateNamespace(),{rows:i}=await e(`SELECT 1 AS present FROM pg_catalog.pg_namespace WHERE nspname = $1`,[t]);if(i.length===0)throw new r(`The configured PostgreSQL schema "${t}" does not exist. VibORM never creates or drops a schema: create it (or fix the configured \`namespace\`) before running migrations.`,n.MIGRATION_INVALID_STATE,{meta:{dialect:this.dialect,driver:this.driverName,namespace:t}})}canonicalizeIndexPredicates(e,t,n,r){return canonicalizeIndexPredicates(this.requireEstateNamespace(),this.qualify(e),t,n,r)}mapScalarType(e,t,n){let r=e[`~`].nativeType,i=n===void 0?void 0:
|
|
402
|
+
`)).rows}catch(e){throw new r(`PostGIS GeoPoint preflight could not prove the required extension, types, and functions before migration effects.`,n.MIGRATION_INVALID_STATE,{cause:t(e),meta:{dialect:this.dialect,feature:`GeoPoint`,...S(e)}})}if(y.length!==1||y[0]?.ready!==!0)throw new r(`PostGIS GeoPoint preflight did not prove the required extension, visible types, and exact function signatures. VibORM never installs PostGIS.`,n.MIGRATION_INVALID_STATE,{meta:{dialect:this.dialect,feature:`GeoPoint`}});return u}catch(e){throw e instanceof r?e:new r(`PostgreSQL schema preflight could not prove the required catalog facts before migration effects.`,n.MIGRATION_INVALID_STATE,{cause:t(e),meta:{dialect:this.dialect,feature:`schema catalog`,...S(e)}})}}async proveNamespaceExists(e){let t=this.requireEstateNamespace(),{rows:i}=await e(`SELECT 1 AS present FROM pg_catalog.pg_namespace WHERE nspname = $1`,[t]);if(i.length===0)throw new r(`The configured PostgreSQL schema "${t}" does not exist. VibORM never creates or drops a schema: create it (or fix the configured \`namespace\`) before running migrations.`,n.MIGRATION_INVALID_STATE,{meta:{dialect:this.dialect,driver:this.driverName,namespace:t}})}canonicalizeIndexPredicates(e,t,n,r){return canonicalizeIndexPredicates(this.requireEstateNamespace(),this.qualify(e),t,n,r)}mapScalarType(e,t,n){let r=e[`~`].nativeType,i=n===void 0?void 0:u(n,r,`pg`);if(i)return i.columnType;let a=l(r,`pg`);return a?t.array?`${a.type}[]`:a.type:_({type:t.type,array:t.array,withTimezone:t.withTimezone,dimension:t.dimension,decimal:t.decimal})}finalizeTable(e){return{...e,...e.primaryKey?.name?{primaryKey:{...e.primaryKey,name:g(e.primaryKey.name)}}:{},uniqueConstraints:e.uniqueConstraints.map(e=>({...e,name:g(e.name)})),foreignKeys:e.foreignKeys.map(e=>({...e,name:g(e.name)})),indexes:e.indexes.map(e=>({...e,name:g(e.name),...e.type===`spatial`?{type:`gist`}:{}}))}}getDefaultExpression(e,t){let n=t.hasDefault&&!t.autoGenerate&&!t.decimal&&(t.array||t.type===`datetime`||t.type===`date`)?this.literalDefaultValue(t):void 0;if(t.hasDefault&&!t.autoGenerate&&t.array&&Array.isArray(n)){if(t.decimal)return super.getDefaultExpression(e,t);let r=n.map(e=>(t.type===`datetime`||t.type===`date`)&&typeof e==`string`?f(e):e);return this.escapeValue(E(r))}if(t.hasDefault&&t.default===null)return;if(t.type===`datetime`&&t.autoGenerate?.kind===`now`){let n=this.mapScalarType(e,t).toLowerCase(),r=n.includes(`timestamptz`)||n.includes(`with time zone`)?`CURRENT_TIMESTAMP`:`(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')`;return Number(Z.exec(n)?.[1]??6)>3?`date_trunc('milliseconds', ${r})`:r}if((t.type===`datetime`||t.type===`date`)&&t.autoGenerate===void 0&&t.hasDefault&&typeof n==`string`)return this.escapeValue(f(n));if(t.autoGenerate?.kind===`now`){if(t.type===`date`)return`(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')`;if(t.type===`time`){let n=this.mapScalarType(e,t).toLowerCase();return Number(Z.exec(n)?.[1]??6)>3?`timezone('UTC', CURRENT_TIME(3))`:n.includes(`timetz`)||n.includes(`with time zone`)?`timezone('UTC', CURRENT_TIME)`:`(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')`}}let r=d(t);if(!(r!==void 0&&u(r,e[`~`].nativeType,`pg`)?.representation===`bytes`)&&!(t.autoGenerate?.kind===`uuid`&&!c(t.default)))return super.getDefaultExpression(e,t)}getAutoGenerateExpression(e){switch(e?.kind){case`uuid`:return i(e.prefix)?void 0:`gen_random_uuid()`;case`now`:return`NOW()`;default:return}}getEnumColumnType(e,t,n){return g(`${e}_${t}_enum`)}static SERIAL_TYPE_MAP={integer:`SERIAL`,int4:`SERIAL`,int:`SERIAL`,bigint:`BIGSERIAL`,int8:`BIGSERIAL`,smallint:`SMALLSERIAL`,int2:`SMALLSERIAL`};formatColumnType(e,t){if(e.autoIncrement){let t=e.type.toLowerCase(),i=PostgresMigrationDriver.SERIAL_TYPE_MAP[t];if(!i)throw new r(`PostgreSQL auto-increment (SERIAL) requires an integer type (INTEGER, BIGINT, SMALLINT). Column "${e.name}" has type "${e.type}" which is not compatible with auto-increment.`,n.INVALID_INPUT,{meta:{column:e.name,type:e.type,autoIncrement:!0}});return i}return this.renderTypeToken(e.type,t)}generateCreateTable(e,t){let{table:n}=e,r=n.columns.map(e=>this.generateColumnDef(e,t));if(n.primaryKey){let e=n.primaryKey.columns.map(e=>this.escapeIdentifier(e)).join(`, `),t=`CONSTRAINT ${this.escapeIdentifier(this.generatedPrimaryKeyName(n.name,n.primaryKey.name))} `;r.push(`${t}PRIMARY KEY (${e})`)}for(let e of n.uniqueConstraints){let t=e.columns.map(e=>this.escapeIdentifier(e)).join(`, `);r.push(`CONSTRAINT ${this.escapeIdentifier(e.name)} UNIQUE (${t})`)}let i=[`CREATE TABLE ${this.qualify(n.name)} (\n ${r.join(`,
|
|
403
403
|
`)}\n)`];for(let e of n.indexes)i.push(this.generateCreateIndex({type:`createIndex`,tableName:n.name,index:e},t));for(let e of n.foreignKeys)i.push(this.generateAddForeignKey({type:`addForeignKey`,tableName:n.name,fk:e},t));return i}generateDropTable(e,t){return`DROP TABLE ${this.qualify(e.tableName)}`}generateRenameTable(e,t){return`ALTER TABLE ${this.qualify(e.from)} RENAME TO ${this.escapeIdentifier(e.to)}`}renameDerivedNames(e,t){return[...t].map(([t,{kind:n,to:r}])=>n===`constraint`?`ALTER TABLE ${this.qualify(e)} RENAME CONSTRAINT ${this.escapeIdentifier(t)} TO ${this.escapeIdentifier(r)}`:`ALTER ${n===`type`?`TYPE`:`INDEX`} ${this.qualify(t)} RENAME TO ${this.escapeIdentifier(r)}`)}generatedPrimaryKeyName(e,t){return t||g(`${e}_pkey`)}generateAddColumn(e,t){let n=this.generateColumnDef(e.column,t);return`ALTER TABLE ${this.qualify(e.tableName)} ADD COLUMN ${n}`}generateDropColumn(e,t){return`ALTER TABLE ${this.qualify(e.tableName)} DROP COLUMN ${this.escapeIdentifier(e.columnName)}`}generateRenameColumn(e,t){return`ALTER TABLE ${this.qualify(e.tableName)} RENAME COLUMN ${this.escapeIdentifier(e.from)} TO ${this.escapeIdentifier(e.to)}`}generateAlterColumn(e,t){let{tableName:n,columnName:r,from:i,to:a}=e,o=[],s=this.qualify(n),c=this.escapeIdentifier(r),l=p(i,a);if(l&&a.decimal){let e=this.renderTypeToken(a.type,t),n=this.escapeIdentifier(T(e.endsWith(`[]`)?`list`:`scalar`,a.decimal));o.push(`LOCK TABLE ${s} IN ACCESS EXCLUSIVE MODE`),o.push(`ALTER TABLE ${s} ADD CONSTRAINT ${n} CHECK (${m(c,e)})`)}if(i.type!==a.type){i.default!==void 0&&o.push(`ALTER TABLE ${s} ALTER COLUMN ${c} DROP DEFAULT`);let e=this.renderTypeToken(a.type,t);ne(i.type,e)&&o.push(ie(s,c));let n=i.type.endsWith(`[]`)?i.type.slice(0,-2):i.type,r=this.managedEnumNames(t).has(n)?`::text${i.type.endsWith(`[]`)?`[]`:``}`:``;o.push(`ALTER TABLE ${s} ALTER COLUMN ${c} TYPE ${e} USING ${c}${r}::${e}`)}if(i.nullable!==a.nullable&&(a.nullable?o.push(`ALTER TABLE ${s} ALTER COLUMN ${c} DROP NOT NULL`):o.push(`ALTER TABLE ${s} ALTER COLUMN ${c} SET NOT NULL`)),(i.default!==a.default||i.type!==a.type&&i.default!==void 0)&&(a.default===void 0?o.push(`ALTER TABLE ${s} ALTER COLUMN ${c} DROP DEFAULT`):o.push(`ALTER TABLE ${s} ALTER COLUMN ${c} SET DEFAULT ${a.default}`)),l&&a.decimal){let e=this.renderTypeToken(a.type,t);o.push(`ALTER TABLE ${s} DROP CONSTRAINT ${this.escapeIdentifier(T(e.endsWith(`[]`)?`list`:`scalar`,a.decimal))}`)}return o}generateCreateIndex(e,t){let{tableName:n,index:r}=e,i=r.type===`spatial`?`gist`:r.type;this.validateIndexType(i,r.name);let a=r.unique?`UNIQUE `:``,o=i?`USING ${i} `:``,s=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `),c=r.where?` WHERE ${r.where}`:``;return`CREATE ${a}INDEX${t.lowLock===`add`?` CONCURRENTLY`:``} ${this.escapeIdentifier(r.name)} ON ${this.qualify(n)} ${o}(${s})${c}`}generateDropIndex(e,t){return`DROP INDEX ${this.qualify(e.indexName)}`}generateAddForeignKey(e,t){let{tableName:n,fk:r}=e;if(t.lowLock===`validate`)return`ALTER TABLE ${this.qualify(n)} VALIDATE CONSTRAINT ${this.escapeIdentifier(r.name)}`;let i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `),a=r.referencedColumns.map(e=>this.escapeIdentifier(e)).join(`, `),o=r.onDelete?` ON DELETE ${this.formatReferentialAction(r.onDelete)}`:``,s=r.onUpdate?` ON UPDATE ${this.formatReferentialAction(r.onUpdate)}`:``,c=t.lowLock===`add`?` NOT VALID`:``;return`ALTER TABLE ${this.qualify(n)} ADD CONSTRAINT ${this.escapeIdentifier(r.name)} FOREIGN KEY (${i}) REFERENCES ${this.qualify(r.referencedTable)} (${a})${o}${s}${c}`}generateDropForeignKey(e,t){return`ALTER TABLE ${this.qualify(e.tableName)} DROP CONSTRAINT ${this.escapeIdentifier(e.fkName)}`}generateAddUniqueConstraint(e,t){let{tableName:n,constraint:r}=e,i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `);return`ALTER TABLE ${this.qualify(n)} ADD CONSTRAINT ${this.escapeIdentifier(r.name)} UNIQUE (${i})`}generateDropUniqueConstraint(e,t){return`ALTER TABLE ${this.qualify(e.tableName)} DROP CONSTRAINT ${this.escapeIdentifier(e.constraintName)}`}generateAddPrimaryKey(e,t){let{tableName:n,primaryKey:r}=e,i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `),a=this.escapeIdentifier(this.generatedPrimaryKeyName(n,r.name));return`ALTER TABLE ${this.qualify(n)} ADD CONSTRAINT ${a} PRIMARY KEY (${i})`}generateDropPrimaryKey(e,t){return`ALTER TABLE ${this.qualify(e.tableName)} DROP CONSTRAINT ${this.escapeIdentifier(e.constraintName)}`}generateCreateEnum(e,t){let{enumDef:n}=e,r=n.values.map(e=>this.escapeValue(e)).join(`, `);return`CREATE TYPE ${this.qualify(n.name)} AS ENUM (${r})`}generateDropEnum(e,t){return`DROP TYPE ${this.qualify(e.enumName)}`}generateAcquireLock(e){let{lockWait:t}=this.limits??x;return`WITH RECURSIVE lock_attempt AS (
|
|
404
404
|
SELECT pg_try_advisory_xact_lock(${e}) AS acquired, clock_timestamp() + interval '${t/1e3} seconds' AS deadline
|
|
405
405
|
UNION ALL
|
|
@@ -412,4 +412,4 @@ SELECT (
|
|
|
412
412
|
JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
|
|
413
413
|
WHERE t.typtype = 'e' AND n.nspname = $1
|
|
414
414
|
ORDER BY t.typname`,params:[this.requireEstateNamespace()]}}generateDropEnumSQL(e){return`DROP TYPE IF EXISTS ${this.qualify(e)}`}generateAlterEnum(e,t){let i={...t,currentSchema:this.schemaAtOperation(t)},{enumName:a,addValues:o=[],removeValues:s,newValues:c,dependentColumns:l}=e,u=[],d=this.qualify(a),f=i.currentSchema?.enums?.find(e=>e.name===a)?.values??[],p=c!==void 0&&f.filter(e=>c.includes(e)).join(`\0`)!==c.filter(e=>f.includes(e)).join(`\0`),m=readsAddedValue(a,o,i.currentSchema?.tables??[],t.followingOperations??[]);if(!(s?.length||p||m)){let e=new Set(f);for(let t of o){let n=c?.slice(c.indexOf(t)+1).find(t=>e.has(t));u.push(`ALTER TYPE ${d} ADD VALUE ${this.escapeValue(t)}${n===void 0?``:` BEFORE ${this.escapeValue(n)}`}`),e.add(t)}return u}if(!c?.length)throw new r(`Cannot alter enum "${a}" without its full destination values`,n.MIGRATION_INVALID_STATE);for(let{tableName:e,columnName:t}of l??[]){let n=i.currentSchema?.tables.find(t=>t.name===e)?.columns.find(e=>e.name===t),r=`${this.qualify(e)} ALTER COLUMN ${this.escapeIdentifier(t)}`;n?.default!==void 0&&u.push(`ALTER TABLE ${r} DROP DEFAULT`);let a=n?.type.endsWith(`[]`)?`text[]`:`text`;u.push(`ALTER TABLE ${r} TYPE ${a} USING ${this.escapeIdentifier(t)}::${a}`)}u.push(...this.buildEnumReplacementUpdates(e,i)),u.push(`DROP TYPE ${d}`),u.push(`CREATE TYPE ${d} AS ENUM (${c.map(e=>this.escapeValue(e)).join(`, `)})`);for(let{tableName:e,columnName:t}of l??[]){let n=i.currentSchema?.tables.find(t=>t.name===e)?.columns.find(e=>e.name===t),r=`${this.qualify(e)} ALTER COLUMN ${this.escapeIdentifier(t)}`,o=n?.type.endsWith(`[]`)?`${d}[]`:d;u.push(`ALTER TABLE ${r} TYPE ${o} USING ${this.escapeIdentifier(t)}::${o}`),n?.default!==void 0&&!enumDefaultLabels(n,a).some(e=>e!==null&&s?.includes(e))&&u.push(`ALTER TABLE ${r} SET DEFAULT ${n.default}`)}return u}enumColumnReplacementUpdates(e,t,n,r){if(!(r.currentSchema?.tables.find(e=>e.name===t)?.columns.find(e=>e.name===n)?.type)?.endsWith(`[]`))return super.enumColumnReplacementUpdates(e,t,n,r);let i=this.enumReplacementCases(e,t,n);if(i.length===0)return[];let a=this.escapeIdentifier(n);return[`UPDATE ${this.qualify(t)} SET ${a} = ARRAY(SELECT CASE value ${i.join(` `)} ELSE value END FROM unnest(${a}) WITH ORDINALITY AS member(value, position) ORDER BY position) WHERE ${a} IS NOT NULL`]}};export{ye as t};
|
|
415
|
-
//# sourceMappingURL=postgres-
|
|
415
|
+
//# sourceMappingURL=postgres-BqAxDWTQ.mjs.map
|