viborm 1.2.4 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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-s1ySUuMb.mjs +2 -0
- package/dist/builder-s1ySUuMb.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-7qiFSE8J.mjs +2 -0
- package/dist/chain-7qiFSE8J.mjs.map +1 -0
- package/dist/cli.mjs +2 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/client-6YgGlXzN.mjs +2 -0
- package/dist/client-6YgGlXzN.mjs.map +1 -0
- package/dist/{client-CUnPXifK.d.mts → client-70MrTq1E.d.mts} +3 -3
- package/dist/client-BgJ7Faln.mjs +49 -0
- package/dist/{client-B3VWFhv_.mjs.map → client-BgJ7Faln.mjs.map} +1 -1
- 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-KQ85SWfT.mjs +2 -0
- package/dist/controls-KQ85SWfT.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-vn-9CN0y.mjs} +2 -2
- package/dist/{driver-B19QlFqn.mjs.map → driver-vn-9CN0y.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-CcpKWCVo.mjs +2 -0
- package/dist/{every-o-Nu9Em8.mjs.map → every-CcpKWCVo.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-BsPZI4jE.mjs +2 -0
- package/dist/{hydration-CAxOL4aI.mjs.map → hydration-BsPZI4jE.mjs.map} +1 -1
- package/dist/identifier-conversion-BneQiLxQ.mjs +2 -0
- package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-BneQiLxQ.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-D9LtHxVK.mjs +2 -0
- package/dist/{key-BeoOwGr3.mjs.map → key-D9LtHxVK.mjs.map} +1 -1
- package/dist/{libsql-Drp-zaxq.mjs → libsql-BlSBYwd_.mjs} +3 -3
- package/dist/{libsql-Drp-zaxq.mjs.map → libsql-BlSBYwd_.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-CDTUZQWL.mjs → memory-C0k-_S_n.mjs} +2 -2
- package/dist/{memory-CDTUZQWL.mjs.map → memory-C0k-_S_n.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-D7zC03yD.mjs → mysql-DOLHwIM_.mjs} +6 -6
- package/dist/{mysql-D7zC03yD.mjs.map → mysql-DOLHwIM_.mjs.map} +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/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-DQVSTqVm.mjs} +4 -4
- package/dist/{postgres-Dv-QnnbD.mjs.map → postgres-DQVSTqVm.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-B6yWtnx_.mjs +2 -0
- package/dist/result-shape-B6yWtnx_.mjs.map +1 -0
- package/dist/scalar-CpEwuJvn.mjs +4 -0
- package/dist/scalar-CpEwuJvn.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-BnzGHn7k.mjs +2 -0
- package/dist/{schema-Cjem1-0f.mjs.map → schema-BnzGHn7k.mjs.map} +1 -1
- package/dist/{schema-introspection-DEYGC2qg.mjs → schema-introspection-DZsdP6bi.mjs} +4 -4
- package/dist/{schema-introspection-DEYGC2qg.mjs.map → schema-introspection-DZsdP6bi.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-C5RMZl05.mjs +2 -0
- package/dist/to-many-C5RMZl05.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-C3r4gO3Y.mjs} +4 -4
- package/dist/{utils-CZNaOZR7.mjs.map → utils-C3r4gO3Y.mjs.map} +1 -1
- package/dist/v-DtLdBQYg.mjs +2 -0
- package/dist/v-DtLdBQYg.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-CVSrhn0u.mjs +2 -0
- package/dist/validator-CVSrhn0u.mjs.map +1 -0
- package/dist/version-C8QLCt1n.mjs +2 -0
- package/dist/{version-nt0parEY.mjs.map → version-C8QLCt1n.mjs.map} +1 -1
- package/package.json +36 -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
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{p as t,y as n}from"./validation-Dk9Q_-C7.mjs";import{o as r,t as i}from"./sql-Bp7jicEX.mjs";import{r as a}from"./adapter-internals-n3Mf3css.mjs";import{O as o}from"./geo-point-codec-lhxH42SK.mjs";import{i as s}from"./datetime-physical-codec-oIhiYZEP.mjs";import{a as c,t as l}from"./physical-6V_LNU3L.mjs";import{t as u}from"./json-number-CGXpPu4D.mjs";import{C as d,D as f,E as p,M as ee,O as m,S as h,T as te,_ as ne,a as re,b as ie,d as g,f as _,g as v,h as y,i as b,j as x,k as S,l as C,n as w,o as T,p as E,r as D,s as O,v as k,w as A,x as j,y as M}from"./standard-sql-Bk4RZPqJ.mjs";import{r as N,t as P}from"./batch-refs-4L8ECdPU.mjs";import{f as F,g as I,h as L,n as R,o as z,p as B,r as V,t as H,u as U}from"./select-assembly-f1UGoblh.mjs";const W=ee(`"`),G={quotient:(e,t)=>r`(${e} / ${t})`,remainder:(e,t)=>r`(${e} % ${t})`};function sqliteIntegerPrecision(e){let t=m(e);if(t<19)return t;if(!(t>19))return(e.startsWith(`-`)?e.slice(1)<=`9223372036854775808`:e<=`9223372036854775807`)?t:void 0}const K=r.raw(`1000000000000000000`),overflowCoefficient=e=>r.raw(`1${`0`.repeat(Math.min(e.precision,18))}`),guardedCoefficientAssignment=(e,t,n,i)=>r`${e} = CASE WHEN ${e} IS NULL OR ${t} THEN ${n} ELSE ${overflowCoefficient(i)} END`,q=/^\d+$/,J=/["\\]/,jsonPathLeg=e=>{if(q.test(e))return`$[${e}]`;if(J.test(e))throw Error(`SQLite JSON path segments containing " or \\ must be rejected by the portable query contract.`);return`$."${e}"`},jsonExtract=(e,t)=>{let n=r`${e} -> '$'`;for(let e of t)n=r`${n} -> ${jsonPathLeg(e)}`;return n},jsonExtractText=(e,t)=>{if(t.length===0)return r`${e} ->> '$'`;let n=t.map(jsonPathLeg),i=n.pop(),a=e;for(let e of n)a=r`${a} -> ${e}`;return r`${a} ->> ${i}`},jsonArrayConcat=(e,t)=>r`(CASE WHEN ${e} = '[]' THEN ${t} WHEN ${t} = '[]' THEN ${e} ELSE substr(${e}, 1, length(${e}) - 1) || ',' || substr(${t}, 2) END)`,sqliteJsonListValue=e=>r`${x(e)}`,Y=[``,``],X=[`CAST(`,` AS INTEGER)`],ae=/\p{Cs}/u,Z=p().list;function jsonMember(e){return typeof e==`string`?ae.test(e)?void 0:JSON.stringify(e):e instanceof Uint8Array?`"${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}"`:typeof e==`bigint`||typeof e==`boolean`||Number.isSafeInteger(e)?String(e):void 0}function sqliteList(e){if(e.length<=25)return Z(e);let[t]=e,n=t?.strings[0]===X[0]?X:Y,a=[],o=0;for(let t of e){let[r,i,s]=t.strings,c=t.values[0],l=jsonMember(c);if(l===void 0||r!==n[0]||i!==n[1]||s!==void 0)return Z(e);c instanceof Uint8Array&&o++,a.push(l)}return o!==0&&o!==e.length?Z(e):r`(SELECT ${new i(n,[r.raw(o===0?`value`:`unhex(value)`)])} FROM json_each(${`[${a.join(`,`)}]`}))`}const Q={...p(),value:e=>{if(typeof e==`bigint`&&sqliteIntegerPrecision(String(e))===void 0)throw new t(`SQLite bigint values must fit signed 64-bit integers.`);return r`${e}`},true:()=>r.raw(`1`),false:()=>r.raw(`0`),json:e=>r`${JSON.stringify(e)}`,dateTime:(e,t)=>r`${s(e,l(t))}`,decimal:(e,t)=>new i(X,[o(e,t,`coefficient`)]),id:(e,t)=>r`${e}`,list:sqliteList},oe={...re(),like:(e,t)=>r`${e} LIKE ${t} ESCAPE '\\'`,notLike:(e,t)=>r`${e} NOT LIKE ${t} ESCAPE '\\'`,ilike:(e,t)=>r`lower(${e}) LIKE lower(${t}) ESCAPE '\\'`,notIlike:(e,t)=>r`lower(${e}) NOT LIKE lower(${t}) ESCAPE '\\'`,containsText:(e,t)=>r`instr(${e}, ${t}) > 0`,startsWithText:(e,t)=>r`substr(${e}, 1, length(${t})) COLLATE BINARY = ${t}`,endsWithText:(e,t)=>r`substr(${e}, length(${e}) - length(${t}) + 1) COLLATE BINARY = ${t}`,startsWithPrefix:(e,t)=>r`${e} GLOB ${`${S(t)}*`}`,exactTextEq:(e,t)=>r`${e} COLLATE BINARY = ${t}`,exactTextIn:(e,t)=>r`${e} COLLATE BINARY IN ${t}`,...v(),...k(),...j(),...y(Q.true,Q.false),...g()},se={...b(),asciiCaseFold:e=>r`lower(${e})`,caseSensitiveText:e=>r`${e} COLLATE BINARY`,concat:(...e)=>e.length===0?r.raw(`''`):e.length===1?e[0]:r`(${r.join(e,` || `)})`,greatest:(...e)=>r`MAX(${r.join(e,`, `)})`,least:(...e)=>r`MIN(${r.join(e,`, `)})`,integerDivide:(e,t)=>r`(${e} / CAST(${t} AS INTEGER))`,decimalCast:(e,t)=>r`CAST(${e} AS INTEGER)`,idCast:(e,t)=>t===`bytes`?r`unhex(${e})`:r`CAST(${e} AS TEXT)`,cast:D({text:`TEXT`,integer:`INTEGER`,bigint:`INTEGER`,boolean:`INTEGER`,numeric:`NUMERIC`}),blobToHex:e=>r`lower(hex(${e}))`},ce={...w(`9e999`),decimalAvg:(e,t)=>z(G,r`SUM(${e})`,r`COUNT(${e})`),decimalSumOperandPrecision:sqliteIntegerPrecision,integerSum:e=>{let t=r`SUM(${e} >> 32)`,n=r`SUM(${e} - ((${e} >> 32) << 32))`,i=r`(${t} + (${n} >> 32))`,a=r`(${n} & 4294967295)`,o=r`${i} * 4294967296.0 + ${a}`;return{parts:[t,n],value:r`CASE WHEN ${i} > 2147483647 THEN ${o} WHEN ${i} >= -2147483648 THEN ${i} * 4294967296 + ${a} ELSE MIN(${o}, -9223372036854777856.0) END`,order:[i,a]}}};function sqliteJsonEquals(e,t){let nodes=e=>r`SELECT fullkey, CASE WHEN type IN ('integer', 'real') THEN 'number' ELSE type END, atom FROM json_tree(${e})`;return r`(CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE NOT EXISTS (${nodes(e)} EXCEPT ${nodes(t)}) AND NOT EXISTS (${nodes(t)} EXCEPT ${nodes(e)}) END)`}const sqliteJsonObject=e=>{if(e.length===0)return r.raw(`json_object()`);let t=e.flatMap(([e,t])=>[r`${e}`,t]);return r`json_object(${r.join(t,`, `)})`},le={equals:sqliteJsonEquals,number:e=>r`CASE WHEN ${e} IS NULL THEN NULL ELSE printf(${r.raw(`'${u}'`)}, ${e}) END`,boolean:e=>r`json(CASE WHEN ${e} THEN 'true' ELSE 'false' END)`,document:e=>r`json(${e})`,object:sqliteJsonObject,array:e=>e.length===0?r.raw(`json_array()`):r`json_array(${r.join(e,`, `)})`,emptyArray:()=>r.raw(`json_array()`),agg:e=>r`COALESCE(json_group_array(json(${e})), json_array())`,objectFromColumns:sqliteJsonObject,extract:jsonExtract,extractText:jsonExtractText,numberAtPath:(e,t)=>r`(CASE WHEN json_type(${jsonExtract(e,t)}) IN ('integer', 'real') THEN CAST(${jsonExtractText(e,t)} AS REAL) END)`,stringAtPath:(e,t)=>r`((CASE WHEN json_type(${jsonExtract(e,t)}) = 'text' THEN ${jsonExtractText(e,t)} END) COLLATE BINARY)`,contains:(e,t)=>r`(json_type(${e}) = 'array' AND NOT EXISTS (SELECT 1 FROM json_each(${t}) AS required WHERE NOT EXISTS (SELECT 1 FROM json_each(${e}) AS candidate WHERE ${sqliteJsonEquals(r`${e} -> candidate.fullkey`,r`${t} -> required.fullkey`)})))`,lastElement:e=>r`${e} -> '$[#-1]'`,value:e=>r`${x(e)}`},ue={literal:e=>e.length===0?r.raw(`json_array()`):r`json_array(${r.join(e,`, `)})`,value:sqliteJsonListValue,enumValue:sqliteJsonListValue,has:(e,t)=>r`EXISTS (SELECT 1 FROM json_each(${e}) WHERE value = ${t})`,hasEvery:(e,t)=>r`(SELECT COUNT(*) FROM json_each(${t}) WHERE value IN (SELECT value FROM json_each(${e}))) = json_array_length(${t})`,hasSome:(e,t)=>r`EXISTS (SELECT 1 FROM json_each(${e}) AS a, json_each(${t}) AS b WHERE a.value = b.value)`,isEmpty:e=>r`(json_array_length(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>r`CAST(${e} AS TEXT)`,length:e=>r`json_array_length(${e})`,get:(e,t)=>r`json_extract(${e}, '$[' || ${t} || ']')`,push:(e,t)=>r`json_insert(${e}, '$[#]', ${t})`,set:(e,t,n)=>r`json_set(${e}, '$[' || ${t} || ']', ${n})`},de={...C(),nullsFirst:(e,t)=>t===`desc`?r`${e} DESC NULLS FIRST`:r`${e} ASC NULLS FIRST`,nullsLast:(e,t)=>t===`desc`?r`${e} DESC NULLS LAST`:r`${e} ASC NULLS LAST`},fe={...M(),multiply:(e,t,n)=>{let i=n?.decimal;return i?guardedCoefficientAssignment(e,r`${t} = 0 OR ABS(${e}) <= ${K} / ABS(${t})`,z(G,r`(${e} * ${t})`,U(i.scale)),i):r`${e} = ${e} * ${t}`},divide:(e,t,n)=>{let i=n?.decimal;if(i){let n=U(i.scale);return guardedCoefficientAssignment(e,r`ABS(${e}) <= ${K} / ${n}`,z(G,F(r`(${e} * ${n})`,t),r`ABS(${t})`),i)}return n?.integer?r`${e} = ${e} / CAST(${t} AS INTEGER)`:r`${e} = ${e} / ${t}`},push:(e,t)=>r`${e} = ${jsonArrayConcat(r`json(COALESCE(${e}, '[]'))`,t)}`,unshift:(e,t)=>r`${e} = ${jsonArrayConcat(t,r`json(COALESCE(${e}, '[]'))`)}`},pe={skipDuplicatesStrategy:`sql`,insert:E(W),insertDefault:e=>r`INSERT INTO ${e} DEFAULT VALUES`,...ne(),returning:e=>r`RETURNING ${e}`,...ie()},$={exists:e=>r`SELECT CASE WHEN EXISTS (${e}) THEN 1 ELSE json_extract('x', '$') END AS "__viborm_assert__"`,notExists:e=>r`SELECT CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE json_extract('x', '$') END AS "__viborm_assert__"`},me={...T(),right:(e,t)=>{throw Error(`SQLite does not support RIGHT JOIN. Restructure the query with joins.left and swapped operands.`)},full:(e,t)=>{throw Error(`SQLite does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.`)},lateral:(e,t)=>{throw Error(`SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.`)},lateralLeft:(e,t)=>{throw Error(`SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.`)}},he={supportsReturning:!0,supportsCteWithMutations:!1,supportsFullOuterJoin:!1,supportsLateralJoins:!1,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!1},ge={decimalRepresentation:`coefficient`,decimalListRepresentation:`coefficient`,dateTimeRepresentation:l,idRepresentation:(e,t)=>c(e,t,`sqlite`)?.representation??`text`,parseResult:I,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()},_e=_(W),ve=te(),ye=d(),be=f(W),xe=O(W),Se=A(),Ce=h();var SQLiteAdapter=class{constructor({temporaryObjects:e=!0}={}){B(this,this.geoPoint);let t,createBatchRefs=()=>this.#t(e);a(this,{get batchRefs(){return t??=createBatchRefs(),t},constraints:L,select:this.#e.select})}raw=Ce;identifiers={..._e};literals={...Q};operators={...oe};expressions={...se};aggregates={...ce};json={...le};arrays={...ue};orderBy={...de};clauses={...ve};set={...fe};filters={...ye};subqueries={...be};noLimitValue=r.raw(`-1`);#e={select:e=>e.distinct?H(e,e.distinct,this.identifiers.escape,this.noLimitValue):R(r`SELECT ${e.columns}`,e,{forUpdate:`omit`,noLimitValue:this.noLimitValue})};cte={...xe};mutations={...pe};assertions={...$};joins={...me};setOperations={...Se};capabilities={...he};lastInsertId=()=>r.raw(`last_insert_rowid()`);#t(e){let t=r.raw(W(P)),n=r.raw(e?`CREATE TEMP TABLE IF NOT EXISTS`:`CREATE TABLE IF NOT EXISTS`);return N({table:t,batchIdColumn:r.raw(`"batch_id"`),keyColumn:r.raw(`"ref_key"`),valueColumn:r.raw(`"ref_value"`),createTable:r`${n} ${t} ("batch_id" TEXT NOT NULL, "ref_key" TEXT NOT NULL, "ref_value" TEXT, PRIMARY KEY ("batch_id", "ref_key"))`,castValue:e=>r`CAST((${e}) AS TEXT)`,lastInsertId:()=>this.lastInsertId()})}vector=n;geoPoint=(()=>{let longitude=e=>this.json.numberAtPath(e,[`longitude`]),latitude=e=>this.json.numberAtPath(e,[`latitude`]);return{value:(e,t)=>r`json_object('longitude', ${this.json.document(this.json.number(e))}, 'latitude', ${this.json.document(this.json.number(t))})`,longitude,latitude,...V(longitude,latitude,this.operators)}})();result={...ge}};export{SQLiteAdapter as t};
|
|
2
|
-
//# sourceMappingURL=sqlite-adapter-CW_3l6ea.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sqlite-adapter-CW_3l6ea.mjs","names":["sql","#createBatchRefs","#assemble"],"sources":["../src/adapters/databases/sqlite/sqlite-adapter.ts"],"sourcesContent":["import { UnsupportedOperationError, unsupportedVector } from \"@errors\";\nimport { sqliteDateTimePhysicalForm } from \"@schema/scalars/datetime/physical\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { Sql, sql } from \"@sql\";\nimport { encodePhysicalDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type {\n ArithmeticTarget,\n BatchReferenceSqlAdapter,\n} from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport {\n type AdapterResultParser,\n passThroughParseResult,\n} from \"../../adapter-result-parser\";\nimport { sqliteConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n} from \"../../database-adapter\";\nimport {\n BATCH_REFS_TABLE,\n createOnConflictBatchRefs,\n} from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n halfEvenQuotient,\n scaleFactorSql,\n signedNumerator,\n} from \"../../shared/decimal-arithmetic\";\nimport { createGeoPointCoordinatePredicates } from \"../../shared/geo-point\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDirectionOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createOnConflictBuilders,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n decimalCoefficientPrecision,\n escapeGlobLiteral,\n stringifyJson,\n} from \"../../shared/standard-sql\";\nimport { SQLITE_BINARY64_FORMAT } from \"./storage/json-number\";\n\nconst quoteIdent = createIdentifierQuoter('\"');\n\n/**\n * Every SQLite decimal expression is signed-int64 integer arithmetic on the\n * stored unscaled coefficient, so `/` IS truncating integer division and `%`\n * carries the dividend's sign. Neither is true once an operand becomes REAL or\n * TEXT, which is why every operand below arrives as an INTEGER column, an\n * integer literal, or a `CAST(... AS INTEGER)` bind.\n */\nconst SQLITE_INTEGERS: ExactIntegerArithmetic = {\n quotient: (n: Sql, d: Sql): Sql => sql`(${n} / ${d})`,\n remainder: (n: Sql, d: Sql): Sql => sql`(${n} % ${d})`,\n};\n\nconst SQLITE_INT64_NEGATIVE_MAGNITUDE = \"9223372036854775808\";\nconst SQLITE_INT64_MAX = \"9223372036854775807\";\n\n/** Admit the exact TEXT-to-INTEGER cast domain, including its 19-digit edges. */\nfunction sqliteIntegerPrecision(coefficient: string): number | undefined {\n const precision = decimalCoefficientPrecision(coefficient);\n if (precision < 19) return precision;\n if (precision > 19) return undefined;\n const isAdmitted = coefficient.startsWith(\"-\")\n ? coefficient.slice(1) <= SQLITE_INT64_NEGATIVE_MAGNITUDE\n : coefficient <= SQLITE_INT64_MAX;\n return isAdmitted ? precision : undefined;\n}\n\n/**\n * The widest intermediate the guarded arms will evaluate: 10^18.\n *\n * SQLite does not raise on an integer multiply that overflows — it converts the\n * expression to REAL, which is the one representation an exact decimal must\n * never touch. So the arms are GUARDED: the guard compares magnitudes by\n * DIVISION (`|x| <= LIMIT / |y|`, exact for integers) instead of computing the\n * product it is protecting, and a `CASE` evaluates only the branch it selects.\n *\n * 10^18 is not arbitrary, and it is not independent. `precision + scale <= 18`\n * is SQLite's declared field limit (plan 3.1), ENFORCED once when the schema is\n * bound (`schema/scalars/decimal/provider-limits.ts`), so every mathematically\n * in-range result has `|x * y| <= 10^(p+s) <= 10^18`: the guard never rejects\n * an answer that fits the field, and int64 keeps a factor of nine in reserve\n * for the `+/- 1` step and the `d - |r|` tie test.\n *\n * THE COUPLING IS LOAD-BEARING, in both directions. This constant is flat where\n * the per-descriptor bound would be `B = scale === 0 ? M : M*F + F/2 - 1`, and\n * that is only equivalent because no descriptor past `p + s = 18` can reach it:\n * a product in `(B, 10^18]` is admitted here and then refused by the range\n * CHECK instead of by the sentinel — the same loud, atomic failure by the other\n * mechanism. Remove the bind limit and the flat guard stops being a bound on\n * the FIELD at all, which is exactly what {@link overflowCoefficient} depends\n * on below.\n */\nconst SQLITE_INTERMEDIATE_LIMIT = sql.raw(\"1000000000000000000\");\n\n/**\n * The coefficient an unsafe or out-of-domain arithmetic result becomes: 10^p,\n * the smallest integer OUTSIDE a `precision: p` field's declared range.\n *\n * The DDL's range check refuses it, so the statement fails atomically and\n * nothing is written — which is the contract for an overflow that is only\n * knowable mid-statement.\n *\n * THE CLAMP DEPENDS ON THE BIND LIMIT, and is only correct because of it. At 19\n * digits and beyond, `10^p` is a REAL to SQLite's own parser, so the sentinel\n * would stop being an integer the CHECK can refuse — and `min(p, 18)` would put\n * it INSIDE the range of a `precision >= 19` column, which is a silently\n * written wrong value rather than a failure. No such column exists: plan 3.1's\n * `precision <= 18 && precision + scale <= 18` is proven once at schema bind\n * (`schema/scalars/decimal/provider-limits.ts`), before any I/O, so\n * `min(p, 18)` is `p` for every descriptor that ever reaches here. The clamp is\n * what an unreachable arm does when it is reached anyway, not a policy — and it\n * is why the bind limit is load-bearing rather than ergonomic.\n */\nconst overflowCoefficient = (descriptor: DecimalDescriptor): Sql =>\n sql.raw(`1${\"0\".repeat(Math.min(descriptor.precision, 18))}`);\n\n/**\n * `column = <exact coefficient arithmetic>`, or the constraint-breaking\n * coefficient when the intermediate would leave int64.\n *\n * A NULL column is safe by definition and takes the guarded arm, where every\n * operator is null-strict and the assignment stays NULL.\n */\nconst guardedCoefficientAssignment = (\n column: Sql,\n safe: Sql,\n value: Sql,\n descriptor: DecimalDescriptor\n): Sql =>\n sql`${column} = CASE WHEN ${column} IS NULL OR ${safe} THEN ${value} ELSE ${overflowCoefficient(descriptor)} END`;\n\nconst JSON_ARRAY_INDEX_SEGMENT = /^\\d+$/;\nconst JSON_UNADDRESSABLE_LABEL = /[\"\\\\]/;\n\n// Each path segment binds as its own single-leg JSONPath ('$[N]' for\n// array indices, '$.\"seg\"' otherwise) chained with -> , so segments can\n// never splice extra legs into the path. SQLite's path grammar has no\n// escape syntax inside quoted labels, so the portable query contract rejects\n// keys containing \" or \\ before adapter execution. This throw is defensive.\nconst jsonPathLeg = (segment: string): string => {\n if (JSON_ARRAY_INDEX_SEGMENT.test(segment)) {\n return `$[${segment}]`;\n }\n if (JSON_UNADDRESSABLE_LABEL.test(segment)) {\n throw new Error(\n 'SQLite JSON path segments containing \" or \\\\ must be rejected by the portable query contract.'\n );\n }\n return `$.\"${segment}\"`;\n};\n\n/** Chain one bound `-> '$leg'` per path segment ('$' alone = document root). */\nconst jsonExtract = (column: Sql, path: string[]): Sql => {\n let expr = sql`${column} -> '$'`;\n for (const segment of path) {\n expr = sql`${expr} -> ${jsonPathLeg(segment)}`;\n }\n return expr;\n};\n\n/** Same chain, but the final leg uses `->>` so strings come back unquoted. */\nconst jsonExtractText = (column: Sql, path: string[]): Sql => {\n if (path.length === 0) {\n return sql`${column} ->> '$'`;\n }\n const legs = path.map(jsonPathLeg);\n const last = legs.pop()!;\n let expr: Sql = column;\n for (const leg of legs) {\n expr = sql`${expr} -> ${leg}`;\n }\n return sql`${expr} ->> ${last}`;\n};\n\n/**\n * Concatenate two JSON array texts by string surgery: strip `left`'s closing\n * bracket and `right`'s opening bracket. SQLite has no JSON array-concat\n * function, and json_insert('$[#]') can only append one element per pair.\n * Both sides must be canonical JSON (json() output or JSON.stringify).\n */\nconst jsonArrayConcat = (left: Sql, right: Sql): Sql =>\n sql`(CASE WHEN ${left} = '[]' THEN ${right} WHEN ${right} = '[]' THEN ${left} ELSE substr(${left}, 1, length(${left}) - 1) || ',' || substr(${right}, 2) END)`;\n\n/** The one JSON list container every SQLite list value crosses as. */\nconst sqliteJsonListValue = (values: unknown[]): Sql =>\n sql`${stringifyJson(values)}`;\n\n/** A bare operand, and a decimal operand: its coefficient read as INTEGER. */\nconst PARAMETER = [\"\", \"\"];\nconst COEFFICIENT = [\"CAST(\", \" AS INTEGER)\"];\nconst LONE_SURROGATE = /\\p{Cs}/u;\nconst PARENTHESIZED_LIST = createStandardLiterals().list;\n/**\n * The longest list kept parenthesized. Without `sqlite_stat1` SQLite sizes an\n * `IN (SELECT …)` at 25 rows and a list at its length, so up to 25 members the\n * list is planned no worse: a key list beside another indexed equality still\n * seeks the key. It is also a quarter of D1's 100-value bind budget.\n */\nconst PLANNED_LIST = 25;\n\n/**\n * One member as JSON text that `json_each` reads back as the value its own\n * parameter binds, or `undefined`. A non-integer number is not one: SQLite\n * reparses JSON text with an error in the last place for some doubles; nor is\n * a string with a lone surrogate, which a driver binds as U+FFFD.\n */\nfunction jsonMember(value: unknown): string | undefined {\n if (typeof value === \"string\")\n return LONE_SURROGATE.test(value) ? undefined : JSON.stringify(value);\n if (value instanceof Uint8Array)\n return `\"${Array.from(value, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}\"`;\n return typeof value === \"bigint\" ||\n typeof value === \"boolean\" ||\n Number.isSafeInteger(value)\n ? String(value)\n : undefined;\n}\n\n/**\n * engine-09: a list longer than {@link PLANNED_LIST} whose members are each one\n * parameter under one spelling — bare, or a decimal's coefficient cast — as\n * ONE parameter, a JSON array `json_each` reads back and spells per element as\n * each member was, so `IN` and `NOT IN` keep their answers, NULLs included.\n * Blobs travel as hex, read through `unhex` (SQLite 3.41). Any other list\n * keeps a parameter per member.\n */\nfunction sqliteList(members: Sql[]): Sql {\n if (members.length <= PLANNED_LIST) return PARENTHESIZED_LIST(members);\n const [first] = members;\n const spelling =\n first?.strings[0] === COEFFICIENT[0] ? COEFFICIENT : PARAMETER;\n const elements: string[] = [];\n let blobs = 0;\n for (const member of members) {\n const [head, tail, extra] = member.strings;\n const value = member.values[0];\n const element = jsonMember(value);\n if (\n element === undefined ||\n head !== spelling[0] ||\n tail !== spelling[1] ||\n extra !== undefined\n )\n return PARENTHESIZED_LIST(members);\n if (value instanceof Uint8Array) blobs++;\n elements.push(element);\n }\n // Blobs beside other values: nothing one spelling reads.\n if (blobs !== 0 && blobs !== members.length)\n return PARENTHESIZED_LIST(members);\n const read = new Sql(spelling, [\n sql.raw(blobs === 0 ? \"value\" : \"unhex(value)\"),\n ]);\n return sql`(SELECT ${read} FROM json_each(${`[${elements.join(\",\")}]`}))`;\n}\n\n/** Facts a SQLite driver states about its transport. */\nexport interface SQLiteAdapterOptions {\n /**\n * Whether the transport admits temporary objects (`CREATE TEMP TABLE`).\n * better-sqlite3, libSQL and bun:sqlite do; Cloudflare D1's authorizer\n * rejects them with `SQLITE_AUTH`, and rejects the whole batch with them.\n * Defaults to `true`.\n */\n readonly temporaryObjects?: boolean;\n}\n\n/**\n * The dialect's stateless SQL builders, built once per module. Each adapter\n * takes its own shallow copy of every group, so a driver that overrides one\n * hook (`driver.adapter.result.parseField = …`) changes only its own adapter,\n * as before, while a driver per request no longer rebuilds every closure.\n */\nconst SQLITE_LITERALS = {\n ...createStandardLiterals(),\n\n value: (value: unknown): Sql => {\n if (\n typeof value === \"bigint\" &&\n sqliteIntegerPrecision(String(value)) === undefined\n )\n throw new UnsupportedOperationError(\n \"SQLite bigint values must fit signed 64-bit integers.\"\n );\n return sql`${value}`;\n },\n\n // SQLite uses 1/0 for booleans\n true: (): Sql => sql.raw(\"1\"),\n\n false: (): Sql => sql.raw(\"0\"),\n\n // SQLite requires JSON values to be stringified\n json: (v: unknown): Sql => sql`${JSON.stringify(v)}`,\n\n // SQLite has no temporal type, so the field's declaration is what the column\n // physically holds and the operand has to be the same kind of value: an ISO\n // string bound against an epoch-millisecond INTEGER matches no row and,\n // written, stores text the typed read then refuses. A TEXT-declared or\n // undeclared field keeps the ISO spelling byte for byte. The string is a\n // validated ISO timestamp — the ISO boundary owns that — and every\n // four-digit public instant round-trips through the Julian-day double.\n dateTime: (iso: string, nativeType?: NativeTypeDeclaration): Sql =>\n sql`${encodePhysicalDateTime(iso, sqliteDateTimePhysicalForm(nativeType))}`,\n\n // SQLite has no exact decimal type, so a decimal column stores the UNSCALED\n // INTEGER COEFFICIENT and an operand becomes that same coefficient. Integer\n // comparison is then exact numeric comparison, and ordering, aggregation\n // and arithmetic are exact for the same reason.\n //\n // The digits bind as TEXT and `CAST(... AS INTEGER)` reads them, rather than\n // riding a JavaScript number (which rounds above 2^53) or a bigint (which\n // D1 will not bind). SQLite's TEXT-to-INTEGER cast is a decimal integer\n // parse, not a float one.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n new Sql(COEFFICIENT, [\n encodePhysicalDecimal(canonical, descriptor, \"coefficient\"),\n ]),\n\n // Every compact domain is a `BLOB` here and takes the payload's bytes as\n // the ordinary binary parameter a blob scalar already binds; a text-stored\n // domain takes the public string unchanged.\n id: (physical: string | Uint8Array, _representation: IdRepresentation): Sql =>\n sql`${physical}`,\n\n list: sqliteList,\n};\n\nconst SQLITE_OPERATORS = {\n ...createComparisonOperators(),\n\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`lower(${column}) LIKE lower(${pattern}) ESCAPE '\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`lower(${column}) NOT LIKE lower(${pattern}) ESCAPE '\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`instr(${column}, ${value}) > 0`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`substr(${column}, 1, length(${value})) COLLATE BINARY = ${value}`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`substr(${column}, length(${column}) - length(${value}) + 1) COLLATE BINARY = ${value}`,\n // GLOB, not LIKE — and this is the one place the \"portable escaped LIKE\"\n // premise of Decision 7.3 does not survive contact with SQLite. Both of\n // SQLite's LIKE-optimization preconditions fail here: an ESCAPE clause\n // disqualifies the optimization outright, and with `case_sensitive_like`\n // off (the default, and connection-global, so not ours to flip) the\n // optimization additionally wants a NOCASE-collated index, while `push()`\n // only ever creates BINARY ones. Measured on better-sqlite3, 20k rows,\n // plain index: `col LIKE ? ESCAPE '\\'` is a SCAN — exactly what the\n // `substr` spelling above already costs — AND it answers case-insensitively,\n // which would break the case-sensitivity contract this operator holds.\n //\n // GLOB has neither problem. It compares bytes, so it is case- and\n // accent-sensitive by construction (that is what `COLLATE BINARY` buys\n // above, so nothing is lost by dropping it), and it ranges on the ordinary\n // BINARY index: the same probe plans this as a covering index SEARCH over\n // 111 rows against a 20000-row SCAN. Its wildcards are `*`/`?`/`[`, and it\n // has no ESCAPE clause, so `escapeGlobLiteral` quotes them as classes.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`${column} GLOB ${`${escapeGlobLiteral(value)}*`}`,\n\n // `COLLATE BINARY` names a COLLATION, not a function of the column, and\n // SQLite's ordinary index is a BINARY index — so the case-sensitive\n // spelling is already the index-usable one and there is nothing to add.\n // Byte-identical to what shipped before §10.2.\n exactTextEq: (column: Sql, value: Sql): Sql =>\n sql`${column} COLLATE BINARY = ${value}`,\n exactTextIn: (column: Sql, values: Sql): Sql =>\n sql`${column} COLLATE BINARY IN ${values}`,\n\n ...createMembershipOperators(),\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n // Logical (vacuous cases use SQLite's 1/0 booleans)\n ...createLogicalOperators(SQLITE_LITERALS.true, SQLITE_LITERALS.false),\n\n ...createExistenceOperators(),\n};\n\nconst SQLITE_EXPRESSIONS = {\n ...createCommonExpressions(),\n\n // SQLite lower() intentionally provides the portable ASCII-only contract.\n asciiCaseFold: (expr: Sql): Sql => sql`lower(${expr})`,\n caseSensitiveText: (expr: Sql): Sql => sql`${expr} COLLATE BINARY`,\n\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw(\"''\");\n if (parts.length === 1) return parts[0]!;\n return sql`(${sql.join(parts, \" || \")})`;\n },\n\n // SQLite has no GREATEST/LEAST; multi-arg MAX/MIN are the scalar forms\n greatest: (...exprs: Sql[]): Sql => sql`MAX(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`MIN(${sql.join(exprs, \", \")})`,\n\n // The expression form of `set.divide`'s integer arm, and for the same\n // reason: SQLite drivers bind JS numbers as REAL, so `x / ?` would run real\n // division. Casting the divisor to INTEGER makes it native INT/INT\n // division, truncating toward zero.\n integerDivide: (left: Sql, right: Sql): Sql =>\n sql`(${left} / CAST(${right} AS INTEGER))`,\n\n // A deferred SQLite decimal is already a captured coefficient. The\n // descriptor still travels through the common contract so no caller can\n // select this physical cast without naming the destination domain.\n decimalCast: (expr: Sql, _descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${expr} AS INTEGER)`,\n\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`unhex(${expr})`\n : sql`CAST(${expr} AS TEXT)`,\n\n // SQLite type mappings\n cast: createCastExpression({\n text: \"TEXT\",\n integer: \"INTEGER\",\n bigint: \"INTEGER\",\n boolean: \"INTEGER\",\n numeric: \"NUMERIC\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`lower(hex(${expr}))`,\n};\n\nconst SQLITE_AGGREGATES = {\n ...createAggregateFunctions(\"9e999\"),\n\n // The average of a coefficient column IS the half-even integer quotient of\n // its exact sum by its non-null count: dividing both the sum and the count\n // of `logical x 10^s` values leaves `average x 10^s`, so no scale factor\n // appears at all. `COUNT(column)` is zero exactly when `SUM` is NULL, so\n // the null-strict operators answer NULL for an empty or all-null group and\n // the zero divisor is never reached with a value.\n decimalAvg: (column: Sql, _descriptor: DecimalDescriptor): Sql =>\n halfEvenQuotient(\n SQLITE_INTEGERS,\n sql`SUM(${column})`,\n sql`COUNT(${column})`\n ),\n\n // A SQLite decimal aggregate is an int64 `SUM` over coefficients. Exact\n // operand admission follows the signed range rather than digit count: some\n // 19-digit values fit, while the next value past either endpoint would make\n // `CAST(... AS INTEGER)` saturate. The sum itself is `integerSum`'s, exact\n // past that range.\n decimalSumOperandPrecision: sqliteIntegerPrecision,\n\n // `>>` is arithmetic, so an int64 member is exactly `(x >> 32) * 2^32` plus\n // its second part. That part stays REAL for a non-integer member, which the\n // reader refuses as it refused the plain `SUM`.\n // `low` sums non-negative 32-bit remainders: carrying its high bits into\n // `high` leaves a pair that sorts exactly as the total. `value` is that\n // total inside int64 and its nearest double outside, below -2^63 at most\n // `-2^63 - 2048`: SQLite compares an integer with a double exactly, so it\n // is exact against every int64 operand (a decimal coefficient's whole\n // domain), and a number operand past int64 is told apart from every total\n // but those that round to it.\n integerSum: (column: Sql) => {\n const high = sql`SUM(${column} >> 32)`;\n const low = sql`SUM(${column} - ((${column} >> 32) << 32))`;\n const carried = sql`(${high} + (${low} >> 32))`;\n const rest = sql`(${low} & 4294967295)`;\n const double = sql`${carried} * 4294967296.0 + ${rest}`;\n return {\n parts: [high, low] as const,\n value: sql`CASE WHEN ${carried} > 2147483647 THEN ${double} WHEN ${carried} >= -2147483648 THEN ${carried} * 4294967296 + ${rest} ELSE MIN(${double}, -9223372036854777856.0) END`,\n order: [carried, rest],\n };\n },\n};\n\n// Compare every node, including empty containers. Array indices remain part\n// of the path; object property insertion order does not. JSON numbers share\n// one domain, while booleans, strings and JSON null retain their distinct type.\nfunction sqliteJsonEquals(left: Sql, right: Sql): Sql {\n const nodes = (value: Sql) =>\n sql`SELECT fullkey, CASE WHEN type IN ('integer', 'real') THEN 'number' ELSE type END, atom FROM json_tree(${value})`;\n return sql`(CASE WHEN ${left} IS NULL OR ${right} IS NULL THEN NULL ELSE NOT EXISTS (${nodes(left)} EXCEPT ${nodes(right)}) AND NOT EXISTS (${nodes(right)} EXCEPT ${nodes(left)}) END)`;\n}\n\nconst sqliteJsonObject = (pairs: [string, Sql][]): Sql => {\n if (pairs.length === 0) return sql.raw(\"json_object()\");\n const args = pairs.flatMap(([key, value]) => [sql`${key}`, value]);\n return sql`json_object(${sql.join(args, \", \")})`;\n};\n\nconst SQLITE_JSON = {\n equals: sqliteJsonEquals,\n number: (expression: Sql): Sql =>\n sql`CASE WHEN ${expression} IS NULL THEN NULL ELSE printf(${sql.raw(`'${SQLITE_BINARY64_FORMAT}'`)}, ${expression}) END`,\n boolean: (condition: Sql): Sql =>\n sql`json(CASE WHEN ${condition} THEN 'true' ELSE 'false' END)`,\n // SQLite drops the JSON subtype across scalar-subquery boundaries. Restore it\n // before embedding the value in json_object/json_array, or an object becomes a\n // quoted JSON string inside the outer document.\n document: (expression: Sql): Sql => sql`json(${expression})`,\n\n object: sqliteJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw(\"json_array()\");\n return sql`json_array(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw(\"json_array()\"),\n\n // Use json() to ensure the aggregated value is treated as JSON, not string\n // Without json(), json_group_array produces [\"{...}\"] instead of [{...}]\n agg: (expr: Sql): Sql =>\n sql`COALESCE(json_group_array(json(${expr})), json_array())`,\n\n objectFromColumns: sqliteJsonObject,\n\n // `->` returns the value as canonical JSON text ('\"str\"', '2', 'null'),\n // the same format json.value binds, so extracted values compare with\n // plain equality (json_extract would return native SQL values instead)\n extract: jsonExtract,\n\n // `->>` returns text with strings unquoted, for LIKE matching\n extractText: jsonExtractText,\n\n // json_type reads the chained `->` result (canonical JSON text), so it\n // sees 'integer'/'real' only for real JSON numbers; every other shape —\n // and an absent path, where `->` is NULL — falls through to NULL\n numberAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN json_type(${jsonExtract(column, path)}) IN ('integer', 'real') THEN CAST(${jsonExtractText(column, path)} AS REAL) END)`,\n\n // COLLATE BINARY is SQLite's default for these columns; naming it keeps\n // the code-point ordering contract explicit alongside PG's COLLATE \"C\"\n stringAtPath: (column: Sql, path: string[]): Sql =>\n sql`((CASE WHEN json_type(${jsonExtract(column, path)}) = 'text' THEN ${jsonExtractText(column, path)} END) COLLATE BINARY)`,\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`(json_type(${target}) = 'array' AND NOT EXISTS (SELECT 1 FROM json_each(${value}) AS required WHERE NOT EXISTS (SELECT 1 FROM json_each(${target}) AS candidate WHERE ${sqliteJsonEquals(sql`${target} -> candidate.fullkey`, sql`${value} -> required.fullkey`)})))`,\n\n lastElement: (target: Sql): Sql => sql`${target} -> '$[#-1]'`,\n\n value: (v: unknown): Sql => sql`${stringifyJson(v)}`,\n};\n\nconst SQLITE_ARRAYS = {\n // SQLite uses JSON arrays\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw(\"json_array()\");\n return sql`json_array(${sql.join(items, \", \")})`;\n },\n\n value: sqliteJsonListValue,\n\n // Deliberately the same container, by identity: SQLite stores an enum LIST\n // as JSON like every other list, so its members are ordinary JSON strings\n // and there is no element type to spell. The `TEXT CHECK(col IN ...)`\n // describes one member.\n enumValue: sqliteJsonListValue,\n\n // Check if value exists in JSON array using json_each\n has: (column: Sql, value: Sql): Sql =>\n sql`EXISTS (SELECT 1 FROM json_each(${column}) WHERE value = ${value})`,\n\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`(SELECT COUNT(*) FROM json_each(${values}) WHERE value IN (SELECT value FROM json_each(${column}))) = json_array_length(${values})`,\n\n hasSome: (column: Sql, values: Sql): Sql =>\n sql`EXISTS (SELECT 1 FROM json_each(${column}) AS a, json_each(${values}) AS b WHERE a.value = b.value)`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(json_array_length(${column}) = 0 OR ${column} IS NULL)`,\n\n // The column already stores the container as TEXT (its declared type is\n // TEXT, not JSON, precisely so the descriptor's CHECK can hold it). The\n // cast is what stops a JSON carrier from embedding it as a document and a\n // driver from handing back anything but the stored bytes.\n exactNumericProjection: (column: Sql): Sql => sql`CAST(${column} AS TEXT)`,\n\n length: (column: Sql): Sql => sql`json_array_length(${column})`,\n\n get: (column: Sql, index: Sql): Sql =>\n sql`json_extract(${column}, '$[' || ${index} || ']')`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`json_insert(${column}, '$[#]', ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`json_set(${column}, '$[' || ${index} || ']', ${value})`,\n};\n\nconst SQLITE_ORDER_BY = {\n ...createDirectionOrderBy(),\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS FIRST`\n : sql`${column} ASC NULLS FIRST`,\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS LAST`\n : sql`${column} ASC NULLS LAST`,\n};\n\nconst SQLITE_SET = {\n ...createNumericSetOperations(),\n\n // `x * y / 10^s` in coefficient space, rounded half to even. The guard is\n // the multiply's own: `x * y` is the only intermediate here that can leave\n // int64, and it does so exactly when the result cannot fit the field.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n const descriptor = target?.decimal;\n if (!descriptor) return sql`${column} = ${column} * ${by}`;\n return guardedCoefficientAssignment(\n column,\n sql`${by} = 0 OR ABS(${column}) <= ${SQLITE_INTERMEDIATE_LIMIT} / ABS(${by})`,\n halfEvenQuotient(\n SQLITE_INTEGERS,\n sql`(${column} * ${by})`,\n scaleFactorSql(descriptor.scale)\n ),\n descriptor\n );\n },\n\n // `x * 10^s / y` in coefficient space, rounded half to even; the divisor's\n // sign moves onto the numerator so the rule always sees a positive divisor.\n // `y` is never zero — division by canonical zero is refused before I/O.\n //\n // SQLite drivers bind JS numbers as REAL, so `col / ?` runs real division\n // and would persist a fractional value into an INTEGER column. Casting the\n // divisor to INTEGER makes it native INT/INT division (truncating toward\n // zero, matching Postgres) for integer columns; real columns keep real\n // division since the column itself carries REAL affinity.\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n const descriptor = target?.decimal;\n if (descriptor) {\n const factor = scaleFactorSql(descriptor.scale);\n return guardedCoefficientAssignment(\n column,\n sql`ABS(${column}) <= ${SQLITE_INTERMEDIATE_LIMIT} / ${factor}`,\n halfEvenQuotient(\n SQLITE_INTEGERS,\n signedNumerator(sql`(${column} * ${factor})`, by),\n sql`ABS(${by})`\n ),\n descriptor\n );\n }\n return target?.integer\n ? sql`${column} = ${column} / CAST(${by} AS INTEGER)`\n : sql`${column} = ${column} / ${by}`;\n },\n\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = ${jsonArrayConcat(\n sql`json(COALESCE(${column}, '[]'))`,\n values\n )}`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = ${jsonArrayConcat(\n values,\n sql`json(COALESCE(${column}, '[]'))`\n )}`,\n};\n\nconst SQLITE_MUTATIONS = {\n skipDuplicatesStrategy: \"sql\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql => sql`INSERT INTO ${table} DEFAULT VALUES`,\n\n ...createMutationCommands(),\n\n // SQLite 3.35+ supports RETURNING\n returning: (columns: Sql): Sql => sql`RETURNING ${columns}`,\n\n // SQLite uses same ON CONFLICT syntax as PostgreSQL (3.24+/3.35+)\n ...createOnConflictBuilders(),\n};\n\nconst SQLITE_ASSERTIONS = {\n exists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN EXISTS (${query}) THEN 1 ELSE json_extract('x', '$') END AS \"__viborm_assert__\"`,\n notExists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE json_extract('x', '$') END AS \"__viborm_assert__\"`,\n};\n\nconst SQLITE_JOINS = {\n ...createCoreJoins(),\n\n // SQLite doesn't support RIGHT JOIN (before 3.39, and driver support varies).\n // Never silently downgrade: emitting LEFT JOIN without swapping operands\n // returns wrong rows. The query engine never calls this today.\n right: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"SQLite does not support RIGHT JOIN. Restructure the query with joins.left and swapped operands.\"\n );\n },\n\n // SQLite doesn't support FULL OUTER JOIN (before 3.39, and driver support varies).\n full: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"SQLite does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.\"\n );\n },\n\n // SQLite does NOT support LATERAL joins\n // These methods should never be called - query engine should check capability first\n lateral: (_subquery: Sql, _alias: string): Sql => {\n throw new Error(\n \"SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.\"\n );\n },\n\n lateralLeft: (_subquery: Sql, _alias: string): Sql => {\n throw new Error(\n \"SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.\"\n );\n },\n};\n\nconst SQLITE_CAPABILITIES = {\n supportsReturning: true, // SQLite 3.35+\n // FALSE IN FACT, and it read `true` until the Phase 8 fold gave the flag its\n // first reader (query-performance-plan Phase 10.1). SQLite's `WITH` grammar\n // admits a SELECT and nothing else: measured on SQLite 3.51.2, each of\n // `WITH x AS (UPDATE …/INSERT …/DELETE … RETURNING …) SELECT * FROM x` is a\n // parse error (`near \"UPDATE\": syntax error`). Kept as a capability rather\n // than deleted because Phase 8's `WITH u AS (UPDATE … RETURNING *) SELECT …`\n // fold reads it to decide whether it may emit at all.\n supportsCteWithMutations: false,\n supportsFullOuterJoin: false,\n supportsLateralJoins: false, // SQLite does not support LATERAL joins\n supportsVector: false,\n supportsUpsertWhere: true, // SQLite supports WHERE in ON CONFLICT (3.24+)\n supportsTargetedUpsert: true, // ON CONFLICT (cols) arbitrates on those cols\n supportsMutationTargetInSubquery: true,\n // UPDATE/DELETE ... LIMIT needs SQLITE_ENABLE_UPDATE_DELETE_LIMIT, which is\n // off in the builds this project targets (better-sqlite3, libSQL, D1).\n supportsMutationRowLimit: false,\n supportsRowLocks: false,\n};\n\nconst SQLITE_RESULT: AdapterResultParser = {\n // SQLite has no exact decimal type: a decimal column IS its unscaled\n // integer coefficient, and every projection casts it to text before a\n // driver turns an int64 into a double. The result boundary cannot tell the\n // two vocabularies apart by inspection, so the promise is declared here.\n decimalRepresentation: \"coefficient\",\n\n // A decimal LIST is TEXT holding a JSON array of those same coefficients,\n // stated separately because the two facts are separate: a dialect can spell\n // its scalar decimals exactly and still have no exact decimal inside JSON.\n decimalListRepresentation: \"coefficient\",\n\n // The same reading the `dateTime` literal above lowers through, so a column\n // is read back in the vocabulary it was written in.\n dateTimeRepresentation: sqliteDateTimePhysicalForm,\n\n // Derived from the ONE storage owner, so the column the migration creates\n // and the value this reads back cannot be two decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"sqlite\")?.representation ?? \"text\",\n\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n\n parseField: (\n _value: unknown,\n _scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n};\n\nconst SQLITE_IDENTIFIERS = createIdentifiers(quoteIdent);\n\nconst SQLITE_CLAUSES = createStandardClauses();\n\nconst SQLITE_FILTERS = createRelationFilters();\n\nconst SQLITE_SUBQUERIES = createSubqueries(quoteIdent);\n\nconst SQLITE_CTE = createCteBuilders(quoteIdent);\n\nconst SQLITE_SET_OPERATIONS = createSetOperations();\n\nconst SQLITE_RAW = createRawSql();\n\nexport class SQLiteAdapter implements DatabaseAdapter {\n constructor({ temporaryObjects = true }: SQLiteAdapterOptions = {}) {\n installGeoPointSql(this, this.geoPoint);\n // Only batches read the reference-table SQL, so it is built on first use.\n let batchRefs: BatchReferenceSqlAdapter | undefined;\n const createBatchRefs = () => this.#createBatchRefs(temporaryObjects);\n installAdapterInternals(this, {\n get batchRefs() {\n batchRefs ??= createBatchRefs();\n return batchRefs;\n },\n constraints: sqliteConstraintIdentities,\n select: this.#assemble.select,\n });\n }\n\n raw = SQLITE_RAW;\n\n identifiers = { ...SQLITE_IDENTIFIERS };\n\n literals = { ...SQLITE_LITERALS };\n\n operators = { ...SQLITE_OPERATORS };\n\n expressions = { ...SQLITE_EXPRESSIONS };\n\n aggregates = { ...SQLITE_AGGREGATES };\n\n // SQLite 3.38+ JSON functions\n json = { ...SQLITE_JSON };\n\n arrays = { ...SQLITE_ARRAYS };\n\n // SQLite parses NULLS FIRST/LAST natively since 3.30 (2019-10-04), which is\n // below this adapter's documented 3.35+ floor. The `(col IS NULL)` emulation\n // this replaces was an extra leading sort key, and an index can never supply\n // a sort key that is an expression: on a 100,000-row table with an index over\n // the sort columns, the emulated spelling planned `SCAN t | USE TEMP B-TREE\n // FOR ORDER BY` at 3.356 ms per page and the native one plans `SCAN t USING\n // INDEX` at 0.005 ms. MySQL keeps the emulation — it has no native syntax at\n // any version.\n orderBy = { ...SQLITE_ORDER_BY };\n\n clauses = { ...SQLITE_CLAUSES };\n\n set = { ...SQLITE_SET };\n\n filters = { ...SQLITE_FILTERS };\n\n subqueries = { ...SQLITE_SUBQUERIES };\n\n // SQLite has no bare OFFSET; LIMIT -1 means \"no limit\"\n noLimitValue = sql.raw(\"-1\");\n\n readonly #assemble = {\n select: (parts: QueryParts): Sql => {\n // SQLite doesn't support DISTINCT ON natively\n // Simulate using ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)\n if (parts.distinct) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape,\n this.noLimitValue\n );\n }\n\n // SQLite uses database-level locking, so FOR UPDATE is a no-op\n // (ignoring parts.forUpdate intentionally)\n return assembleSelectQuery(sql`SELECT ${parts.columns}`, parts, {\n forUpdate: \"omit\",\n noLimitValue: this.noLimitValue,\n });\n },\n };\n\n cte = { ...SQLITE_CTE };\n\n mutations = { ...SQLITE_MUTATIONS };\n\n assertions = { ...SQLITE_ASSERTIONS };\n\n joins = { ...SQLITE_JOINS };\n\n setOperations = { ...SQLITE_SET_OPERATIONS };\n\n capabilities = { ...SQLITE_CAPABILITIES };\n\n lastInsertId = (): Sql => sql.raw(\"last_insert_rowid()\");\n\n // The scratch is a TEMP table wherever the transport admits one, so it never\n // enters the user's database file. Where it does not (D1), it is an ordinary\n // table in `main`: created once, kept, and EMPTY between batches — every\n // batch deletes the rows it stored, keyed by its own batch id, inside that\n // same batch, and a batch that fails rolls its rows back with it. The table\n // itself persists; SQLite migration introspection leaves it out of the\n // snapshot (`src/migrations/drivers/sqlite/introspect.ts`).\n #createBatchRefs(temporaryObjects: boolean): BatchReferenceSqlAdapter {\n const table = sql.raw(quoteIdent(BATCH_REFS_TABLE));\n const create = sql.raw(\n temporaryObjects\n ? \"CREATE TEMP TABLE IF NOT EXISTS\"\n : \"CREATE TABLE IF NOT EXISTS\"\n );\n return createOnConflictBatchRefs({\n table,\n batchIdColumn: sql.raw('\"batch_id\"'),\n keyColumn: sql.raw('\"ref_key\"'),\n valueColumn: sql.raw('\"ref_value\"'),\n createTable: sql`${create} ${table} (\"batch_id\" TEXT NOT NULL, \"ref_key\" TEXT NOT NULL, \"ref_value\" TEXT, PRIMARY KEY (\"batch_id\", \"ref_key\"))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS TEXT)`,\n lastInsertId: () => this.lastInsertId(),\n });\n }\n\n vector = unsupportedVector;\n\n readonly geoPoint: GeoPointSql = (() => {\n const longitude = (point: Sql): Sql =>\n this.json.numberAtPath(point, [\"longitude\"]);\n const latitude = (point: Sql): Sql =>\n this.json.numberAtPath(point, [\"latitude\"]);\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`json_object('longitude', ${this.json.document(this.json.number(pointLongitude))}, 'latitude', ${this.json.document(this.json.number(pointLatitude))})`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators\n ),\n };\n })();\n\n result: AdapterResultParser = { ...SQLITE_RESULT };\n}\n"],"mappings":"4xBAyEA,MAAM,EAAa,GAAuB,IAAI,CASxC,EAA0C,CAC9C,UAAW,EAAQ,IAAgB,CAAG,IAAI,EAAE,KAAK,EAAE,GACnD,WAAY,EAAQ,IAAgB,CAAG,IAAI,EAAE,KAAK,EAAE,GACrD,CAMD,SAAS,uBAAuB,EAAyC,CACvE,IAAM,EAAY,EAA4B,EAAY,CAC1D,GAAI,EAAY,GAAI,OAAO,EACvB,OAAY,IAIhB,OAHmB,EAAY,WAAW,IAAI,CAC1C,EAAY,MAAM,EAAE,EAAI,sBACxB,GAAe,uBACC,EAAY,IAAA,GA4BlC,MAAM,EAA4BA,EAAI,IAAI,sBAAsB,CAqB1D,oBAAuB,GAC3BA,EAAI,IAAI,IAA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EAASA,EAAI,IACjB,EACI,kCACA,6BACL,CACD,OAAO,EAA0B,CAC/B,QACA,cAAeA,EAAI,IAAI,aAAa,CACpC,UAAWA,EAAI,IAAI,YAAY,CAC/B,YAAaA,EAAI,IAAI,cAAc,CACnC,YAAa,CAAG,GAAG,EAAO,GAAG,EAAM,6GACnC,UAAY,GAAa,CAAG,SAAS,EAAS,YAC9C,iBAAoB,KAAK,cAAc,CACxC,CAAC,CAGJ,OAAS,EAET,cAAwC,CACtC,IAAM,UAAa,GACjB,KAAK,KAAK,aAAa,EAAO,CAAC,YAAY,CAAC,CACxC,SAAY,GAChB,KAAK,KAAK,aAAa,EAAO,CAAC,WAAW,CAAC,CAC7C,MAAO,CACL,OAAQ,EAAgB,IACtB,CAAG,4BAA4B,KAAK,KAAK,SAAS,KAAK,KAAK,OAAO,EAAe,CAAC,CAAC,gBAAgB,KAAK,KAAK,SAAS,KAAK,KAAK,OAAO,EAAc,CAAC,CAAC,GAC1J,UACA,SACA,GAAG,EACD,UACA,SACA,KAAK,UACN,CACF,IACC,CAEJ,OAA8B,CAAE,GAAG,GAAe"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"standard-sql-Bk4RZPqJ.mjs","names":["sql"],"sources":["../src/sql/identifiers.ts","../src/adapters/shared/standard-sql.ts"],"sourcesContent":["/**\n * Identifier text primitives.\n *\n * Quoting one name for a dialect, and composing a namespace-qualified object\n * name, are string concerns with no `Sql` involvement: runtime adapters wrap the\n * result in `Sql`, migration drivers splice it into DDL text. Both pass their\n * own quoter — the two differ in escape semantics and null handling — so what is\n * shared here is the composition rule alone, and it has one owner.\n */\n\n/** Quote a single identifier for the dialect: `\"name\"` or `` `name` ``. */\nexport type IdentifierQuoter = (name: string) => string;\n\n/** Build an identifier quoter that doubles embedded quote characters to prevent SQL injection. */\nexport const createIdentifierQuoter =\n (quoteChar: '\"' | \"`\"): IdentifierQuoter =>\n (name: string): string => {\n const escaped =\n name.indexOf(quoteChar) === -1\n ? name\n : name.replaceAll(quoteChar, quoteChar + quoteChar);\n return quoteChar + escaped + quoteChar;\n };\n\n/**\n * The one qualification rule. A present namespace contributes a quoted prefix;\n * an absent one contributes nothing, which is what unbound MySQL and every\n * SQLite adapter mean.\n */\nconst qualifiedPrefix = (\n quoteIdentifier: IdentifierQuoter,\n namespace: string\n): string => `${quoteIdentifier(namespace)}.`;\n\n/**\n * Compose one namespace-qualified object name. The namespace must already be\n * normalized: this primitive validates nothing, holds nothing, and returns text\n * for exactly one object.\n */\nexport const renderQualifiedIdentifier = (\n quoteIdentifier: IdentifierQuoter,\n namespace: string | undefined,\n object: string\n): string =>\n namespace === undefined\n ? quoteIdentifier(object)\n : qualifiedPrefix(quoteIdentifier, namespace) + quoteIdentifier(object);\n\n/**\n * Bind one namespace so its prefix is quoted once per adapter rather than once\n * per rendered statement. The returned function renders exactly what\n * `renderQualifiedIdentifier` would for the same namespace.\n */\nexport const createQualifiedIdentifierRenderer = (\n quoteIdentifier: IdentifierQuoter,\n namespace: string | undefined\n): IdentifierQuoter => {\n if (namespace === undefined) {\n return quoteIdentifier;\n }\n const prefix = qualifiedPrefix(quoteIdentifier, namespace);\n return (object: string): string => prefix + quoteIdentifier(object);\n};\n","import { Sql, sql } from \"@sql\";\nimport {\n createQualifiedIdentifierRenderer,\n type IdentifierQuoter,\n} from \"../../sql/identifiers\";\nimport type { CastType, DatabaseAdapter } from \"../database-adapter\";\n\ntype StandardLiterals = Pick<\n DatabaseAdapter[\"literals\"],\n \"value\" | \"null\" | \"list\"\n>;\n\ntype ComparisonOperators = Pick<\n DatabaseAdapter[\"operators\"],\n \"eq\" | \"neq\" | \"lt\" | \"lte\" | \"gt\" | \"gte\"\n>;\n\ntype NullOperators = Pick<DatabaseAdapter[\"operators\"], \"isNull\" | \"isNotNull\">;\n\ntype RangeOperators = Pick<\n DatabaseAdapter[\"operators\"],\n \"between\" | \"notBetween\"\n>;\n\ntype ExistenceOperators = Pick<\n DatabaseAdapter[\"operators\"],\n \"exists\" | \"notExists\"\n>;\n\ntype DirectionOrderBy = Pick<DatabaseAdapter[\"orderBy\"], \"asc\" | \"desc\">;\n\ntype NumericSetOperations = Pick<\n DatabaseAdapter[\"set\"],\n \"assign\" | \"increment\" | \"decrement\"\n>;\n\ntype MutationCommands = Pick<DatabaseAdapter[\"mutations\"], \"update\" | \"delete\">;\n\nexport const createRawSql = (): DatabaseAdapter[\"raw\"] => {\n return (sqlString: string): Sql => sql.raw(sqlString);\n};\n\n/**\n * JSON-serialize a value for dialects that store lists/JSON as JSON text\n * (MySQL, SQLite). BigInt has no JSON representation, so it serializes as a\n * string; the result parser converts it back via the scalar's bigint type.\n */\nexport const stringifyJson = (value: unknown): string =>\n JSON.stringify(value, (_key, v) =>\n typeof v === \"bigint\" ? v.toString() : v\n );\n\nconst JSON_PATH_ARRAY_INDEX = /^\\d+$/;\n\n/**\n * Build a MySQL/SQLite JSONPath string from path segments: '$' plus `[N]`\n * for integer segments (array indices) and `.\"seg\"` for object keys.\n * Keys are JSON-string-escaped so quotes/dots/backslashes in a segment\n * cannot alter the path structure; the result is bound as a parameter.\n */\nexport const buildJsonPath = (path: string[]): string => {\n let jsonPath = \"$\";\n for (const segment of path) {\n jsonPath += JSON_PATH_ARRAY_INDEX.test(segment)\n ? `[${segment}]`\n : `.${JSON.stringify(segment)}`;\n }\n return jsonPath;\n};\n\nexport const createStandardLiterals = (): StandardLiterals => ({\n value: (v: unknown): Sql => sql`${v}`,\n null: (): Sql => sql.raw(\"NULL\"),\n list: (values: Sql[]): Sql => {\n if (values.length === 0) return sql.raw(\"()\");\n return sql`(${sql.join(values, \", \")})`;\n },\n});\n\nexport const createComparisonOperators = (): ComparisonOperators => ({\n eq: (left: Sql, right: Sql): Sql => sql`${left} = ${right}`,\n neq: (left: Sql, right: Sql): Sql => sql`${left} <> ${right}`,\n lt: (left: Sql, right: Sql): Sql => sql`${left} < ${right}`,\n lte: (left: Sql, right: Sql): Sql => sql`${left} <= ${right}`,\n gt: (left: Sql, right: Sql): Sql => sql`${left} > ${right}`,\n gte: (left: Sql, right: Sql): Sql => sql`${left} >= ${right}`,\n});\n\nexport const createNullOperators = (): NullOperators => ({\n isNull: (expr: Sql): Sql => sql`${expr} IS NULL`,\n isNotNull: (expr: Sql): Sql => sql`${expr} IS NOT NULL`,\n});\n\nexport const createRangeOperators = (): RangeOperators => ({\n between: (column: Sql, min: Sql, max: Sql): Sql =>\n sql`${column} BETWEEN ${min} AND ${max}`,\n notBetween: (column: Sql, min: Sql, max: Sql): Sql =>\n sql`${column} NOT BETWEEN ${min} AND ${max}`,\n});\n\nexport const createExistenceOperators = (): ExistenceOperators => ({\n exists: (subquery: Sql): Sql => sql`EXISTS (${subquery})`,\n notExists: (subquery: Sql): Sql => sql`NOT EXISTS (${subquery})`,\n});\n\ntype StandardAggregates = Omit<\n DatabaseAdapter[\"aggregates\"],\n \"decimalAvg\" | \"decimalSumOperandPrecision\"\n>;\n\n/**\n * The aggregate functions every dialect spells identically. `decimalAvg` is\n * deliberately absent: an exact decimal average is derived from `SUM` and\n * `COUNT` in the column's own physical domain, which is the one thing the three\n * dialects do not agree on, so each adapter states it.\n * `decimalSumOperandPrecision` is absent because each dialect also owns exact\n * admission of an operand compared with a widened sum.\n *\n * `infinity` is the dialect's infinite double literal; MySQL has none.\n */\nexport const createAggregateFunctions = (\n infinity?: string\n): StandardAggregates => ({\n count: (expr?: Sql): Sql =>\n expr ? sql`COUNT(${expr})` : sql.raw(\"COUNT(*)\"),\n countDistinct: (expr: Sql): Sql => sql`COUNT(DISTINCT ${expr})`,\n sum: (expr: Sql): Sql => sql`SUM(${expr})`,\n numberSum: (expr: Sql) => {\n const high = sql`SUM(CASE WHEN ABS(${expr}) >= 1e-288 THEN ${expr} / 4294967296.0 / 4294967296.0 END)`;\n const low = sql`SUM(CASE WHEN ABS(${expr}) < 1e-288 THEN ${expr} END)`;\n // The reader's join in SQL: scaling `high` back by 2^64 is exact below\n // 2^960 and leaves the double range from there, where this multiplies\n // nothing — PostgreSQL and MySQL raise on an overflowing product. Without\n // an infinite double (MySQL) the overflow clamps to the largest finite\n // one, which a `having` operand of exactly that value cannot tell apart,\n // and `high` then sorts an infinite sum past a clamped one.\n const bound = sql.raw(infinity ?? \"1.7976931348623157e308\");\n const value = sql`CASE WHEN ${high} IS NULL THEN ${low} WHEN ABS(${high}) < 9.7453140114e288 THEN ${high} * 4294967296.0 * 4294967296.0 + COALESCE(${low}, 0) WHEN ${high} > 0 THEN ${bound} ELSE -${bound} END`;\n return {\n parts: [high, low] as const,\n value,\n order: infinity ? [value] : [value, high],\n };\n },\n avg: (expr: Sql): Sql => sql`AVG(${expr})`,\n min: (expr: Sql): Sql => sql`MIN(${expr})`,\n max: (expr: Sql): Sql => sql`MAX(${expr})`,\n});\n\n/** The widened precision carried by one trusted coefficient spelling. */\nexport function decimalCoefficientPrecision(coefficient: string): number {\n return coefficient.startsWith(\"-\")\n ? coefficient.length - 1\n : coefficient.length;\n}\n\n/** Exact-decimal aggregate operand admission for precision-bounded dialects. */\nexport function createDecimalSumOperandPrecision(\n maxPrecision: number\n): (coefficient: string) => number | undefined {\n return (coefficient) => {\n const precision = decimalCoefficientPrecision(coefficient);\n return precision <= maxPrecision ? precision : undefined;\n };\n}\n\nexport const createDirectionOrderBy = (): DirectionOrderBy => ({\n asc: (column: Sql): Sql => sql`${column} ASC`,\n desc: (column: Sql): Sql => sql`${column} DESC`,\n});\n\nconst directionKeyword = (direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\" ? sql.raw(\"DESC\") : sql.raw(\"ASC\");\n\n/**\n * NULLS FIRST/LAST emulation for dialects without native support\n * (MySQL, SQLite): prepend an IS NULL sort key. IS NULL yields 1 for\n * NULL rows, so DESC puts them first and ASC puts them last.\n */\nexport const createEmulatedNullsOrderBy = (): Pick<\n DatabaseAdapter[\"orderBy\"],\n \"nullsFirst\" | \"nullsLast\"\n> => ({\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n sql`(${column} IS NULL) DESC, ${column} ${directionKeyword(direction)}`,\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n sql`(${column} IS NULL) ASC, ${column} ${directionKeyword(direction)}`,\n});\n\nexport const createStandardClauses = (): DatabaseAdapter[\"clauses\"] => ({\n select: (columns: Sql): Sql => sql`SELECT ${columns}`,\n selectDistinct: (columns: Sql): Sql => sql`SELECT DISTINCT ${columns}`,\n from: (table: Sql): Sql => sql`FROM ${table}`,\n where: (condition: Sql): Sql => sql`WHERE ${condition}`,\n orderBy: (orders: Sql): Sql => sql`ORDER BY ${orders}`,\n limit: (count: Sql): Sql => sql`LIMIT ${count}`,\n offset: (count: Sql): Sql => sql`OFFSET ${count}`,\n groupBy: (columns: Sql): Sql => sql`GROUP BY ${columns}`,\n having: (condition: Sql): Sql => sql`HAVING ${condition}`,\n});\n\n/**\n * The native arithmetic every dialect shares.\n *\n * `increment`/`decrement` are complete here for EVERY scalar including decimal:\n * addition of two values already in the column's domain — logical decimals on\n * PostgreSQL/MySQL, unscaled coefficients at the same scale on SQLite — creates\n * no digit beyond that domain and therefore never rounds.\n *\n * `multiply` and `divide` do create such digits, so each adapter overrides them\n * to route a decimal target through the shared half-even rule.\n */\nexport const createNumericSetOperations = (): NumericSetOperations => ({\n assign: (column: Sql, value: Sql): Sql => sql`${column} = ${value}`,\n increment: (column: Sql, by: Sql): Sql => sql`${column} = ${column} + ${by}`,\n decrement: (column: Sql, by: Sql): Sql => sql`${column} = ${column} - ${by}`,\n});\n\nexport const createRelationFilters = (): DatabaseAdapter[\"filters\"] => ({\n some: (subquery: Sql): Sql => sql`EXISTS (${subquery})`,\n every: (subquery: Sql): Sql => sql`NOT EXISTS (${subquery})`,\n none: (subquery: Sql): Sql => sql`NOT EXISTS (${subquery})`,\n is: (subquery: Sql): Sql => sql`EXISTS (${subquery})`,\n isNot: (subquery: Sql): Sql => sql`NOT EXISTS (${subquery})`,\n});\n\nexport const createMutationCommands = (): MutationCommands => ({\n update: (table: Sql, sets: Sql, where?: Sql): Sql => {\n if (where) {\n return sql`UPDATE ${table} SET ${sets} WHERE ${where}`;\n }\n return sql`UPDATE ${table} SET ${sets}`;\n },\n delete: (table: Sql, where?: Sql): Sql => {\n if (where) {\n return sql`DELETE FROM ${table} WHERE ${where}`;\n }\n return sql`DELETE FROM ${table}`;\n },\n});\n\nexport const createSetOperations = (): DatabaseAdapter[\"setOperations\"] => ({\n union: (...queries: Sql[]): Sql => sql.join(queries, \" UNION \"),\n unionAll: (...queries: Sql[]): Sql => sql.join(queries, \" UNION ALL \"),\n intersect: (...queries: Sql[]): Sql => sql.join(queries, \" INTERSECT \"),\n except: (left: Sql, right: Sql): Sql => sql`${left} EXCEPT ${right}`,\n});\n\n// ============================================================\n// Dialect-parameterized factories: identical grammar across\n// adapters, differing only in the identifier quote character.\n// ============================================================\n\n/**\n * `namespace` is the adapter's prevalidated database namespace, or `undefined`\n * for the unqualified dialects. It is quoted once here, at adapter\n * construction — `table()` runs once per persistent table per compiled\n * statement and must not re-quote it.\n */\nexport const createIdentifiers = (\n quoteIdent: IdentifierQuoter,\n namespace?: string\n): DatabaseAdapter[\"identifiers\"] => {\n const qualify = createQualifiedIdentifierRenderer(quoteIdent, namespace);\n return {\n escape: (name: string): Sql => sql.raw(quoteIdent(name)),\n\n column: (alias: string, field: string): Sql => {\n const identifier = alias\n ? `${quoteIdent(alias)}.${quoteIdent(field)}`\n : quoteIdent(field);\n return sql.raw(identifier);\n },\n\n table: (tableName: string, alias?: string): Sql => {\n const qualified = qualify(tableName);\n return sql.raw(\n alias === undefined ? qualified : `${qualified} AS ${quoteIdent(alias)}`\n );\n },\n\n aliased: (expression: Sql, alias: string): Sql =>\n new Sql([\"\", ` AS ${quoteIdent(alias)}`], [expression]),\n };\n};\n\nexport const createSubqueries = (\n quoteIdent: IdentifierQuoter\n): DatabaseAdapter[\"subqueries\"] => ({\n scalar: (query: Sql): Sql => sql`(${query})`,\n\n correlate: (query: Sql, alias: string): Sql =>\n sql`(${query}) AS ${sql.raw(quoteIdent(alias))}`,\n\n existsCheck: (from: Sql, where: Sql): Sql =>\n sql`SELECT 1 FROM ${from} WHERE ${where}`,\n});\n\nexport const createCteBuilders = (\n quoteIdent: IdentifierQuoter\n): DatabaseAdapter[\"cte\"] => ({\n with: (definitions: { name: string; query: Sql }[]): Sql => {\n const defs = definitions.map(\n ({ name, query }) => sql`${sql.raw(quoteIdent(name))} AS (${query})`\n );\n return sql`WITH ${sql.join(defs, \", \")}`;\n },\n\n recursive: (\n name: string,\n anchor: Sql,\n recursive: Sql,\n union: \"all\" | \"distinct\" = \"all\"\n ): Sql => {\n const unionKeyword =\n union === \"all\" ? sql.raw(\"UNION ALL\") : sql.raw(\"UNION\");\n return sql`WITH RECURSIVE ${sql.raw(quoteIdent(name))} AS (\n ${anchor}\n ${unionKeyword}\n ${recursive}\n )`;\n },\n});\n\nexport const createInsertStatement =\n (quoteIdent: IdentifierQuoter): DatabaseAdapter[\"mutations\"][\"insert\"] =>\n (\n table: Sql,\n columns: string[],\n source: Sql[][] | { readonly select: Sql },\n prefix?: Sql\n ): Sql => {\n const cols = columns.map((c) => sql.raw(quoteIdent(c)));\n const body = Array.isArray(source)\n ? sql`VALUES ${sql.join(\n source.map((row) => sql`(${sql.join(row, \", \")})`),\n \", \"\n )}`\n : source.select;\n const prefixPart = prefix ? sql`${prefix} ` : sql``;\n return sql`INSERT ${prefixPart}INTO ${table} (${sql.join(\n cols,\n \", \"\n )}) ${body}`;\n };\n\n/**\n * Standard ON CONFLICT grammar shared by PostgreSQL and SQLite.\n * MySQL's ON DUPLICATE KEY UPDATE is a different grammar with different\n * semantics — it stays in the MySQL adapter.\n */\nexport const createOnConflictBuilders = (): Pick<\n DatabaseAdapter[\"mutations\"],\n \"onConflict\" | \"onConflictUpdate\" | \"skipDuplicates\"\n> => ({\n onConflict: (target: Sql | null, action: Sql, targetWhere?: Sql): Sql => {\n if (target) {\n if (targetWhere) {\n // ON CONFLICT (id) WHERE <targetWhere> DO UPDATE ...\n return sql`ON CONFLICT (${target}) WHERE ${targetWhere} DO ${action}`;\n }\n return sql`ON CONFLICT (${target}) DO ${action}`;\n }\n return sql`ON CONFLICT DO ${action}`;\n },\n\n onConflictUpdate: (sets: Sql, setWhere?: Sql): Sql => {\n if (setWhere) {\n // UPDATE SET x = y WHERE <setWhere>\n return sql`UPDATE SET ${sets} WHERE ${setWhere}`;\n }\n return sql`UPDATE SET ${sets}`;\n },\n\n // The UNTARGETED skip, and the only caller left is top-level `createMany`,\n // whose `skipDuplicates: true` means \"any unique constraint\". Junction\n // membership inserts want the opposite — only an exact repeat of the complete\n // membership key — and reach `onConflict` above with that key as the target.\n skipDuplicates: () => ({\n prefix: sql``,\n suffix: sql`ON CONFLICT DO NOTHING`,\n }),\n});\n\nexport const createMembershipOperators = (): Pick<\n DatabaseAdapter[\"operators\"],\n \"in\" | \"notIn\"\n> => ({\n in: (column: Sql, values: Sql): Sql => sql`${column} IN ${values}`,\n notIn: (column: Sql, values: Sql): Sql => sql`${column} NOT IN ${values}`,\n});\n\n/**\n * AND/OR/NOT with vacuous-case literals: the dialect's TRUE for an empty\n * AND and FALSE for an empty OR (pass the adapter's literals.true/false).\n */\nexport const createLogicalOperators = (\n vacuousTrue: () => Sql,\n vacuousFalse: () => Sql\n): Pick<DatabaseAdapter[\"operators\"], \"and\" | \"or\" | \"not\"> => ({\n and: (...conditions: Sql[]): Sql => {\n if (conditions.length === 0) return vacuousTrue();\n if (conditions.length === 1) return conditions[0]!;\n return sql`(${sql.join(conditions, \" AND \")})`;\n },\n\n or: (...conditions: Sql[]): Sql => {\n if (conditions.length === 0) return vacuousFalse();\n if (conditions.length === 1) return conditions[0]!;\n return sql`(${sql.join(conditions, \" OR \")})`;\n },\n\n not: (condition: Sql): Sql => sql`NOT (${condition})`,\n});\n\nexport const createCommonExpressions = (): Pick<\n DatabaseAdapter[\"expressions\"],\n | \"caseWhen\"\n | \"add\"\n | \"subtract\"\n | \"multiply\"\n | \"divide\"\n | \"upper\"\n | \"lower\"\n | \"coalesce\"\n> => ({\n caseWhen: (branches, otherwise): Sql =>\n branches.length === 0\n ? otherwise\n : sql`CASE ${sql.join(\n branches.map(\n (branch) => sql`WHEN ${branch.when} THEN ${branch.then}`\n ),\n \" \"\n )} ELSE ${otherwise} END`,\n add: (left: Sql, right: Sql): Sql => sql`(${left} + ${right})`,\n subtract: (left: Sql, right: Sql): Sql => sql`(${left} - ${right})`,\n multiply: (left: Sql, right: Sql): Sql => sql`(${left} * ${right})`,\n divide: (left: Sql, right: Sql): Sql => sql`(${left} / ${right})`,\n upper: (expr: Sql): Sql => sql`UPPER(${expr})`,\n lower: (expr: Sql): Sql => sql`LOWER(${expr})`,\n coalesce: (...exprs: Sql[]): Sql => sql`COALESCE(${sql.join(exprs, \", \")})`,\n});\n\nexport const createCastExpression =\n (typeMap: Record<CastType, string>): DatabaseAdapter[\"expressions\"][\"cast\"] =>\n (expr: Sql, type: CastType): Sql =>\n sql`CAST(${expr} AS ${sql.raw(typeMap[type])})`;\n\nexport const createCoreJoins = (): Pick<\n DatabaseAdapter[\"joins\"],\n \"inner\" | \"left\" | \"right\" | \"cross\"\n> => ({\n inner: (table: Sql, condition: Sql): Sql =>\n sql`INNER JOIN ${table} ON ${condition}`,\n\n left: (table: Sql, condition: Sql): Sql =>\n sql`LEFT JOIN ${table} ON ${condition}`,\n\n right: (table: Sql, condition: Sql): Sql =>\n sql`RIGHT JOIN ${table} ON ${condition}`,\n\n cross: (table: Sql): Sql => sql`CROSS JOIN ${table}`,\n});\n\nexport const createLateralJoins = (\n quoteIdent: IdentifierQuoter\n): Pick<DatabaseAdapter[\"joins\"], \"lateral\" | \"lateralLeft\"> => ({\n lateral: (subquery: Sql, alias: string): Sql =>\n sql`JOIN LATERAL (${subquery}) AS ${sql.raw(quoteIdent(alias))} ON TRUE`,\n\n lateralLeft: (subquery: Sql, alias: string): Sql =>\n sql`LEFT JOIN LATERAL (${subquery}) AS ${sql.raw(quoteIdent(alias))} ON TRUE`,\n});\n\n/**\n * Escape a user value so a SQL `LIKE` pattern matches it literally.\n *\n * `%`, `_` and the escape character itself become escaped; every other\n * character is left alone. The caller appends its own wildcard and must emit\n * a matching `ESCAPE` clause — backslash is only the escape character because\n * every `ESCAPE` clause in this codebase spells backslash.\n */\nexport const escapeLikeLiteral = (value: string): string =>\n value.replace(/[\\\\%_]/g, (char) => `\\\\${char}`);\n\n/**\n * Escape a user value so a SQLite `GLOB` pattern matches it literally.\n *\n * GLOB has no `ESCAPE` clause, so a metacharacter is quoted by wrapping it in\n * a one-character class: `*` becomes `[*]`. Only `*`, `?` and `[` need it —\n * a `]` outside a class is already literal in SQLite's GLOB, and backslash is\n * not a GLOB metacharacter at all.\n */\nexport const escapeGlobLiteral = (value: string): string =>\n value.replace(/[*?[]/g, (char) => `[${char}]`);\n"],"mappings":"uFAcA,MAAa,uBACV,GACA,GAKQ,GAHL,EAAK,QAAQ,EAAU,GAAK,GACxB,EACA,EAAK,WAAW,EAAW,EAAY,EAAU,EAC1B,EAQ3B,iBACJ,EACA,IACW,GAAG,EAAgB,EAAU,CAAC,GAO9B,2BACX,EACA,EACA,IAEA,IAAc,IAAA,GACV,EAAgB,EAAO,CACvB,gBAAgB,EAAiB,EAAU,CAAG,EAAgB,EAAO,CAO9D,mCACX,EACA,IACqB,CACrB,GAAI,IAAc,IAAA,GAChB,OAAO,EAET,IAAM,EAAS,gBAAgB,EAAiB,EAAU,CAC1D,MAAQ,IAA2B,EAAS,EAAgB,EAAO,ECvBxD,iBACH,GAA2BA,EAAI,IAAI,EAAU,CAQ1C,cAAiB,GAC5B,KAAK,UAAU,GAAQ,EAAM,IAC3B,OAAO,GAAM,SAAW,EAAE,UAAU,CAAG,EACxC,CAEG,EAAwB,QAQjB,cAAiB,GAA2B,CACvD,IAAI,EAAW,IACf,IAAK,IAAM,KAAW,EACpB,GAAY,EAAsB,KAAK,EAAQ,CAC3C,IAAI,EAAQ,GACZ,IAAI,KAAK,UAAU,EAAQ,GAEjC,OAAO,GAG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AAY,IAClB,CAAG,cAAc,EAAM,MAAM,IAE/B,MAAO,EAAY,IACjB,CAAG,aAAa,EAAM,MAAM,IAE9B,OAAQ,EAAY,IAClB,CAAG,cAAc,EAAM,MAAM,IAE/B,MAAQ,GAAoB,CAAG,cAAc,IAC9C,EAEY,mBACX,IAC+D,CAC/D,SAAU,EAAe,IACvB,CAAG,iBAAiB,EAAS,OAAOA,EAAI,IAAI,EAAW,EAAM,CAAC,CAAC,UAEjE,aAAc,EAAe,IAC3B,CAAG,sBAAsB,EAAS,OAAOA,EAAI,IAAI,EAAW,EAAM,CAAC,CAAC,UACvE,EAUY,kBAAqB,GAChC,EAAM,QAAQ,UAAY,GAAS,KAAK,IAAO,CAUpC,kBAAqB,GAChC,EAAM,QAAQ,SAAW,GAAS,IAAI,EAAK,GAAG"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{t}from"./validation-Dk9Q_-C7.mjs";import{t as n}from"./identifier-hQCs8M1n.mjs";const r=Symbol.for(`viborm.field-ref`);function isFieldRef(e){if(typeof e!=`object`||!e)return!1;let t=e[r];return typeof t==`object`&&!!t}function fieldRefPayload(e){return e[r]}function formatFieldRef(e){let t=fieldRefPayload(e);return`${t.model}.${t.field}`}function createFieldRef(e,t,n,i){return Object.freeze({[r]:Object.freeze({model:e,field:t,type:n,list:i})})}const UNKNOWN_FIELD=(e,t,n)=>Error(`Unknown scalar field "${t}" on model '${e}'. Known fields: ${n.join(`, `)}.`);function createModelFieldRefs(e,t){let n=new Map,r=t[`~`].state.scalars,i=Object.keys(r).filter(e=>r[e][`~`].state.type!==`point`),a=new Set(i);return new Proxy(Object.create(null),{get(t,o){if(typeof o!=`string`)return;let s=n.get(o);if(s)return s;let c=a.has(o)?r[o]:void 0;if(!c)throw UNKNOWN_FIELD(e,o,i);let l=c[`~`].state,u=createFieldRef(e,o,l.type,l.array);return n.set(o,u),u},has:(e,t)=>typeof t==`string`&&a.has(t),ownKeys:()=>i,getOwnPropertyDescriptor:(e,t)=>typeof t==`string`&&a.has(t)?{enumerable:!0,configurable:!0}:void 0})}const i=Symbol.for(`viborm.json-null`);var JsonNullSentinel=class{[i];kind;constructor(e){this[i]=e,this.kind=e,Object.freeze(this)}toString(){return this.kind}toJSON(){return`viborm.json-null:${this.kind}`}};const a=new JsonNullSentinel(`DbNull`),o=new JsonNullSentinel(`JsonNull`),s=new JsonNullSentinel(`AnyNull`),c=new Set([`DbNull`,`JsonNull`,`AnyNull`]);function isJsonNullSentinel(e){if(typeof e!=`object`||!e)return!1;let t=e[i];return typeof t==`string`&&c.has(t)}function jsonNullKindOf(e){return isJsonNullSentinel(e)?e.kind:void 0}function refuseRelationInput(e,n,r,i){throw new t({kind:`schema-builder`,builder:e,path:n},[{path:n,message:r}],i===void 0?void 0:{cause:i})}function isPlainRecord(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function declaredKeys(e){return Object.keys(e)}function hasExactKeys(e,t){return e.length===t.length&&t.every(t=>e.includes(t))}function readCallerProperty(e,t,n,r){try{return Reflect.get(t,n)}catch(t){refuseRelationInput(e,r,`Could not read relation input '${r}'`,normalizeThrown(t,`Reading relation input '${r}' threw a non-Error value`))}}function normalizeRelationName(e,t){return(typeof t!=`string`||t.length===0)&&refuseRelationInput(e,`name`,`A relation name must be a non-empty string`),t}function normalizeReferentialAction(e,t){if(t===`cascade`||t===`setNull`||t===`restrict`||t===`noAction`)return t;refuseRelationInput(`s.toOne`,e,`A referential action must be one of 'cascade', 'setNull', 'restrict' or 'noAction'`)}function normalizeJunctionAction(e,t){if(t===`cascade`||t===`restrict`||t===`noAction`)return t;refuseRelationInput(`s.toMany`,e,`A junction referential action must be one of 'cascade', 'restrict' or 'noAction'; 'setNull' cannot null a membership-key member`)}function normalizeJunctionActions(e,t){if(typeof t!=`object`||!t){let n=normalizeJunctionAction(e,t);return Object.freeze({source:n,target:n})}isPlainRecord(t)&&hasExactKeys(declaredKeys(t),[`source`,`target`])||refuseRelationInput(`s.toMany`,e,`A junction '${e}' map is a plain record naming exactly 'source' (the foreign key to the declaring model) and 'target' (the foreign key to its target model)`);let side=n=>normalizeJunctionAction(`${e}.${n}`,readCallerProperty(`s.toMany`,t,n,`${e}.${n}`));return Object.freeze({source:side(`source`),target:side(`target`)})}function normalizeJunctionToken(e,t){return n(t)||refuseRelationInput(`s.toMany`,e,`Junction '${e}' must be a valid schema identifier`),t}function normalizeFieldTuple(e,t,n){let[r,...i]=n;return r===void 0&&refuseRelationInput(e,t,`'${t}' requires at least one field key`),new Set(n).size!==n.length&&refuseRelationInput(e,t,`'${t}' cannot repeat a field key in one foreign-key tuple`),[r,...i]}function createTargetSettlement(e){let t=new Map;return n=>{let r=n??``,i=t.get(r);if(i===void 0&&(i=settleTargetOnce(e,n),t.set(r,i)),i.settled===`value`)return i.value;throw i.error}}function settleTargetOnce(e,t){let n=e(t);if(typeof n!=`function`)return{settled:`error`,error:Error(`Relation target getter is not a function`)};try{return{settled:`value`,value:n()}}catch(e){return{settled:`error`,error:normalizeThrown(e,`Relation target getter threw a non-Error value`)}}}function normalizeThrown(e,t){if(e instanceof Error)return e;let n;try{n=typeof e==`symbol`?e.toString():String(e)}catch{n=`<unrenderable non-Error value>`}return Error(`${t}: ${n}`)}export{jsonNullKindOf as _,normalizeFieldTuple as a,formatFieldRef as b,normalizeReferentialAction as c,refuseRelationInput as d,s as f,isJsonNullSentinel as g,JsonNullSentinel as h,isPlainRecord as i,normalizeRelationName as l,o as m,declaredKeys as n,normalizeJunctionActions as o,a as p,hasExactKeys as r,normalizeJunctionToken as s,createTargetSettlement as t,readCallerProperty as u,createModelFieldRefs as v,isFieldRef as x,fieldRefPayload as y};
|
|
2
|
-
//# sourceMappingURL=terminal-C8cq1WWX.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"terminal-C8cq1WWX.mjs","names":[],"sources":["../src/schema/field-ref.ts","../src/schema/json-null.ts","../src/schema/relation/terminal.ts"],"sourcesContent":["/**\n * Field references (Prisma `FieldRef` parity)\n *\n * A field reference is an opaque, symbol-branded token that stands for a COLUMN\n * instead of a bound parameter in a filter operand position:\n *\n * ```ts\n * client.post.findMany({ where: { views: { gt: (ctx) => ctx.fields.likes } } });\n * // -> ... WHERE \"t0\".\"views\" > \"t0\".\"likes\"\n * ```\n *\n * The token is the MECHANISM; the callback is the surface that hands one out —\n * `ctx.fields` is this file's per-model table, built for the model whose filter\n * the operand sits in (see `validation/primitives/operand.ts`). A token held\n * directly is just as valid: it is what the callback returns.\n *\n * The token carries only what both the validation layer and the SQL builders\n * need — the owning model's schema key, the field's schema key, and the field's\n * scalar type — so it can be created without touching the model graph and\n * compared without any registry lookup.\n *\n * Two rules govern it, and each is enforced where it is actually decidable:\n *\n * - TYPE. A reference's scalar type must match the filter operand's scalar\n * type. Decided by the validation layer ({@link file://../validation/primitives/operand.ts}),\n * which knows the operand's type and nothing about models — scalar filter\n * schemas are interned across models by design (see `validation/scalars/intern.ts`).\n *\n * - SAME MODEL. A reference may only be used in a filter on its own model\n * (Prisma's rule: a field reference compares two columns of the SAME row).\n * Decided by the where-builder ({@link file://../query-engine/builders/where-builder.ts}),\n * because \"the model being filtered\" is a property of the QUERY SCOPE, not of\n * the schema: a nested relation `where` re-scopes to the relation's target\n * model while reusing that model's own (interned, model-blind) filter schemas.\n * The builder must resolve the referenced column against the current scope to\n * emit it at all, so the check is intrinsic there, not a duplicated guard. It\n * runs at SQL-build time — before any I/O.\n */\n\nimport type { Model } from \"./model/model\";\nimport type { ScalarType } from \"./scalars/common\";\n\n/**\n * Brand carried by every field reference. `Symbol.for` (not a fresh symbol) so\n * a reference stays recognizable across duplicated module instances.\n */\nexport const FIELD_REF_BRAND: unique symbol = Symbol.for(\"viborm.field-ref\");\n\n/**\n * An opaque reference to a scalar column of `TModel`.\n *\n * `TType` is the field's scalar type; it is what makes an `Int` reference\n * unassignable to a `String` filter operand at the type level.\n */\n/** What a reference knows about its column, held UNDER the brand symbol. */\nexport interface FieldRefPayload<\n TModel extends string = string,\n TType extends ScalarType = ScalarType,\n> {\n /** Schema key of the model owning the field (e.g. `\"post\"`). */\n readonly model: TModel;\n /** Schema key of the field (e.g. `\"likes\"`), NOT the mapped column name. */\n readonly field: string;\n /** Scalar type of the field (e.g. `\"int\"`). */\n readonly type: TType;\n /** Whether the field is a list scalar. List references are not supported. */\n readonly list: boolean;\n}\n\nexport interface FieldRef<\n TModel extends string = string,\n TType extends ScalarType = ScalarType,\n> {\n // The ONLY key, and it is a symbol on purpose. A reference rides operand\n // unions everywhere a filter value goes; if it exposed string-keyed members\n // (`model`, `field`, ...) the editor would offer them as completions inside\n // every filter object literal that admits a reference. The payload lives\n // under the brand so the token contributes NOTHING to those completions.\n readonly [FIELD_REF_BRAND]: FieldRefPayload<TModel, TType>;\n}\n\n/** Any field reference, regardless of model or scalar type. */\nexport type AnyFieldRef = FieldRef<string, ScalarType>;\n\n/**\n * Runtime brand check. Deliberately a plain property probe: it runs once per\n * filter operand, so it must be a single `typeof` plus one symbol lookup.\n */\nexport function isFieldRef(value: unknown): value is AnyFieldRef {\n if (typeof value !== \"object\" || value === null) return false;\n const payload = (value as { [FIELD_REF_BRAND]?: unknown })[FIELD_REF_BRAND];\n return typeof payload === \"object\" && payload !== null;\n}\n\n/** The reference's column facts. The one sanctioned way to read them. */\nexport function fieldRefPayload(ref: AnyFieldRef): FieldRefPayload {\n return ref[FIELD_REF_BRAND];\n}\n\n/** Human-readable spelling of a reference, for error messages. */\nexport function formatFieldRef(ref: AnyFieldRef): string {\n const payload = fieldRefPayload(ref);\n return `${payload.model}.${payload.field}`;\n}\n\nfunction createFieldRef(\n model: string,\n field: string,\n type: ScalarType,\n list: boolean\n): AnyFieldRef {\n return Object.freeze({\n [FIELD_REF_BRAND]: Object.freeze({ model, field, type, list }),\n });\n}\n\n// =============================================================================\n// TYPE-LEVEL PROJECTION: model -> its reference table\n// =============================================================================\n\ntype ScalarsOf<M> = M extends { \"~\": { state: { scalars: infer S } } }\n ? S\n : never;\n\ntype ScalarTypeOf<S> = S extends {\n \"~\": { state: { type: infer T extends ScalarType } };\n}\n ? T\n : ScalarType;\n\ntype ReferenceableScalarKeys<M> = {\n [K in keyof ScalarsOf<M>]: ScalarTypeOf<ScalarsOf<M>[K]> extends \"point\"\n ? never\n : K;\n}[keyof ScalarsOf<M>];\n\n/**\n * One model's reference table — the type of `ctx.fields` inside an operand\n * callback: one reference per scalar field, and nothing else on it, so a\n * mistyped field name is a compile error before it is a runtime one.\n */\nexport type ModelFieldRefs<TModelName extends string, M> = {\n readonly [K in ReferenceableScalarKeys<M> & string]: FieldRef<\n TModelName,\n ScalarTypeOf<ScalarsOf<M>[K]>\n >;\n};\n\n// =============================================================================\n// RUNTIME PROJECTION\n// =============================================================================\n\nconst UNKNOWN_FIELD = (modelName: string, key: string, known: string[]) =>\n new Error(\n `Unknown scalar field \"${key}\" on model '${modelName}'. Known fields: ${known.join(\", \")}.`\n );\n\n/**\n * The reference table for ONE model: `{ likes, views, … }`, each entry built on\n * first read and memoized.\n *\n * This is what an operand callback receives as `ctx.fields`, built once per\n * model and cached there — a query that never compares columns never builds\n * one, and a model's table costs a single object until a field is read. The\n * model name is passed in because the token carries the model's SCHEMA KEY,\n * which is what the where-builder compares the query scope against (hydration\n * sets `names.ts` to that key — see `hydration.ts`).\n */\nexport function createModelFieldRefs<\n TName extends string,\n M extends Model<any>,\n>(modelName: TName, model: M): ModelFieldRefs<TName, M> {\n const cache = new Map<string, AnyFieldRef>();\n const scalars = model[\"~\"].state.scalars;\n const referenceableNames = Object.keys(scalars).filter(\n (key) => scalars[key]![\"~\"].state.type !== \"point\"\n );\n const referenceableSet = new Set(referenceableNames);\n const table = new Proxy(Object.create(null) as Record<string, AnyFieldRef>, {\n get(_target, key) {\n if (typeof key !== \"string\") return undefined;\n const cached = cache.get(key);\n if (cached) return cached;\n const scalar = referenceableSet.has(key) ? scalars[key] : undefined;\n if (!scalar) {\n throw UNKNOWN_FIELD(modelName, key, referenceableNames);\n }\n const state = scalar[\"~\"].state;\n const ref = createFieldRef(modelName, key, state.type, state.array);\n cache.set(key, ref);\n return ref;\n },\n has: (_target, key) => typeof key === \"string\" && referenceableSet.has(key),\n ownKeys: () => referenceableNames,\n getOwnPropertyDescriptor: (_target, key) =>\n typeof key === \"string\" && referenceableSet.has(key)\n ? {\n enumerable: true,\n configurable: true,\n }\n : undefined,\n });\n // The one projection this file owes its callers: the proxy answers exactly\n // the model's scalar keys (`has`/`ownKeys` above enforce it, and any other key\n // throws), which is what `ModelFieldRefs` describes and no proxy signature can.\n return table as ModelFieldRefs<TName, M>;\n}\n","/**\n * JSON null sentinels (Prisma `DbNull` / `JsonNull` / `AnyNull` parity)\n *\n * A nullable JSON column has TWO different nulls, and SQL can tell them apart\n * while JavaScript cannot:\n *\n * - the SQL NULL — the column holds no document at all (`col IS NULL`);\n * - the JSON null — the column holds a document, and that document is the\n * JSON value `null` (`'null'::jsonb`, `CAST('null' AS JSON)`, the text\n * `null` on SQLite).\n *\n * Both read back as JavaScript `null`, so a bare `null` cannot name either one\n * without guessing. Prisma solves this with three exported sentinel values, and\n * so does this file:\n *\n * ```ts\n * import { AnyNull, DbNull, JsonNull } from \"viborm\";\n *\n * await client.entry.update({ where, data: { meta: DbNull } }); // -> SQL NULL\n * await client.entry.update({ where, data: { meta: JsonNull } }); // -> 'null'\n * await client.entry.findMany({ where: { meta: { equals: AnyNull } } });\n * ```\n *\n * `AnyNull` is FILTER-ONLY, exactly as in Prisma: \"either null\" is a question,\n * not a value, so there is nothing for a write to store. The validation layer\n * refuses it in write position by name (see\n * {@link file://../validation/primitives/json-null.ts}).\n *\n * THE TOKENS ARE CLASS INSTANCES ON PURPOSE. `v.json()` accepts a plain object\n * with any keys, so a plain-object token would type-check as an ordinary JSON\n * document and could be PERSISTED as user data — the same hazard field\n * references have (see {@link file://./field-ref.ts}). A class instance has a\n * prototype that is not `Object.prototype`, so JSON validation rejects it\n * structurally: a sentinel nested anywhere inside a document\n * (`{ a: DbNull }`) fails validation instead of landing in the column as `{}`.\n * Only the top-level operand positions that explicitly opt in accept one.\n *\n * The `kind` property is an OWN ENUMERABLE STRING key, not only the symbol\n * brand, so a token reads as itself in a dump and a structural serializer at\n * least tells the three apart rather than flattening all three to `{}`.\n *\n * BEING TOLD APART IS NOT THE SAME AS BEING RECOGNIZED, and this file used to\n * claim otherwise. A JSON column accepts an ARBITRARY object, so\n * `{ kind: \"DbNull\" }` is ordinary user data — and a serializer walking\n * `Object.keys` gives it the same identity as the sentinel. The cache key\n * builder did exactly that, and a cached client served the rows of\n * `equals: DbNull` for `equals: { kind: \"DbNull\" }`, in both directions, for\n * the whole TTL. A consumer that must not confuse the two asks\n * {@link isJsonNullSentinel} and keys the answer somewhere a document cannot\n * reach, as {@link file://../cache/key.ts} now does.\n */\n\n/**\n * Brand carried by every JSON null sentinel. `Symbol.for` (not a fresh symbol)\n * so a token stays recognizable across duplicated module instances, exactly as\n * for field references.\n */\nexport const JSON_NULL_BRAND: unique symbol = Symbol.for(\"viborm.json-null\");\n\n/** The three sentinels, by name. */\nexport type JsonNullKind = \"DbNull\" | \"JsonNull\" | \"AnyNull\";\n\n/**\n * A JSON null sentinel. `TKind` is what makes `AnyNull` unassignable to a write\n * slot while `DbNull` and `JsonNull` are assignable to it.\n */\nexport class JsonNullSentinel<TKind extends JsonNullKind = JsonNullKind> {\n readonly [JSON_NULL_BRAND]: TKind;\n /** Own enumerable key so structural serializers separate the three. */\n readonly kind: TKind;\n\n constructor(kind: TKind) {\n this[JSON_NULL_BRAND] = kind;\n this.kind = kind;\n Object.freeze(this);\n }\n\n /** Readable in error messages: `DbNull`, not `[object Object]`. */\n toString(): string {\n return this.kind;\n }\n\n /** Distinct under `JSON.stringify` (instrumentation, dedup keys). */\n toJSON(): string {\n return `viborm.json-null:${this.kind}`;\n }\n}\n\n/** Any sentinel, regardless of kind. */\nexport type AnyJsonNullSentinel = JsonNullSentinel<JsonNullKind>;\n\n/** The database NULL: the column holds no JSON document. */\nexport const DbNull: JsonNullSentinel<\"DbNull\"> = new JsonNullSentinel(\n \"DbNull\"\n);\n\n/** The JSON null: the column holds the JSON document `null`. */\nexport const JsonNull: JsonNullSentinel<\"JsonNull\"> = new JsonNullSentinel(\n \"JsonNull\"\n);\n\n/** Either null. Filter positions only — see the module header. */\nexport const AnyNull: JsonNullSentinel<\"AnyNull\"> = new JsonNullSentinel(\n \"AnyNull\"\n);\n\nconst KINDS: ReadonlySet<string> = new Set<JsonNullKind>([\n \"DbNull\",\n \"JsonNull\",\n \"AnyNull\",\n]);\n\n/**\n * Runtime brand check. A property probe rather than `instanceof`, so a token\n * created by a duplicated copy of this module is still recognized (the same\n * reason {@link file://./field-ref.ts} probes its symbol).\n */\nexport function isJsonNullSentinel(\n value: unknown\n): value is AnyJsonNullSentinel {\n if (typeof value !== \"object\" || value === null) return false;\n const brand = (value as { [JSON_NULL_BRAND]?: unknown })[JSON_NULL_BRAND];\n return typeof brand === \"string\" && KINDS.has(brand);\n}\n\n/** The sentinel's kind, or `undefined` when the value is not a sentinel. */\nexport function jsonNullKindOf(value: unknown): JsonNullKind | undefined {\n return isJsonNullSentinel(value) ? value.kind : undefined;\n}\n","// Shared immutable-terminal machinery: the construction-time refusal vocabulary\n// and the source-independent target once-cell.\n//\n// Every structurally knowable fact about a declaration is decided HERE or in the\n// factory/modifier that owns it, before the value enters trusted relation state.\n// Facts that need the schema graph — is the settled return a registered model,\n// which endpoint owns the foreign key, does the pair exist — belong to the\n// full-schema relation resolver and are deliberately absent.\n\nimport { ValidationError } from \"@errors\";\nimport { isValidSchemaIdentifier } from \"../identifier\";\nimport type {\n JunctionReferentialAction,\n JunctionSideActions,\n NonEmptyFieldTuple,\n ReferentialAction,\n} from \"./types\";\n\n/** The builder label carried by every construction-time refusal. */\nexport type RelationBuilder = \"s.toOne\" | \"s.toMany\" | \"s.model\";\n\n/**\n * The one construction-time refusal. Structural input the factories and\n * modifiers can judge on their own never reaches the schema resolver as a\n * `SchemaValidationIssue`; it fails here, at the call the author wrote.\n */\nexport function refuseRelationInput(\n builder: RelationBuilder,\n path: string,\n message: string,\n cause?: Error\n): never {\n throw new ValidationError(\n { kind: \"schema-builder\", builder, path },\n [{ path, message }],\n cause === undefined ? undefined : { cause }\n );\n}\n\n// =============================================================================\n// PLAIN-RECORD READS\n// =============================================================================\n\n/**\n * A caller-supplied map is a variant declaration only when it is a plain\n * record: a hostile prototype would otherwise smuggle inherited entries past\n * own-key enumeration into schema truth.\n */\nexport function isPlainRecord(\n value: unknown\n): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * Own ENUMERABLE string keys — the declaration surface of a record. Symbol keys\n * and inherited entries are not declarations, and neither is an own key hidden\n * behind `enumerable: false`.\n */\nexport function declaredKeys(record: Record<string, unknown>): string[] {\n return Object.keys(record);\n}\n\n/** Exactly these keys, in any order. */\nexport function hasExactKeys(\n actual: readonly string[],\n expected: readonly string[]\n): boolean {\n return (\n actual.length === expected.length &&\n expected.every((key) => actual.includes(key))\n );\n}\n\n/**\n * Read one caller-owned property exactly once. Accessors are executable input:\n * when one throws, the declaration boundary owns the V4002 refusal and keeps a\n * normalized cause instead of leaking the caller's thrown value.\n */\nexport function readCallerProperty(\n builder: RelationBuilder,\n record: Record<string, unknown>,\n property: string,\n path: string\n): unknown {\n try {\n return Reflect.get(record, property);\n } catch (thrown) {\n refuseRelationInput(\n builder,\n path,\n `Could not read relation input '${path}'`,\n normalizeThrown(\n thrown,\n `Reading relation input '${path}' threw a non-Error value`\n )\n );\n }\n}\n\n// =============================================================================\n// MODIFIER TOKENS\n// =============================================================================\n\n/**\n * A relation name is a non-empty PAIRING LABEL, not a SQL identifier: an\n * explicit `.through(...)` lets `\"Post tags/v2\"` name a pair without pretending\n * the label is a database name.\n */\nexport function normalizeRelationName(\n builder: RelationBuilder,\n name: unknown\n): string {\n if (typeof name !== \"string\" || name.length === 0) {\n refuseRelationInput(\n builder,\n \"name\",\n \"A relation name must be a non-empty string\"\n );\n }\n return name;\n}\n\nexport function normalizeReferentialAction(\n path: string,\n action: unknown\n): ReferentialAction {\n if (\n action === \"cascade\" ||\n action === \"setNull\" ||\n action === \"restrict\" ||\n action === \"noAction\"\n ) {\n return action;\n }\n refuseRelationInput(\n \"s.toOne\",\n path,\n \"A referential action must be one of 'cascade', 'setNull', 'restrict' or 'noAction'\"\n );\n}\n\n/** Junction actions exclude `setNull` at the type level and here. */\nfunction normalizeJunctionAction(\n path: string,\n action: unknown\n): JunctionReferentialAction {\n if (action === \"cascade\" || action === \"restrict\" || action === \"noAction\") {\n return action;\n }\n refuseRelationInput(\n \"s.toMany\",\n path,\n \"A junction referential action must be one of 'cascade', 'restrict' or 'noAction'; 'setNull' cannot null a membership-key member\"\n );\n}\n\n/**\n * The ONE normalization of a junction action declaration. A bare action is the\n * symmetric shorthand and becomes the same pair a `{ source, target }` map\n * spells, so trusted state holds one form and no consumer asks which spelling\n * declared it. The map names both sides and nothing else: an omitted side\n * would silently keep a default the author never chose. Every object is read\n * as a map, so an array or a class instance is told what a map must be rather\n * than which actions exist.\n */\nexport function normalizeJunctionActions(\n path: \"onDelete\" | \"onUpdate\",\n declared: unknown\n): JunctionSideActions {\n if (typeof declared !== \"object\" || declared === null) {\n const action = normalizeJunctionAction(path, declared);\n return Object.freeze({ source: action, target: action });\n }\n if (\n !(\n isPlainRecord(declared) &&\n hasExactKeys(declaredKeys(declared), [\"source\", \"target\"])\n )\n ) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `A junction '${path}' map is a plain record naming exactly 'source' (the foreign key to the declaring model) and 'target' (the foreign key to its target model)`\n );\n }\n const side = (name: \"source\" | \"target\"): JunctionReferentialAction =>\n normalizeJunctionAction(\n `${path}.${name}`,\n readCallerProperty(\"s.toMany\", declared, name, `${path}.${name}`)\n );\n return Object.freeze({ source: side(\"source\"), target: side(\"target\") });\n}\n\n/** One junction table name or side naming token. */\nexport function normalizeJunctionToken(path: string, token: unknown): string {\n if (!isValidSchemaIdentifier(token)) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Junction '${path}' must be a valid schema identifier`\n );\n }\n return token;\n}\n\n/** A non-empty foreign-key tuple whose members are distinct. */\nexport function normalizeFieldTuple(\n builder: RelationBuilder,\n path: string,\n fields: readonly string[]\n): NonEmptyFieldTuple {\n const [head, ...rest] = fields;\n if (head === undefined) {\n refuseRelationInput(\n builder,\n path,\n `'${path}' requires at least one field key`\n );\n }\n if (new Set(fields).size !== fields.length) {\n refuseRelationInput(\n builder,\n path,\n `'${path}' cannot repeat a field key in one foreign-key tuple`\n );\n }\n return [head, ...rest];\n}\n\n// =============================================================================\n// TARGET SETTLEMENT\n// =============================================================================\n\ntype SettledTarget =\n | { readonly settled: \"value\"; readonly value: unknown }\n | { readonly settled: \"error\"; readonly error: Error };\n\n/**\n * The declaration-lifetime target cell.\n *\n * A raw getter stays lazy, but it is invoked at most ONCE per target: the first\n * resolution settles its return or one normalized `Error`, and every later\n * consumer — including a second schema graph reusing the same immutable\n * terminal — observes that same outcome. A resolver-local cache alone would let\n * a stateful getter give validation, migrations and the query engine different\n * declaration truth.\n *\n * Only settled outcomes live here. The resolver decides whether a return is a\n * registered model and attaches its own model/field path to any issue, so\n * contextual diagnostics are never cached on the shared terminal.\n */\nexport function createTargetSettlement(\n readGetter: (variantKey: string | undefined) => unknown\n): (variantKey?: string) => unknown {\n const cells = new Map<string, SettledTarget>();\n return (variantKey?: string): unknown => {\n const cellKey = variantKey ?? \"\";\n let cell = cells.get(cellKey);\n if (cell === undefined) {\n cell = settleTargetOnce(readGetter, variantKey);\n cells.set(cellKey, cell);\n }\n if (cell.settled === \"value\") return cell.value;\n throw cell.error;\n };\n}\n\nfunction settleTargetOnce(\n readGetter: (variantKey: string | undefined) => unknown,\n variantKey: string | undefined\n): SettledTarget {\n // READING the getter cannot fail: every `readGetter` handed to\n // {@link createTargetSettlement} is one property read over frozen\n // declaration state. INVOKING it can, and that is the one `try` below.\n const getter = readGetter(variantKey);\n // The read still may not produce one: a variant asked without a key or with\n // an unknown one has no entry, and a forged state can carry a non-function\n // target where the factories admit only a getter. Settling that as a failure\n // is what keeps every later consumer from re-reading a target that can never\n // resolve — and from reading `undefined` as a resolved one.\n if (typeof getter !== \"function\") {\n return {\n settled: \"error\",\n error: new Error(\"Relation target getter is not a function\"),\n };\n }\n try {\n return { settled: \"value\", value: getter() };\n } catch (thrown) {\n return {\n settled: \"error\",\n error: normalizeThrown(\n thrown,\n \"Relation target getter threw a non-Error value\"\n ),\n };\n }\n}\n\n/**\n * One normalization, owned here: a thrown `Error` keeps its identity across\n * every consumer, and a non-Error throw becomes exactly one `Error` that every\n * consumer then shares.\n */\nfunction normalizeThrown(thrown: unknown, nonErrorPrefix: string): Error {\n if (thrown instanceof Error) return thrown;\n let rendered: string;\n try {\n rendered = typeof thrown === \"symbol\" ? thrown.toString() : String(thrown);\n } catch {\n rendered = \"<unrenderable non-Error value>\";\n }\n return new Error(`${nonErrorPrefix}: ${rendered}`);\n}\n"],"mappings":"gIA8CA,MAAa,EAAiC,OAAO,IAAI,mBAAmB,CA0C5E,SAAgB,WAAW,EAAsC,CAC/D,GAAI,OAAO,GAAU,WAAY,EAAgB,MAAO,GACxD,IAAM,EAAW,EAA0C,GAC3D,OAAO,OAAO,GAAY,YAAY,EAIxC,SAAgB,gBAAgB,EAAmC,CACjE,OAAO,EAAI,GAIb,SAAgB,eAAe,EAA0B,CACvD,IAAM,EAAU,gBAAgB,EAAI,CACpC,MAAO,GAAG,EAAQ,MAAM,GAAG,EAAQ,QAGrC,SAAS,eACP,EACA,EACA,EACA,EACa,CACb,OAAO,OAAO,OAAO,EAClB,GAAkB,OAAO,OAAO,CAAE,QAAO,QAAO,OAAM,OAAM,CAAC,CAC/D,CAAC,CAuCJ,MAAM,eAAiB,EAAmB,EAAa,IACjD,MACF,yBAAyB,EAAI,cAAc,EAAU,mBAAmB,EAAM,KAA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MAAW,MAAM,2CAA2C,CAC7D,CAEH,GAAI,CACF,MAAO,CAAE,QAAS,QAAS,MAAO,GAAQ,CAAE,OACrC,EAAQ,CACf,MAAO,CACL,QAAS,QACT,MAAO,gBACL,EACA,iDACD,CACF,EASL,SAAS,gBAAgB,EAAiB,EAA+B,CACvE,GAAI,aAAkB,MAAO,OAAO,EACpC,IAAI,EACJ,GAAI,CACF,EAAW,OAAO,GAAW,SAAW,EAAO,UAAU,CAAG,OAAO,EAAO,MACpE,CACN,EAAW,iCAEb,OAAW,MAAM,GAAG,EAAe,IAAI,IAAW"}
|
package/dist/v-D5Z06FKN.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,c as n,i as r,n as i,o as a,r as o,s}from"./value-guards-CK9guf2Z.mjs";import{t as c}from"./validation-Dk9Q_-C7.mjs";import{g as l,m as ee,v as u,x as d,y as f}from"./terminal-C8cq1WWX.mjs";import{o as te,r as p}from"./sql-Bp7jicEX.mjs";import{B as m,F as ne,H as h,I as g,J as _,K as v,Nt as re,R as y,U as b,V as x,W as S,Y as C,a as w,d as T,f as E,i as ie,m as D,o as ae,p as O,q as oe,r as se,z as k}from"./geo-point-codec-lhxH42SK.mjs";function array(e){let t=e[`~standard`].validate,n=h(`array`,e=>oe(e,t));return n.item=e,n}const A=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected Uint8Array`})])}),j=Object.getPrototypeOf(Uint8Array.prototype);function localBufferPrototype(){try{let e=Reflect.get(globalThis,`Buffer`);if(typeof e!=`function`)return;let t=Reflect.get(e,`prototype`);if(typeof t==`object`&&t&&Object.getPrototypeOf(t)===Uint8Array.prototype)return t}catch{return}}const M=localBufferPrototype();function hasOwnViewMetadata(e){return Object.getOwnPropertyDescriptor(e,`buffer`)!==void 0||Object.getOwnPropertyDescriptor(e,`byteOffset`)!==void 0||Object.getOwnPropertyDescriptor(e,`byteLength`)!==void 0}function hasTrustedLocalPrototype(e){let t=Object.getPrototypeOf(e);return(t===Uint8Array.prototype||t===M)&&!hasOwnViewMetadata(e)}function validateBlob(e){try{if(!n(e))return A;let t=Reflect.get(j,`buffer`,e),r=Reflect.get(j,`byteOffset`,e),i=Reflect.get(j,`byteLength`,e),a=hasTrustedLocalPrototype(e),o=new Uint8Array(t,r,i);return S(a?e:o)}catch{return A}}function blob(e){return x(`blob`,validateBlob,e)}const N=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected boolean`})])});function validateBoolean(e){return i(e)?S(e):N}function boolean(e){return x(`boolean`,validateBoolean,e)}const P=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected Date`})])}),F=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected valid Date`})])});function validateDate(e){if(!o(e))return P;let t=Date.prototype.getTime.call(e);return Number.isNaN(t)?F:e instanceof Date?S(e):S(new Date(t))}function date(e){return x(`date`,validateDate,e)}const I=Object.freeze({issues:Object.freeze([Object.freeze({message:g})])});function validateDecimal(e){let t=y(e);return t===void 0?I:S(t)}function buildDecimalValueValidator(e){let t=e?.schema,n=e?.decimal,validate=validateDecimal;if(t!==void 0){let e=t[`~standard`].validate,n=validate;validate=t=>{let r=n(t);if(r.issues)return r;let i=e(ne(r.value));if(`then`in i)return C(i),b(`Async schemas are not supported`);if(i.issues)return v(i.issues);let a=k(i.value);return a===void 0?b(`Expected a Decimal: a custom decimal schema may refine or brand the value it is given, but not return a string, a number, or a value of any other type`):S(a)}}if(n!==void 0){let e=validate;validate=t=>{let r=e(t);if(r.issues)return r;let i=m(r.value,n.precision,n.scale);return i===void 0?r:b(i)}}return validate}function decimal(e){let t=e===void 0?void 0:{...e,schema:void 0};return x(`decimal`,buildDecimalValueValidator(e),t)}function enum_(e,t){let n=new Set(e),baseValidate=t=>s(t)&&n.has(t)?S(t):{issues:[{message:`Expected one of: ${e.join(` | `)}`}]};return x(`enum`,baseValidate,t,{values:e})}function getNestedValue(e,t){let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return r}function declaresPath(e,t){let n=t.lastIndexOf(`.`),r=n===-1?e:getNestedValue(e,t.slice(0,n));return a(r)&&t.slice(n+1)in r}function entriesFromObject(e,t){let n={};for(let r of Object.keys(e)){let i=getNestedValue(e[r],t);i!==void 0&&(n[r]=i)}return Object.keys(e).length>0&&Object.keys(n).length===0&&refuseUnmatchedPath(e,t),n}function fromObject(e,t,n){return D(entriesFromObject(e,t),n)}function refuseUnmatchedPath(e,t){if(!Object.values(e).some(e=>declaresPath(e,t)))throw new c({kind:`schema-builder`,builder:`fromObject`,path:t},[{path:t,message:`fromObject path "${t}" did not match any entries in the source object`}])}const L=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,3})?(?:Z|[+-](\d{2}):(\d{2}))$/,R=/^(\d{4})-(\d{2})-(\d{2})$/,z=/^\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/,B=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected string or Date`})])}),V=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected ISO timestamp format (YYYY-MM-DDTHH:mm:ss.sssZ)`})])}),H=Object.freeze({issues:Object.freeze([Object.freeze({message:`Invalid date in ISO timestamp`})])});function validateIsoTimestamp(e){if(o(e))return E(Date.prototype.getTime.call(e))?S(Date.prototype.toISOString.call(e)):H;if(!s(e))return B;let t=L.exec(e);return t?!(O(Number(t[1]),Number(t[2]),Number(t[3]))&&T(Number(t[4]),Number(t[5]),Number(t[6])))||Number(t[7]??0)>23||Number(t[8]??0)>59||!E(Date.parse(e))?H:S(new Date(e).toISOString()):V}function isoTimestamp(e){return x(`iso_timestamp`,validateIsoTimestamp,e)}const U=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected ISO date format (YYYY-MM-DD)`})])}),W=Object.freeze({issues:Object.freeze([Object.freeze({message:`Invalid date`})])});function validateIsoDate(e){if(o(e))return E(Date.prototype.getTime.call(e))?S(Date.prototype.toISOString.call(e).slice(0,10)):W;if(!s(e))return B;let t=R.exec(e);return t?O(Number(t[1]),Number(t[2]),Number(t[3]))?S(e):W:U}function isoDate(e){return x(`iso_date`,validateIsoDate,e)}const G=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected ISO time format (HH:mm:ss)`})])}),K=Object.freeze({issues:Object.freeze([Object.freeze({message:`Invalid time`})])});function validateIsoTime(e){if(o(e))return Number.isNaN(Date.prototype.getTime.call(e))?K:S(Date.prototype.toISOString.call(e).split(`T`)[1].replace(`Z`,``));if(!s(e))return B;if(!z.test(e))return G;let t=e.split(`:`),n=Number(t[0]),r=Number(t[1]),i=Math.trunc(Number(t[2]));return n<0||n>23||r<0||r>59||i<0||i>59?K:S(e.padEnd(12,e.includes(`.`)?`0`:`.000`))}function isoTime(e){return x(`iso_time`,validateIsoTime,e)}const ce=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected JSON-compatible value`})])}),q=Symbol(`invalid JSON`);function normalizeJson(e,n=new WeakMap){if(e===null||s(e)||i(e))return e;if(t(e))return Number.isFinite(e)?e:q;if(!(a(e)||Array.isArray(e))||d(e))return q;let r=n.get(e);if(r!==void 0)return r;if(n.set(e,q),Array.isArray(e)){let t=[];for(let r of e){let e=r===void 0?null:normalizeJson(r,n);if(e===q)return q;t.push(e)}return n.set(e,t),t}let o=Object.getPrototypeOf(e);if(o!==null&&o!==Object.prototype)return q;let c={};for(let t of Object.keys(e)){let r=e[t];if(r===void 0)continue;let i=normalizeJson(r,n);if(i===q)return q;Object.defineProperty(c,t,{value:i,enumerable:!0,configurable:!0,writable:!0})}return n.set(e,c),c}function validateJson(e){let t=normalizeJson(e);return t===q?ce:S(t)}function json(e){return x(`json`,validateJson,e)}const J=[`DbNull`,`JsonNull`,`AnyNull`];function listKinds(e){return e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} or ${e.at(-1)}`}function refuseSentinel(e,t,n){return b(`${J.filter(e=>!t.includes(e)).length===J.length?`JSON null sentinels are not supported in ${n}`:`${e.kind} is not supported in ${n}; that slot accepts ${listKinds(t)}`}.`)}function checkSentinel(e,t,n){return t.includes(e.kind)?S(e):refuseSentinel(e,t,n)}function copyOptionality(e,t,n){e.allowed=n,e.wrapped=t,e.acceptsUndefined=t.acceptsUndefined===!0}function jsonNullOr(e,t,n){let r=h(`json_null_or`,r=>l(r)?checkSentinel(r,e,n):_(t,r));return copyOptionality(r,t,e),r}function jsonWrite(e,t,n,r){let i=h(`json_write`,i=>{if(l(i))return checkSentinel(i,e,n);if(i===null)return b(r);let a=_(t,i);return!a.issues&&a.value===null&&i!==void 0?checkSentinel(ee,e,n):a});return copyOptionality(i,t,e),i}function lazy(e){let t=e,n,resolve=()=>(t&&=(n=t(),void 0),n);return new Proxy({},{get(e,t,n){let i=resolve(),a=Reflect.get(i,t,n);return r(a)?a.bind(i):a},has(e,t){return Reflect.has(resolve(),t)},ownKeys(e){return Reflect.ownKeys(resolve())},getOwnPropertyDescriptor(e,t){return Reflect.getOwnPropertyDescriptor(resolve(),t)},getPrototypeOf(e){return Reflect.getPrototypeOf(resolve())}})}function lazyRef(e){let t=e,n,resolve=()=>(t&&=(n=t(),void 0),n);return{type:`lazyRef`,get wrapped(){return resolve()},get entries(){return resolve().entries},"~standard":{version:1,vendor:`viborm`,validate:e=>resolve()[`~standard`].validate(e),get jsonSchema(){return resolve()[`~standard`].jsonSchema}}}}function literal(e,t){let n=e===null?`null`:String(e),r=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected literal: ${n}`})])}),baseValidate=t=>t===e?S(t):r;return x(`literal`,baseValidate,t,{value:e})}function nullable(e){let t=e[`~standard`].validate,n=h(`nullable`,e=>e===null?S(null):t(e));return n.wrapped=e,n}function maybeNullable(e,t){return t?nullable(e):e}function omit(e,t){return D(e.entries,{...e.options||{},omit:t})}let Y=0;function limitFilterDepth(e){let t=e[`~standard`].validate;return Object.defineProperty(e[`~standard`],`validate`,{value:e=>{if(Y>=16)return b(`Filter nesting exceeds 16 levels`);Y++;try{return t(e)}finally{Y--}}}),e}let X;const Z=new WeakMap;function runInOperandScope(e,t){let n=X;X=e;try{return t()}finally{X=n}}function scopeOperands(e,t){let n=e[`~standard`],r=n.validate;return n.validate=e=>runInOperandScope(t,()=>r(e)),limitFilterDepth(e)}function currentContext(){let e=X;if(!e)return;let t=Z.get(e);if(t)return t;let n={fields:u(e[`~`].names.ts??`unknown`,e),sql:te};return Z.set(e,n),n}const Q="A filter callback must return a field reference (ctx.fields.<field>) or an SQL fragment (ctx.sql`…`)";function describe$1(e){return e===null?`null`:Array.isArray(e)?`an array`:`a value of type '${typeof e}'`}e(describe$1,`describe`);function resolveCallback(e,t){let n=currentContext();if(!n)return b(`A filter callback is only meaningful inside a model filter, where the model whose columns it names is known.`);let i;try{i=e(n)}catch(e){return b(`Filter callback threw: ${e instanceof Error?e.message:String(e)}`)}return d(i)?checkRef(i,t):p(i)?S(i):a(i)&&r(i.then)?(C(i),b(`${Q}; it returned a promise. Validation is synchronous, so a filter callback cannot be async.`)):b(`${Q}; it returned ${describe$1(i)}.`)}function comparisonOperand(e,t){let n=h(`comparison_operand`,n=>r(n)?resolveCallback(n,e):d(n)?checkRef(n,e):p(n)?S(n):_(t,n));return n.fieldType=e,n.wrapped=t,n.acceptsUndefined=t.acceptsUndefined===!0,n}function fieldRefOr(e,t){let n=h(`field_ref_or`,n=>d(n)?checkRef(n,e):_(t,n));return n.fieldType=e,n.wrapped=t,n.acceptsUndefined=t.acceptsUndefined===!0,n}function closeOperands(e,t,n){let r=e[`~standard`],i={"~standard":{version:r.version,vendor:r.vendor,validate:r.validate}},a=h(`no_field_ref`,e=>{let r=findOpaqueOperand(e,n);if(r)return b(`${r} is not supported in ${t}.`);let a=_(i,e);if(a.issues)return a;let o=findOpaqueOperand(a.value,n);return o?b(`${o} is not supported in ${t}.`):a});return a.wrapped=e,a.acceptsUndefined=e.acceptsUndefined??!1,a}function noFieldRef(e,t){return closeOperands(e,t,!1)}function noOperandExpression(e,t){return closeOperands(e,t,!0)}function findOpaqueOperand(e,t){let n=new WeakSet,r=[e];for(;r.length>0;){let e=r.pop();if(t&&typeof e==`function`)return`A filter callback`;if(!(typeof e!=`object`||!e)){if(d(e)){let t=f(e);return`Field reference '${t.model}.${t.field}'`}if(t&&p(e))return`An SQL fragment`;if(!n.has(e)&&(n.add(e),!(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))){if(Array.isArray(e)){for(let t of e)r.push(t);continue}for(let t of Object.keys(e))r.push(e[t])}}}}function checkRef(e,t){let n=f(e);return n.list?b(`Field reference '${n.model}.${n.field}' is a list field; list fields cannot be used as a comparison operand.`):n.type===t?S(e):b(`Field reference '${n.model}.${n.field}' is of type '${n.type}', but a '${t}' operand is required here.`)}function transform(e){return{type:`transform`,transform:e}}function pipe(e,...t){let n=h(`pipe`,n=>{let r=_(e,n);if(r.issues)return r;let i=r.value;for(let e of t)if(e.type===`transform`)try{i=e.transform(i)}catch(e){return b(`Transform failed: ${e instanceof Error?e.message:String(e)}`)}return S(i)});return n.schema=e,n.actions=t,n}function point(e){return x(`point`,se,e)}function record(e,t){let n=h(`record`,n=>{if(!a(n))return b(`Expected object, received ${Array.isArray(n)?`array`:typeof n}`);let r={};for(let[i,a]of Object.entries(n)){let n=_(e,i);if(n.issues)return b(`Invalid key "${i}": ${n.issues[0].message}`,[i]);let o=_(t,a);if(o.issues){let e=o.issues[0],t=e.path?[i].concat(e.path):[i];return b(e.message,t)}r[n.value]=o.value}return S(r)});return n.key=e,n.value=t,n}function entriesFromKeys(e,t){let n={};for(let r of e)n[r]=t;return n}function fromKeys(e,t,n){return D(entriesFromKeys(e,t),n)}function refused(e){return h(`refused`,()=>b(e))}function coerce(e,t){let n=h(`transform`,n=>{let r=_(e,n);if(r.issues)return{issues:r.issues};try{return S(t(r.value))}catch(e){return b(`Transform failed: ${e instanceof Error?e.message:String(e)}`)}});return n.wrapped=e,n.acceptsUndefined=e.acceptsUndefined===!0,n}const le=coerce,shorthandFilter=e=>coerce(e,e=>({equals:e})),shorthandUpdate=e=>coerce(e,e=>({set:e})),shorthandArray=e=>coerce(e,e=>[e]),ue=Object.freeze([Object.freeze({message:`Async schemas are not supported`})]);function tagsOf(e){let t,n=new Map;for(let r of e){let{type:e,entries:i,options:a}=r;if(e!==`object`||!i||a?.array===!0)return;t??=Object.keys(i).find(e=>isLiteral(i[e]));let o=t===void 0?void 0:i[t];if(!(isLiteral(o)&&o.acceptsUndefined!==!0)||n.has(o.value)||a?.omit?.includes(t))return;n.set(o.value,r[`~standard`].validate)}return t===void 0||n.size<2?void 0:{key:t,members:n}}function isLiteral(e){return a(e)&&e.type===`literal`}function settled(e){return`then`in e?(C(e),{issues:ue}):e}function describe({message:e,path:t}){return t?.length?`${t.join(`.`)}: ${e}`:e}function union(e){let t=e.map(e=>e[`~standard`].validate),n=null,r=h(`union`,r=>{n===null&&(n=tagsOf(e));let i=n&&a(r)&&n.members.get(r[n.key]);if(i)return settled(i(r));let o,s=-1,c;for(let e of t){let t=settled(e(r));if(!t.issues)return t;let{issues:n}=t,i=n[0].path?.length??0;if(i>s)o=n,s=i,c=void 0;else if(i===s){let e=describe(n[0]);c??=[describe(o[0])],c.includes(e)||c.push(e)}}return c&&c.length>1?b(c.join(`, or `)):o?{issues:o}:b(`Expected no value: the union has no member`)});return r.options=e,r}const singleOrArray=e=>union([coerce(e,e=>[e]),array(e)]),de=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected string`})])});function validateString(e){return s(e)?S(e):de}function string(e){return x(`string`,validateString,e)}const fe=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected array of numbers`})])});function createVectorValidator(e){let n=e===void 0?null:Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected vector of ${e} dimensions`})])});return r=>{if(!Array.isArray(r))return fe;let i=r.length;for(let e=0;e<i;e++)if(!(t(r[e])&&Number.isFinite(r[e])))return b(`Expected finite number at index ${e}`);return n&&i!==e?n:S(r)}}function vector(e,t){return x(`vector`,createVectorValidator(e),t,{dimensions:e})}const $={string,number:ae,integer:w,boolean,bigint:re,decimal,literal,enum:enum_,json,date,isoTimestamp,isoDate,isoTime,blob,vector,point,array,nullable,maybeNullable,optional:ie,object:D,omit,fromObject,union,pipe,transformAction:transform,record,fromKeys,coerce,map:le,lazy,lazyRef,singleOrArray,shorthandFilter,shorthandUpdate,shorthandArray,comparisonOperand,fieldRefOr,noFieldRef,noOperandExpression,jsonNullOr,jsonWrite,refused};var pe=$;export{limitFilterDepth as a,validateIsoTimestamp as c,scopeOperands as i,entriesFromObject as l,pe as n,validateIsoDate as o,entriesFromKeys as r,validateIsoTime as s,$ as t};
|
|
2
|
-
//# sourceMappingURL=v-D5Z06FKN.mjs.map
|