viborm 1.14.2 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-namespace-DaRiTIIf.mjs → adapter-namespace-DD-BQ2Wk.mjs} +2 -2
- package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DD-BQ2Wk.mjs.map} +1 -1
- package/dist/adapters.d.mts +15 -3
- package/dist/adapters.mjs +1 -1
- package/dist/{args-764KdWMr.mjs → args-BvA37zBZ.mjs} +2 -2
- package/dist/{args-764KdWMr.mjs.map → args-BvA37zBZ.mjs.map} +1 -1
- package/dist/{batch-refs-C-gx7A4-.mjs → batch-refs-BmEpMmjI.mjs} +2 -2
- package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-BmEpMmjI.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +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.d.mts +2 -2
- package/dist/cache.mjs +1 -1
- package/dist/{call-Cz8XUmrl.mjs → call-BWFI7-vU.mjs} +2 -2
- package/dist/{call-Cz8XUmrl.mjs.map → call-BWFI7-vU.mjs.map} +1 -1
- package/dist/cli.mjs +2 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/client-CVCC-D1j.mjs +2 -0
- package/dist/client-CVCC-D1j.mjs.map +1 -0
- package/dist/{client-CRxfhw2y.d.mts → client-DZ39sYy2.d.mts} +2 -2
- package/dist/{client-y7TV0PRZ.mjs → client-DtPTegtA.mjs} +2 -2
- package/dist/{client-y7TV0PRZ.mjs.map → client-DtPTegtA.mjs.map} +1 -1
- package/dist/client.d.mts +3 -3
- package/dist/client.mjs +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/{confine-DqFBTUw6.mjs → confine-BGGv2du0.mjs} +2 -2
- package/dist/{confine-DqFBTUw6.mjs.map → confine-BGGv2du0.mjs.map} +1 -1
- package/dist/{coordination-6qZHx_kl.mjs → coordination-BY6Np3xV.mjs} +2 -2
- package/dist/{coordination-6qZHx_kl.mjs.map → coordination-BY6Np3xV.mjs.map} +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-D62c-uC6.d.mts} +604 -473
- package/dist/{datetime-physical-codec-Dj-APo9f.mjs → datetime-physical-codec-BS2T81sD.mjs} +2 -2
- package/dist/{datetime-physical-codec-Dj-APo9f.mjs.map → datetime-physical-codec-BS2T81sD.mjs.map} +1 -1
- package/dist/{defaults-DwOHWI_M.mjs → defaults-CrtGVdEC.mjs} +2 -2
- package/dist/{defaults-DwOHWI_M.mjs.map → defaults-CrtGVdEC.mjs.map} +1 -1
- package/dist/{document-BVTQ-cF-.d.mts → document-o5Bd5ZoJ.d.mts} +1 -1
- package/dist/{driver-BBEmaJZy.d.mts → driver-0cdCF_KD.d.mts} +1 -1
- package/dist/{driver-BGVcgnIX.mjs → driver-D1grnHEr.mjs} +2 -2
- package/dist/{driver-BGVcgnIX.mjs.map → driver-D1grnHEr.mjs.map} +1 -1
- package/dist/{driver-BIXhOH2_.mjs → driver-Df88hu4U.mjs} +2 -2
- package/dist/{driver-BIXhOH2_.mjs.map → driver-Df88hu4U.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/durable-object.d.mts +1 -1
- package/dist/durable-object.mjs +1 -1
- package/dist/error-mapping-DIRlrmDK.mjs +2 -0
- package/dist/error-mapping-DIRlrmDK.mjs.map +1 -0
- package/dist/every-BHEmfLOW.mjs +2 -0
- package/dist/{every-tOgQmaIE.mjs.map → every-BHEmfLOW.mjs.map} +1 -1
- package/dist/execution-context-VMQm-9CH.mjs +2 -0
- package/dist/execution-context-VMQm-9CH.mjs.map +1 -0
- package/dist/{exports-COCJ8f2f.d.mts → exports-Bzvtum3F.d.mts} +1 -1
- package/dist/geo-area-codec-BDvW7IH-.mjs +2 -0
- package/dist/{geo-area-codec-mHrM3b9A.mjs.map → geo-area-codec-BDvW7IH-.mjs.map} +1 -1
- package/dist/{hydration-A3zffFWP.mjs → hydration-D7U8HACL.mjs} +2 -2
- package/dist/{hydration-A3zffFWP.mjs.map → hydration-D7U8HACL.mjs.map} +1 -1
- package/dist/{identifier-conversion-DHYPTgzr.mjs → identifier-conversion-Ci_iaJ0b.mjs} +2 -2
- package/dist/{identifier-conversion-DHYPTgzr.mjs.map → identifier-conversion-Ci_iaJ0b.mjs.map} +1 -1
- package/dist/identifiers-BTCfD5ic.mjs +2 -0
- package/dist/identifiers-BTCfD5ic.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{introspect-Bm6xnXcG.mjs → introspect-C4T5gt9O.mjs} +2 -2
- package/dist/{introspect-Bm6xnXcG.mjs.map → introspect-C4T5gt9O.mjs.map} +1 -1
- package/dist/{json-DgMc8-GU.mjs → json-CHdgejCt.mjs} +2 -2
- package/dist/{json-DgMc8-GU.mjs.map → json-CHdgejCt.mjs.map} +1 -1
- package/dist/judge-words-DpwxOfre.mjs +2 -0
- package/dist/judge-words-DpwxOfre.mjs.map +1 -0
- package/dist/{key-hxFFCKed.mjs → key-B3xgpu0M.mjs} +2 -2
- package/dist/{key-hxFFCKed.mjs.map → key-B3xgpu0M.mjs.map} +1 -1
- package/dist/{keys-BQxM4c_a.mjs → keys-1Z6WKrnE.mjs} +1 -1
- package/dist/{keys-BQxM4c_a.mjs.map → keys-1Z6WKrnE.mjs.map} +1 -1
- package/dist/{libsql-DuGR904j.mjs → libsql-DJRsCDT_.mjs} +2 -2
- package/dist/{libsql-DuGR904j.mjs.map → libsql-DJRsCDT_.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-G4cSuc6A.mjs → memory-gjKMy3Ql.mjs} +2 -2
- package/dist/{memory-G4cSuc6A.mjs.map → memory-gjKMy3Ql.mjs.map} +1 -1
- package/dist/methods-part-DoTrY6b9.mjs +2 -0
- package/dist/methods-part-DoTrY6b9.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/snowflake.d.mts +4 -4
- package/dist/migrations/snowflake.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/surrealdb.d.mts +4 -4
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-BNXWfTOo.mjs → mysql-BH0Z3PlH.mjs} +2 -2
- package/dist/{mysql-BNXWfTOo.mjs.map → mysql-BH0Z3PlH.mjs.map} +1 -1
- package/dist/mysql-adapter-B06Ve3ds.mjs +2 -0
- package/dist/mysql-adapter-B06Ve3ds.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/named-statements-Bdz2GD5R.d.mts +13 -0
- package/dist/named-statements-CMj1QEyw.mjs +2 -0
- package/dist/named-statements-CMj1QEyw.mjs.map +1 -0
- package/dist/{native-types-DgjMUikz.mjs → native-types-DspZ0Z5E.mjs} +2 -2
- package/dist/{native-types-DgjMUikz.mjs.map → native-types-DspZ0Z5E.mjs.map} +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/{object-store-B_YMoW8u.d.mts → object-store-D5x-Yf7w.d.mts} +3 -3
- package/dist/{object-store-DS0F0yZX.mjs → object-store-WIE0DGGG.mjs} +1 -1
- package/dist/{object-store-DS0F0yZX.mjs.map → object-store-WIE0DGGG.mjs.map} +1 -1
- package/dist/{on-ylYaKuRu.mjs → on-DvrfHGje.mjs} +2 -2
- package/dist/{on-ylYaKuRu.mjs.map → on-DvrfHGje.mjs.map} +1 -1
- package/dist/on.d.mts +1 -1
- package/dist/on.mjs +1 -1
- package/dist/ordering/keys.mjs +1 -1
- package/dist/ordering.d.mts +1 -1
- package/dist/ordering.mjs +1 -1
- package/dist/pending-operation-Dq4rv-Ml.mjs +2 -0
- package/dist/pending-operation-Dq4rv-Ml.mjs.map +1 -0
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/pg.d.mts +27 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/{physical-CeE2nYmI.mjs → physical-wboFLAg9.mjs} +2 -2
- package/dist/{physical-CeE2nYmI.mjs.map → physical-wboFLAg9.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-DHjdvjwk.d.mts → planner-Ckoxeruk.d.mts} +1 -1
- package/dist/{postgres-CDdh5dSP.mjs → postgres-DQ_pO0hi.mjs} +2 -2
- package/dist/{postgres-CDdh5dSP.mjs.map → postgres-DQ_pO0hi.mjs.map} +1 -1
- package/dist/{postgres-adapter-axapXX8d.mjs → postgres-adapter-Byp7Zpop.mjs} +2 -2
- package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-Byp7Zpop.mjs.map} +1 -1
- package/dist/postgres-adapter-Ia4u0-Ht.mjs +2 -0
- package/dist/postgres-adapter-Ia4u0-Ht.mjs.map +1 -0
- package/dist/postgres-result-CiS5OWp1.mjs +2 -0
- package/dist/postgres-result-CiS5OWp1.mjs.map +1 -0
- package/dist/postgres.d.mts +17 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-Ccsb8PTb.mjs → provider-limits-CCOa4d1E.mjs} +2 -2
- package/dist/{provider-limits-Ccsb8PTb.mjs.map → provider-limits-CCOa4d1E.mjs.map} +1 -1
- package/dist/{provider-parameter-snapshot-BikrgKqI.mjs → provider-parameter-snapshot-C0ehKSAA.mjs} +2 -2
- package/dist/{provider-parameter-snapshot-BikrgKqI.mjs.map → provider-parameter-snapshot-C0ehKSAA.mjs.map} +1 -1
- package/dist/query-Cdy8E2jM.mjs +2 -0
- package/dist/query-Cdy8E2jM.mjs.map +1 -0
- package/dist/{query-inspection-BoG-yAln.mjs → query-inspection-C-T2ttRx.mjs} +2 -2
- package/dist/{query-inspection-BoG-yAln.mjs.map → query-inspection-C-T2ttRx.mjs.map} +1 -1
- package/dist/{raw-Dyq6Y6UX.mjs → raw-uaVIxHcE.mjs} +2 -2
- package/dist/{raw-Dyq6Y6UX.mjs.map → raw-uaVIxHcE.mjs.map} +1 -1
- package/dist/{relation-bound-ku_cMdye.mjs → relation-bound-BaU-LuuI.mjs} +1 -1
- package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-BaU-LuuI.mjs.map} +1 -1
- package/dist/{rule-words-ZIGm7cDm.mjs → rule-words-C4lXzgW2.mjs} +2 -2
- package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-C4lXzgW2.mjs.map} +1 -1
- package/dist/scalar-B9WizsvR.mjs +4 -0
- package/dist/scalar-B9WizsvR.mjs.map +1 -0
- package/dist/schema/introspect.d.mts +2 -2
- package/dist/schema/introspect.mjs +1 -1
- package/dist/schema/json.d.mts +2 -2
- package/dist/schema/json.mjs +1 -1
- package/dist/{schema-BYA-_bpk.mjs → schema-MB-pPNTO.mjs} +2 -2
- package/dist/schema-MB-pPNTO.mjs.map +1 -0
- package/dist/{schema-CFIaebgi.mjs → schema-TthAXPVP.mjs} +2 -2
- package/dist/{schema-CFIaebgi.mjs.map → schema-TthAXPVP.mjs.map} +1 -1
- package/dist/schema-introspection-wMVZowIF.mjs +6 -0
- package/dist/schema-introspection-wMVZowIF.mjs.map +1 -0
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/select-assembly-SuVxJjps.mjs +2 -0
- package/dist/select-assembly-SuVxJjps.mjs.map +1 -0
- package/dist/{serializer-rBq3v1xr.mjs → serializer-B2kk7NAR.mjs} +5 -5
- package/dist/{serializer-rBq3v1xr.mjs.map → serializer-B2kk7NAR.mjs.map} +1 -1
- package/dist/{settled-BjyuA76m.mjs → settled-Dkk5w1vE.mjs} +2 -2
- package/dist/{settled-BjyuA76m.mjs.map → settled-Dkk5w1vE.mjs.map} +1 -1
- package/dist/{snowflake-UOCC820W.mjs → snowflake-6sBLJi34.mjs} +2 -2
- package/dist/{snowflake-UOCC820W.mjs.map → snowflake-6sBLJi34.mjs.map} +1 -1
- package/dist/snowflake.d.mts +2 -2
- package/dist/snowflake.mjs +1 -1
- package/dist/snowflake.mjs.map +1 -1
- package/dist/soft-delete.d.mts +1 -1
- package/dist/soft-delete.mjs +1 -1
- package/dist/{spans-XDUFeTzC.mjs → spans-BE-EjlZK.mjs} +1 -1
- package/dist/{spans-XDUFeTzC.mjs.map → spans-BE-EjlZK.mjs.map} +1 -1
- package/dist/sql-BGjAsoBE.mjs +2 -0
- package/dist/sql-BGjAsoBE.mjs.map +1 -0
- package/dist/{sql-Dl6nykFV.mjs → sql-CFxGrk3K.mjs} +2 -2
- package/dist/{sql-Dl6nykFV.mjs.map → sql-CFxGrk3K.mjs.map} +1 -1
- package/dist/{sql-BVZ8QefY.d.mts → sql-CXtSIPzy.d.mts} +11 -5
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/{sqlite-adapter-Ad0d-m2t.mjs → sqlite-adapter-fIbNDvwO.mjs} +2 -2
- package/dist/{sqlite-adapter-Ad0d-m2t.mjs.map → sqlite-adapter-fIbNDvwO.mjs.map} +1 -1
- package/dist/{sqlite-utils-BRvbmlQ1.mjs → sqlite-utils-DcQct689.mjs} +2 -2
- package/dist/{sqlite-utils-BRvbmlQ1.mjs.map → sqlite-utils-DcQct689.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/{standard-sql-qLcQyCtK.mjs → standard-sql-Bsf5nrla.mjs} +3 -3
- package/dist/standard-sql-Bsf5nrla.mjs.map +1 -0
- package/dist/surrealdb.d.mts +2 -2
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/{surrealql-C1dp1sWw.mjs → surrealql-DY7sgVnJ.mjs} +2 -2
- package/dist/{surrealql-C1dp1sWw.mjs.map → surrealql-DY7sgVnJ.mjs.map} +1 -1
- package/dist/{to-many-BybuKQM1.mjs → to-many-DiP6cOSQ.mjs} +2 -2
- package/dist/{to-many-BybuKQM1.mjs.map → to-many-DiP6cOSQ.mjs.map} +1 -1
- package/dist/{unit-BhHbZyuJ.mjs → unit-CSaAB0su.mjs} +2 -2
- package/dist/{unit-BhHbZyuJ.mjs.map → unit-CSaAB0su.mjs.map} +1 -1
- package/dist/{unit-words-CT0yeqfZ.mjs → unit-words-BGMVZ1MX.mjs} +2 -2
- package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BGMVZ1MX.mjs.map} +1 -1
- package/dist/{utils-CpAojrCj.mjs → utils-BLlgSQIo.mjs} +2 -2
- package/dist/{utils-CpAojrCj.mjs.map → utils-BLlgSQIo.mjs.map} +1 -1
- package/dist/validation-D0LG854o.mjs +2 -0
- package/dist/validation-D0LG854o.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-CZLW7aR3.mjs → validator-CDYlO9HV.mjs} +2 -2
- package/dist/{validator-CZLW7aR3.mjs.map → validator-CDYlO9HV.mjs.map} +1 -1
- package/dist/{values-B4aj1i1f.mjs → values-Byqn5wAh.mjs} +2 -2
- package/dist/{values-B4aj1i1f.mjs.map → values-Byqn5wAh.mjs.map} +1 -1
- package/dist/version-B_ZLWzLW.mjs +2 -0
- package/dist/{version-CXGIA82S.mjs.map → version-B_ZLWzLW.mjs.map} +1 -1
- package/package.json +35 -35
- package/dist/client-DRpX3-vw.mjs +0 -2
- package/dist/client-DRpX3-vw.mjs.map +0 -1
- package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
- package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
- package/dist/every-tOgQmaIE.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
- package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
- package/dist/identifiers-s00pGES8.mjs +0 -2
- package/dist/identifiers-s00pGES8.mjs.map +0 -1
- package/dist/judge-words-CzUyXtJ6.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
- package/dist/methods-part-ZY0f2AV_.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
- package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
- package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
- package/dist/pending-operation-C_eOFOBE.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
- package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
- package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
- package/dist/postgres-result-DF6DmW3r.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
- package/dist/query-BZVHfA0s.mjs +0 -2
- package/dist/query-BZVHfA0s.mjs.map +0 -1
- package/dist/scalar-BHCh7aUz.mjs +0 -4
- package/dist/scalar-BHCh7aUz.mjs.map +0 -1
- package/dist/schema-BYA-_bpk.mjs.map +0 -1
- package/dist/schema-introspection-D0f8cti4.mjs +0 -6
- package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
- package/dist/select-assembly-DVI7d3tf.mjs +0 -2
- package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
- package/dist/sql-3o4DOKm9.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs.map +0 -1
- package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
- package/dist/validation-CYaJ8ndO.mjs +0 -2
- package/dist/validation-CYaJ8ndO.mjs.map +0 -1
- package/dist/version-CXGIA82S.mjs +0 -2
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"schema-BYA-_bpk.mjs","names":["sql","base","#linkFields","#membershipViews","#physicalFields","#storedFieldLists","#clearabilityViews","#restrictingSlotViews","#admitArguments","operation","#queryViewsByAdapter"],"sources":["../src/query-engine/raptor3/shared/insert-value.ts","../src/query-engine/raptor3/shared/terms.ts","../src/query-engine/raptor3/shared/parse-boundary.ts","../src/query-engine/raptor3/shared/storage.ts","../src/query-engine/raptor3/shared/schema.ts"],"sourcesContent":["import type { Dialect } from \"@drivers/types\";\nimport type { Sql } from \"@sql\";\nimport type { Queries } from \"./query\";\nimport type { Input } from \"./schema\";\n\n/**\n * One model's names and values as its client's statements spell them: what a\n * fragment written by hand (a computed value, a filter's expression, a joined\n * source) names tables and columns and binds values with, so it reads what a\n * query of the client would.\n */\nexport interface ModelSql {\n readonly dialect: Dialect;\n /** The model's table, in its namespace, under `alias` where given. */\n table(alias?: string): Sql;\n /** A field's column, qualified by `alias` where given. */\n column(field: string, alias?: string): Sql;\n /** `value` bound as a value of `field` is written and compared. */\n value(field: string, value: unknown): Sql;\n /** An identifier quoted for the dialect: `name(\"r\", \"k\")` is `\"r\".\"k\"`. */\n name(...path: string[]): Sql;\n /**\n * A condition over the model's rows read under `alias`: those the call\n * holding the fragment may see; with `update`, those it may update by\n * writing these fields; with `where`, of those the ones it matches. Only a\n * fragment handed to a model operation holds one: that operation settles\n * it.\n */\n visible(\n alias: string,\n options?: { readonly update?: readonly string[]; readonly where?: object }\n ): Sql;\n}\n\n/** What a computed value is given to compute its values with. */\nexport interface InsertValueContext {\n /** The model written, by its name in the schema. */\n readonly model: string;\n /** The INSERT's rows, every value final but the computed ones. */\n readonly rows: readonly Input[];\n /** The field the value is written to. */\n readonly field: string;\n readonly sql: ModelSql;\n readonly dialect: ModelSql[\"dialect\"];\n /**\n * Run one read in the operation (its transaction, if any) and return its\n * raw rows; absent where the operation cannot read before writing (an\n * array transaction's batch), so the value must be an SQL expression.\n */\n readonly read?: (statement: Sql) => Promise<readonly Input[]>;\n}\n\n/**\n * A create value its extension computes once the rows of one INSERT are\n * final, after every incoming foreign key is assigned: a stamp of the `data`\n * capability that is an instance of this class is written where the caller\n * left the field out, not admitted as data. `compute` answers one value per\n * row it is asked about (the indexes of `rows` whose field holds this\n * instance), each a plain value or an SQL expression the INSERT evaluates.\n * An `update`'s data may hold one too: set aside from admission, its\n * expression is the SET's.\n */\nexport abstract class InsertValue {\n abstract compute(\n context: InsertValueContext,\n indexes: readonly number[]\n ): readonly unknown[] | Promise<readonly unknown[]>;\n}\n\n/**\n * An update value keeping the field as stored: set aside at admission as any\n * `InsertValue`, so no generated update value (`updatedAt()`) fills it,\n * then dropped from the data (an update left with nothing to write is one\n * that writes nothing), and not judged as a field the write writes. A write\n * that places a row without changing it keeps the row's instant so.\n */\nexport class Stored extends InsertValue {\n compute(): never {\n throw new Error(\"Stored is no value: the update leaves its field out\");\n }\n}\n\n/**\n * An `updateMany` value read from a derived table the UPDATE joins: `join`\n * answers that table, aliased, and the condition matching it to the row written, over the\n * target's columns qualified by `target`; `compute` answers the SET\n * expression over the table's columns. The engine joins it (`UPDATE … FROM`,\n * MySQL's `UPDATE … JOIN`), so one statement writes each row its own value\n * and the source is read once, before any row changes.\n */\nexport abstract class JoinedValue extends InsertValue {\n abstract join(\n sql: ModelSql,\n target: string\n ): { readonly source: Sql; readonly on: Sql };\n /**\n * The same values as a list, for a database that joins no derived table:\n * each entry names one row by the values its fields hold and gives the\n * value it takes. The row is written only while it holds them. `read` asks\n * the database in the call's unit.\n */\n abstract rows(\n sql: ModelSql,\n read: (statement: Sql) => Promise<readonly Input[]>\n ): Promise<readonly JoinedEntry[]>;\n}\n\n/** One row a joined value is written to, as a list names it. */\nexport interface JoinedEntry {\n readonly where: Input;\n readonly value: unknown;\n}\n\n/**\n * Each engine's renderer, by its schema then its driver's adapter: what\n * spells a model for a fragment written by hand (`$sql`) names tables and\n * columns and binds values as the engine's queries do.\n */\nexport const renderers = new WeakMap<object, WeakMap<object, Queries>>();\n","import { QueryEngineError, UnsupportedOperationError } from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport { type Sql, sql } from \"@sql\";\n\n/** A model's name, as the schema's keys say it. */\nexport const nameOf = (model: AnyModel): string => model[\"~\"].names.ts!;\n/** A model's table, as the database names it. */\nexport const tableOf = (model: AnyModel): string => model[\"~\"].names.sql!;\n/** The scalars a model declares, by field. */\nexport const scalarsOf = (model: AnyModel) => model[\"~\"].state.scalars;\n/** Parts of a statement, one after the other with a comma between. */\nexport const listed = (parts: readonly Sql[]): Sql => sql.join(parts, \", \");\n/**\n * Whether two values a field holds are one value: an instant is one as a\n * `Date` and as its text, wherever that text places it.\n */\nexport const same = (a: unknown, b: unknown): boolean =>\n a instanceof Date || b instanceof Date\n ? a != null && b != null && +new Date(a as Date) === +new Date(b as Date)\n : String(a) === String(b);\n\n/** Refuses what the engine does not support, in the caller's words. */\nexport function unsupported(message: string): never {\n throw new UnsupportedOperationError(message);\n}\n\n/** Stops on a state the engine itself should never reach. */\nexport function engineFault(message: string): never {\n throw new QueryEngineError(message);\n}\n","import { ValidationError } from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport { type InferOutput, parse, type VibSchema } from \"@validation\";\nimport { readValidationFailureCause } from \"@validation/parse-failure\";\nimport type { Operation } from \"../../types\";\nimport { nameOf } from \"./terms\";\n\n/**\n * THE typed parse boundary (X2 — one home for validation). Every seam that turns a\n * user payload (or a sub-payload: a `where`, a `select`, a nested `create`) into a\n * validated value flows through here. It runs the schema, converts a validation\n * failure into V1's byte-identical {@link ValidationError} (operation name +\n * dotted issue path), and returns the schema's INFERRED output type — the `TOutput`\n * the `ObjectSchema` already computes — instead of erasing it to\n * `Record<string, unknown>`.\n *\n * The lone `as InferOutput<S>` below is the ONLY assertion the engine needs and the\n * ONLY one allowed outside a genuinely untyped I/O edge: after the issues guard the\n * schema has PROVEN `value` matches `S`, but `parse`'s conditional result type keeps\n * `value` erased, so the inferred output is re-attached here — the one place\n * inference cannot reach on its own. This is what makes the in-engine re-validation\n * branches (the `isRecord(result.value)` / `requireRecord` / `requires a … object`\n * guards this boundary replaced) dead: the schema layer already guarantees the shape.\n * The structural gate (parse-boundary-gate.core.test.ts) fails loudly if a future phase\n * reintroduces such a branch or an `as Record<string, unknown>` on a validated path.\n *\n * @param schema a concrete operation/core schema (its `TOutput` is the return type)\n * @param value the raw payload to validate\n * @param operation the operation name carried on the {@link ValidationError}\n * @param path the dotted prefix for issue paths (\"\" for a whole-args validate;\n * a field name like \"where\"/\"select\"/\"createMany\" for a sub-payload)\n * @param model the model the operation addresses, named in the error's\n * `meta.model`, its source and its message subject (`user.create`)\n */\nexport function parseValidated<S extends VibSchema>(\n schema: S,\n value: unknown,\n operation: Operation,\n path: string,\n model: AnyModel\n): InferOutput<S> {\n const result = parse(schema, value);\n if (result.issues) {\n const prefix = path ? [path] : [];\n throw new ValidationError(\n operation,\n result.issues.map((issue) => ({\n path:\n [...prefix, ...(issue.path?.map(String) ?? [])].join(\".\") || \"root\",\n message: issue.message,\n })),\n {\n cause: readValidationFailureCause(result),\n meta: { model: nameOf(model) },\n }\n );\n }\n return result.value as InferOutput<S>;\n}\n","import type { AnyModel } from \"@schema/model\";\nimport type { ClearableMembership } from \"@schema/relation/clearability\";\nimport type {\n DeclaredJunctionFacts,\n ResolvedJunctionMember,\n ResolvedJunctionSide,\n} from \"@schema/relation/junction-topology\";\nimport type { PolymorphicStorageColumn } from \"@schema/relation/polymorphic\";\nimport type { RelationSlot } from \"@schema/relation/types\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport type {\n ResolvedSlot,\n ResolvedStoredReference,\n ResolvedVariantJunctionMember,\n ResolvedVariantRowMember,\n} from \"@schema/validation/relation-resolution\";\nimport type { WriteJudgement } from \"./row-scope\";\nimport type { EngineSchema } from \"./schema\";\nimport { scalarsOf } from \"./terms\";\n\nexport type Membership = {\n scope: Pick<ResolvedSlot, \"edge\" | \"member\">;\n clearability: ClearableMembership;\n name: string;\n source: AnyModel;\n target: AnyModel;\n many: boolean;\n discriminator?: { side: \"source\" | \"target\"; field: string; value: string };\n} & (\n | {\n kind: \"reference\";\n owner: \"source\" | \"target\";\n pairs: readonly { source: string; target: string }[];\n reference?: ResolvedStoredReference;\n }\n | {\n kind: \"junction\";\n table: string;\n sourceSide: ResolvedJunctionSide;\n targetSide: ResolvedJunctionSide;\n uniqueSide?: \"source\" | \"target\";\n /** A declared model holds this junction: its key and its own columns. */\n declared?: DeclaredJunctionFacts;\n }\n);\n\n/**\n * One link row's stored columns, each once. A declared junction's column may\n * serve both sides (`organizationId`), and a statement names it once; the value\n * it holds is the source's, which {@link Link.shared} proved the target's too.\n */\nexport function linkMembers(\n edge: Extract<Membership, { kind: \"junction\" }>\n): readonly {\n readonly side: ResolvedJunctionSide;\n readonly pair: ResolvedJunctionMember;\n}[] {\n const seen = new Set<string>();\n const members: {\n side: ResolvedJunctionSide;\n pair: ResolvedJunctionMember;\n }[] = [];\n for (const side of [edge.sourceSide, edge.targetSide])\n for (const pair of side.members) {\n if (seen.has(pair.junctionField)) continue;\n seen.add(pair.junctionField);\n members.push({ side, pair });\n }\n return members;\n}\n\nexport type PhysicalField = {\n readonly name: string;\n readonly scalar: Scalar;\n /** What the scalar was declared with, and the native type it names: read at every comparison. */\n readonly state: Scalar[\"~\"][\"state\"];\n readonly nativeType: Scalar[\"~\"][\"nativeType\"];\n readonly nullable: boolean;\n /**\n * The KEY a private column stands in for — a polymorphic row carrier's id\n * column — which is what its identifier domain is resolved against\n * (`identifier.ts`). A declared scalar is its own key and carries none.\n */\n readonly reference?: PolymorphicStorageColumn[\"reference\"];\n};\n\n/**\n * What the row a link through `edge` reaches is judged at when the link\n * changes on it (R3): the key fields it holds and its own side of the\n * relation, so a join judges both endpoints, the source by its own data.\n * `undefined` where the source holds the key: the target's row does not\n * change, and is only read.\n */\nexport function linkJudgement(edge: Membership): WriteJudgement | undefined {\n if (edge.kind === \"reference\" && edge.owner === \"source\") return undefined;\n const resolved = edge.scope.edge;\n const writes =\n edge.kind === \"reference\" && resolved.kind === \"foreignKey\"\n ? edge.pairs.map((pair) => pair.target)\n : [];\n const own = (slot: RelationSlot) =>\n slot.source === edge.source && slot.field === edge.name;\n const inverse =\n resolved.kind === \"foreignKey\" || resolved.kind === \"junction\"\n ? resolved.endpoints.find((end) => !own(end))\n : own(resolved.carrier)\n ? edge.scope.member?.inverse\n : resolved.carrier;\n if (inverse) writes.push(inverse.field);\n return { kind: \"update\", writes };\n}\n\n/** Orient the already resolved storage once; no declaration getter or inverse search. */\nexport function bindMembership(\n schema: EngineSchema,\n source: AnyModel,\n name: string,\n variant?: string\n): Membership {\n return schema.membership(source, name, variant);\n}\n\nexport function buildMembershipView(\n schema: EngineSchema,\n source: AnyModel,\n name: string,\n variant?: string\n): Membership {\n const resolved = schema.index.get(source)!.get(name)!;\n const edge = resolved.edge;\n const clearability = schema.clearability(resolved);\n const many =\n source[\"~\"].state.relations[name]![\"~\"].state.cardinality === \"many\";\n /**\n * One variant-carrier member: the slot's own bound member, or the arm the\n * caller named. A carrier addressed with no variant names every arm at once,\n * which this one-membership view cannot represent; the caller addresses an arm\n * or composes the arms itself (g4/unit02/note.md §10.3).\n *\n * INVARIANT, not a refusal (N4 row 49). Every caller reads the slot first: a\n * bound inverse carries `resolved.member`, a carrier slot is walked arm by arm\n * over `edge.members`, and the one arm name a payload supplies is the tagged\n * grammar's `type`, which validation pins to a literal union of the configured\n * public variants before the engine sees it.\n */\n const arm = <Member extends { readonly variant: string }>(\n members: readonly Member[]\n ) => {\n const member = ((resolved.member as Member | undefined) ??\n members.find((each) => each.variant === variant))!;\n const direct = resolved.member === undefined;\n return {\n member,\n direct,\n base: {\n scope: { edge, member },\n clearability,\n name: direct ? `${name}.${member.variant}` : name,\n source,\n many,\n },\n };\n };\n if (edge.kind === \"variantRowCarrier\") {\n const { member, direct, base } = arm<ResolvedVariantRowMember>(\n edge.members\n );\n return {\n ...base,\n target: direct ? member.targetModel : edge.carrier.source,\n kind: \"reference\",\n owner: direct ? \"source\" : \"target\",\n pairs: [\n {\n source: direct ? edge.storage.idColumn.name : member.referencedField,\n target: direct ? member.referencedField : edge.storage.idColumn.name,\n },\n ],\n discriminator: {\n side: direct ? \"source\" : \"target\",\n field: edge.storage.typeColumn.name,\n value: member.entry.storedValue,\n },\n };\n }\n if (edge.kind === \"variantJunctionCarrier\") {\n const { member, direct, base } = arm<ResolvedVariantJunctionMember>(\n edge.members\n );\n return {\n ...base,\n target: direct\n ? member.topology.target.model\n : member.topology.source.model,\n kind: \"junction\",\n table: member.topology.table,\n sourceSide: direct ? member.topology.source : member.topology.target,\n targetSide: direct ? member.topology.target : member.topology.source,\n uniqueSide: member.uniqueTarget\n ? direct\n ? \"target\"\n : \"source\"\n : undefined,\n };\n }\n const endpoint = edge.endpoints[0];\n const opposite =\n endpoint.source === source && endpoint.field === name\n ? edge.endpoints[1]\n : endpoint;\n const base = {\n scope: resolved,\n clearability,\n name,\n source,\n target: opposite.source,\n many,\n };\n if (edge.kind === \"foreignKey\") {\n const owns = edge.owner.source === source && edge.owner.field === name;\n return {\n ...base,\n kind: \"reference\",\n owner: owns ? \"source\" : \"target\",\n reference: edge.reference,\n pairs: edge.reference.members.map((pair) => ({\n source: owns ? pair.foreignField : pair.referencedField,\n target: owns ? pair.referencedField : pair.foreignField,\n })),\n };\n }\n const topology = edge.topology;\n // The SLOT decides, not the model: a self junction names one model on both\n // sides and only its two fields tell the directions apart. `opposite` above\n // already resolved that identity, and `endpoints[0]`/`endpoints[1]` are the\n // slots `topology.source`/`topology.target` were built from.\n const forward = opposite === edge.endpoints[1];\n return {\n ...base,\n kind: \"junction\",\n table: topology.table,\n sourceSide: forward ? topology.source : topology.target,\n targetSide: forward ? topology.target : topology.source,\n declared: topology.declared,\n };\n}\n\n/** The fields of the row it leaves that one hop of `edge` reads. */\nexport function hopFieldsOf(edge: Membership): readonly string[] {\n return edge.kind === \"reference\"\n ? sideFields(edge, \"source\")\n : edge.sourceSide.members.map((member) => member.referencedField);\n}\n\n/** The fields a reference holds on one side, its discriminator first. */\nexport const sideFields = (\n edge: Extract<Membership, { kind: \"reference\" }>,\n side: \"source\" | \"target\"\n): string[] => [\n ...(edge.discriminator?.side === side ? [edge.discriminator.field] : []),\n ...edge.pairs.map((pair) => pair[side]),\n];\n\n/** Private carrier columns are resolved schema fields, never public scalar declarations. */\nexport function physicalField(\n schema: EngineSchema,\n model: AnyModel,\n field: string\n): PhysicalField {\n return schema.physicalField(model, field);\n}\n\n/**\n * The private `(type, id)` columns this model's variant ROW carriers store, in\n * declaration order. ONE enumeration of them, so what a field resolves to and\n * what {@link buildStoredFieldsView} says the row stores cannot drift apart.\n */\nfunction carrierColumns(\n schema: EngineSchema,\n model: AnyModel\n): PolymorphicStorageColumn[] {\n const columns: PolymorphicStorageColumn[] = [];\n for (const { edge, member } of schema.index.get(model)!.values())\n if (edge.kind === \"variantRowCarrier\" && !member)\n columns.push(edge.storage.typeColumn, edge.storage.idColumn);\n return columns;\n}\n\n/**\n * INVARIANT, not a refusal (N4 row 48): a model stores its declared scalars and\n * its row carriers' columns, and nothing asks this owner for anything else. A\n * field name arrives from admission, which matched it against the model's\n * declared scalar keys, or from the resolved topology itself — a membership\n * pair, a carrier discriminator, a junction side's referenced field, a row key,\n * or {@link buildStoredFieldsView}, which enumerates exactly those two sets.\n */\nexport function buildPhysicalFieldView(\n schema: EngineSchema,\n model: AnyModel,\n field: string\n): PhysicalField {\n const scalar = scalarsOf(model)[field];\n const view = scalar\n ? {\n name: model[\"~\"].getFieldName(field).sql,\n scalar,\n nullable: scalar[\"~\"].state.nullable === true,\n }\n : carrierColumns(schema, model).find(\n (candidate) => candidate.name === field\n )!;\n const { state, nativeType } = view.scalar[\"~\"];\n return { ...view, state, nativeType };\n}\n\nexport function buildStoredFieldsView(\n schema: EngineSchema,\n model: AnyModel\n): string[] {\n return [\n ...model[\"~\"].scalarFieldNames,\n ...carrierColumns(schema, model).map((column) => column.name),\n ];\n}\n","import type { EngineFacts } from \"@adapters/database-adapter\";\nimport type { AnyDriver } from \"@drivers/exports\";\nimport { UnsupportedOperationError } from \"@errors\";\nimport { hydrateSchemaNames, type Schema } from \"@schema/hydration\";\nimport { type AnyModel, getModelKeyCatalog } from \"@schema/model\";\nimport {\n type ClearableMembership,\n clearableMembership,\n} from \"@schema/relation/clearability\";\nimport { resolveSchemaOrThrow } from \"@schema/validation\";\nimport {\n foreignKeyOnDelete,\n junctionOnDelete,\n type ResolvedSlot,\n} from \"@schema/validation/relation-resolution\";\nimport { createResolvedSchemaRegistry } from \"@validation/builder\";\nimport type { NormalizedRecurrence } from \"@validation/relations/recurrence\";\nimport type { VibSchema } from \"@validation/types\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { InsertValue, Stored } from \"./insert-value\";\nimport { parseValidated } from \"./parse-boundary\";\nimport type { Leaf, PreparedProjection } from \"./query\";\nimport {\n buildMembershipView,\n buildPhysicalFieldView,\n buildStoredFieldsView,\n type Membership,\n type PhysicalField,\n} from \"./storage\";\nimport { scalarsOf } from \"./terms\";\n\nexport type Input = Record<string, unknown>;\nexport type ReadOperation =\n | \"findMany\"\n | \"findUnique\"\n | \"findFirst\"\n | \"count\"\n | \"exist\"\n | \"aggregate\"\n | \"groupBy\";\nexport type Operation =\n | \"create\"\n | \"createMany\"\n | \"update\"\n | \"upsert\"\n | \"updateMany\"\n | \"delete\"\n | \"deleteMany\"\n | ReadOperation;\n\nconst READ_OPERATIONS: ReadonlySet<string> = new Set<ReadOperation>([\n \"findMany\",\n \"findUnique\",\n \"findFirst\",\n \"count\",\n \"exist\",\n \"aggregate\",\n \"groupBy\",\n]);\n\n/** One classification of an admitted operation; a read allocates no write work. */\nexport function isReadOperation(\n operation: Operation\n): operation is ReadOperation {\n return READ_OPERATIONS.has(operation);\n}\n/**\n * The client's already-resolved schema views. A client that composed them once\n * hands them over by identity; the candidate never re-hydrates or re-validates\n * a schema a caller already resolved (g4/unit03/note.md B-3).\n */\nexport interface ResolvedSchemaViews {\n readonly index: ReturnType<typeof resolveSchemaOrThrow>;\n /**\n * Declared as the one member {@link EngineSchema} reads. A client hands over\n * its full resolved registry; anything carrying `getModelSchemas` satisfies\n * this, nothing is widened, and no consumer here reads `proxy`.\n */\n readonly registry: Pick<\n ReturnType<typeof createResolvedSchemaRegistry>,\n \"getModelSchemas\"\n >;\n}\nexport interface EngineConfig {\n schema: Schema;\n driver: AnyDriver;\n resolved?: ResolvedSchemaViews;\n}\nexport interface Arguments extends Input {\n data: Input;\n create?: Input;\n update?: Input;\n where?: Input;\n targetWhere?: Input;\n setWhere?: Input;\n select?: Input;\n include?: Input;\n orderBy?: Input | Input[];\n take?: number;\n skip?: number;\n cursor?: Input;\n distinct?: string[];\n by?: string[];\n having?: Input;\n limit?: number;\n omit?: Input;\n recurse?: NormalizedRecurrence;\n skipDuplicates?: boolean;\n _count?: true | Input;\n _avg?: Input;\n _sum?: Input;\n _min?: Input;\n _max?: Input;\n}\n\n/**\n * The two update operators whose result a provider ROUNDS — the ones an exact\n * decimal row key cannot carry portably, and the ones phase 2 made reachable.\n */\nconst ROUNDING_KEY_UPDATES: readonly string[] = [\"multiply\", \"divide\"];\n\n/**\n * Every operation a key update may name, in the shipped engine's own order\n * (`operations/mutation-identity.ts` `assertPortablePrimaryKeyUpdateInput`),\n * because the refusal sentence lists them in it.\n */\nconst KEY_UPDATE_OPERATIONS = [\n \"set\",\n \"increment\",\n \"decrement\",\n \"multiply\",\n \"divide\",\n] as const;\n\n/** These casts attach the existing admission schema's dynamic model correlation. */\nexport function record(value: unknown): Input {\n return value as Input;\n}\nexport function entries(value: unknown): Input[] {\n return Array.isArray(value) ? value : [record(value)];\n}\n/** `key`'s view in `views`, created on its first use and kept as long as `views`. */\nexport function memo<K, V>(\n views: { get(key: K): V | undefined; set(key: K, value: V): unknown },\n key: K,\n create: () => V\n): V {\n let view = views.get(key);\n if (view === undefined) {\n view = create();\n views.set(key, view);\n }\n return view;\n}\n\n/**\n * What this engine resolves once per (adapter, model) and never again.\n *\n * Both members are a pure function of the schema and the dialect, which is why\n * they may be shared at all (rule 1): a scalar leaf is the field's declared\n * type, nullability and the adapter's own `dateTime` representation; the\n * DEFAULT projection is `scalarFieldNames` minus the model's own `omit`, and an\n * operation-level `omit` never reaches the projection owner — admission\n * desugars it into `select`, which takes the per-operation path. Nothing\n * admitted and nothing a provider answered is stored (rule 5).\n *\n * The two member types are the query owner's, imported for their names only:\n * `import type` adds no runtime edge, so `shared/query.ts` keeps its one\n * runtime import of this file and this file keeps none of it.\n */\nexport type QueryViews = {\n readonly leaves: WeakMap<AnyModel, Map<string, Leaf>>;\n readonly defaultProjections: WeakMap<AnyModel, PreparedProjection>;\n};\n\nconst createQueryViews = (): QueryViews => ({\n leaves: new WeakMap(),\n defaultProjections: new WeakMap(),\n});\n\nconst NO_KEY: readonly string[] = [];\n\nexport class EngineSchema {\n readonly index;\n readonly registry;\n readonly #linkFields = new WeakMap<\n AnyModel,\n {\n readonly required: readonly string[];\n readonly defaults: readonly string[];\n }\n >();\n readonly #membershipViews = new WeakMap<\n AnyModel,\n Map<string, Map<string | undefined, Membership>>\n >();\n readonly #physicalFields = new WeakMap<\n AnyModel,\n Map<string, PhysicalField>\n >();\n readonly #storedFieldLists = new WeakMap<AnyModel, readonly string[]>();\n readonly #clearabilityViews = new WeakMap<\n ResolvedSlot,\n ClearableMembership\n >();\n readonly #restrictingSlotViews = new WeakMap<AnyModel, readonly string[]>();\n readonly schema: Schema;\n constructor(schema: Schema, resolved?: ResolvedSchemaViews) {\n this.schema = schema;\n if (resolved) {\n this.index = resolved.index;\n this.registry = resolved.registry;\n return;\n }\n hydrateSchemaNames(schema);\n this.index = resolveSchemaOrThrow(schema);\n this.registry = createResolvedSchemaRegistry(schema, this.index);\n }\n admit(model: AnyModel, operation: Operation, raw: unknown): Arguments {\n const admitted = this.#admitArguments(model, operation, raw);\n // What a key may be rewritten with is judged where an update is admitted;\n // an upsert's update arm is judged where it runs, on the row found.\n if (operation === \"update\" || operation === \"updateMany\") {\n const refusal = this.keyPortabilityRefusal(model, admitted.data);\n if (refusal) throw refusal;\n }\n return admitted;\n }\n #admitArguments(\n model: AnyModel,\n operation: Operation,\n raw: unknown\n ): Arguments {\n const schema = this.registry.getModelSchemas(model).args[operation];\n // A value the statement computes (`InsertValue`)\n // is no payload: it is set aside here and written as it is. A field kept\n // as stored (`Stored`) is set aside too, so no generated update value\n // (`updatedAt()`) fills it, and is then not written at all.\n const computed: Input = {};\n const kept: string[] = [];\n const input =\n (operation === \"update\" || operation === \"updateMany\") &&\n isRecord(raw) &&\n isRecord(raw.data)\n ? {\n ...raw,\n data: Object.fromEntries(\n Object.entries(raw.data)\n .filter(([field, value]) => {\n if (!(value instanceof InsertValue)) return true;\n if (value instanceof Stored) kept.push(field);\n else computed[field] = value;\n return false;\n })\n .sort(([left], [right]) => {\n const isVariant = (name: string) =>\n model[\"~\"].state.relations[name]?.[\"~\"].state.target\n .kind === \"variants\";\n return Number(isVariant(left)) - Number(isVariant(right));\n })\n ),\n }\n : raw;\n const admitted = parseValidated(\n schema,\n input,\n operation,\n \"\",\n model\n ) as Arguments;\n if (Object.keys(computed).length === 0 && kept.length === 0)\n return admitted;\n const data: Record<string, unknown> = {\n ...(admitted.data as Input),\n ...computed,\n };\n for (const field of kept) delete data[field];\n return { ...admitted, data };\n }\n /**\n * The row key's PORTABILITY contract for the two operators phase 2 made\n * reachable, as one refusal the caller raises where the shipped engine raises\n * it — never a second walker, never a second sentence.\n *\n * A key's post-update value has to be NAMEABLE: a non-returning readback and\n * every dependent's key transition address the row by it. `multiply` and\n * `divide` carry a provider-chosen rounding on a `number` or `decimal` key\n * that no engine can name portably, and a `divide` by zero has no value at\n * all, so the shipped engine refuses both from its own validator\n * (`assertPortablePrimaryKeyUpdateInput`). Until phase 2 implemented the two\n * operators the candidate answered \"not implemented\" for every one of these\n * payloads; implementing them is what brought the shapes within reach, so the\n * refusals arrive with them, in the shipped engine's own sentences.\n *\n * WHAT it says is the shipped assertion with exactly ONE adopted divergence,\n * R-D2 (a) (Arnaud, 2026-09-15): an EXACT-DOMAIN arithmetic update of a\n * `decimal` key — `increment` / `decrement` — is supported, because it is\n * exact in coefficient space, and the registered G3 witness\n * `tests/raptor3/g3/review-execution-boundaries.test.ts` pins that capability.\n * `multiply` / `divide` on the same key still carry the provider's rounding,\n * so they stay refused. Everything else is parity: R-D2 (b), a `number` key\n * under any arithmetic, and R-D2 (c), `set` beside another operation, answer\n * the shipped sentences (they used to be divergences, pinned on both engines;\n * the decision reverted them). The shipped non-finite-operand arm is\n * deliberately NOT mirrored — after the rules below it is reachable only for\n * an `int`/`bigint` key, whose validation refuses a non-finite operand, so it\n * would be a guard whose unique coverage cannot be named.\n *\n * WHERE it is raised belongs to each caller, because the shipped engine does\n * not raise it in one place: `admit` raises it for `update`/`updateMany`, and\n * the upsert's found arm carries it (`commands.ts`) exactly when the update\n * payload names relations — the shipped gate, note §R3.1. A wider placement\n * refuses requests the shipped engine performs, including an upsert that\n * CREATES a row the arithmetic never touches.\n */\n keyPortabilityRefusal(model: AnyModel, data: unknown): Error | undefined {\n if (!isRecord(data)) return undefined;\n for (const keyField of this.keys(model)) {\n const update = data[keyField];\n if (!isRecord(update)) continue;\n const named = KEY_UPDATE_OPERATIONS.filter(\n (operation) => update[operation] !== undefined\n );\n if (named.length !== 1)\n return new UnsupportedOperationError(\n `Primary key field '${keyField}' accepts exactly one update operation; received ${named.join(\", \") || \"none\"}.`\n );\n const operation = named[0]!;\n if (operation === \"set\") continue;\n const scalarType = scalarsOf(model)[keyField]?.[\"~\"].state.type;\n if (\n scalarType === \"number\" ||\n (scalarType === \"decimal\" && ROUNDING_KEY_UPDATES.includes(operation))\n )\n return new UnsupportedOperationError(\n `Arithmetic updates are not portable for ${scalarType} primary key field '${keyField}'. Use an explicit set value.`\n );\n if (update.divide === 0 || update.divide === 0n)\n return new UnsupportedOperationError(\n `Cannot divide primary key field '${keyField}' by zero.`\n );\n }\n return undefined;\n }\n /**\n * Scalar values admitted as a create admits them, field by field through\n * each field's own create schema: a partial source (the fields a stamp\n * writes), so the model's required fields are not asked for, and a field a\n * create takes but an update refuses (`s.dateTime().now()`) is admitted.\n */\n createValues(model: AnyModel, source: Input): Input {\n const scalars = this.registry.getModelSchemas(model).scalars as Record<\n string,\n { readonly create: VibSchema }\n >;\n const admitted: Input = {};\n for (const [field, value] of Object.entries(source))\n admitted[field] = parseValidated(\n scalars[field]!.create,\n value,\n \"create\",\n field,\n model\n );\n return admitted;\n }\n /**\n * The fields of a declared junction beside its two sides' (`members`).\n * `required`: those a link cannot fill itself, required as a create\n * requires them; a write must state them. `defaults`: those its own create\n * schema fills when it is given nothing; a field whose schema answers\n * nothing (nullable, or the database's own default) stays out of the\n * INSERT, and the column takes what it takes for any row. Asked once per\n * model: a junction model holds one pair (JT010).\n */\n linkFields(model: AnyModel, members: readonly string[]) {\n return memo(this.#linkFields, model, () => {\n const scalars = scalarsOf(model);\n const beside = Object.keys(scalars).filter(\n (field) => !members.includes(this.physicalField(model, field).name)\n );\n return {\n required: beside.filter(\n (field) => scalars[field]![\"~\"].state.optional !== true\n ),\n defaults: beside.filter(\n (field) =>\n scalars[field]![\"~\"].state.hasDefault === true &&\n this.createValues(model, { [field]: undefined })[field] !==\n undefined\n ),\n };\n });\n }\n /** What an update writes of a row, admitted as an update's data is. */\n update(model: AnyModel, source: Input): Input {\n return record(\n parseValidated(\n this.registry.getModelSchemas(model).core.update,\n source,\n \"updateMany\",\n \"data\",\n model\n )\n );\n }\n /** The fields of a model's row key: none where the model has no key. */\n keys(model: AnyModel): readonly string[] {\n return getModelKeyCatalog(model).rowKey?.fields ?? NO_KEY;\n }\n identity(model: AnyModel, row: Input): Input {\n const identity: Input = {};\n for (const field of this.keys(model)) identity[field] = row[field];\n return identity;\n }\n membership(model: AnyModel, name: string, variant?: string): Membership {\n const modelViews = memo(this.#membershipViews, model, () => new Map());\n const slotViews = memo(modelViews, name, () => new Map());\n return memo(slotViews, variant, () =>\n buildMembershipView(this, model, name, variant)\n );\n }\n /**\n * The slots through which the database refuses a hard delete of a `model` row\n * while a member exists: an incoming foreign key, or the junction key on this\n * model's side, whose ON DELETE is `restrict` or `noAction`. The actions are\n * the schema's own answer (`foreignKeyOnDelete`, `junctionOnDelete`), the one\n * the migration spells. A polymorphic carrier stores no constraint.\n */\n restrictingSlots(model: AnyModel): readonly string[] {\n return memo(this.#restrictingSlotViews, model, () => {\n const found: string[] = [];\n for (const [name, resolved] of this.index.get(model) ?? []) {\n const edge = resolved.edge;\n if (edge.kind !== \"foreignKey\" && edge.kind !== \"junction\") continue;\n const view = this.membership(model, name);\n const action =\n view.kind === \"junction\"\n ? junctionOnDelete(view.sourceSide)\n : edge.kind === \"foreignKey\" && view.owner === \"target\"\n ? foreignKeyOnDelete(edge)\n : undefined;\n if (action === \"restrict\" || action === \"noAction\") found.push(name);\n }\n return found;\n });\n }\n clearability(resolved: ResolvedSlot): ClearableMembership {\n return memo(this.#clearabilityViews, resolved, () => {\n const view = clearableMembership(resolved);\n if (view.kind === \"columns\") view.fields;\n return view;\n });\n }\n physicalField(model: AnyModel, field: string): PhysicalField {\n let fields = this.#physicalFields.get(model);\n if (!fields) {\n fields = new Map();\n this.#physicalFields.set(model, fields);\n }\n let descriptor = fields.get(field);\n if (!descriptor) {\n descriptor = buildPhysicalFieldView(this, model, field);\n fields.set(field, descriptor);\n }\n return descriptor;\n }\n /**\n * One adapter's {@link QueryViews}, created on its first use.\n *\n * `EngineSchema` already owns the lazy immutable per-model views this engine\n * resolves from the schema alone, but these two are also a fact of the\n * DIALECT — a scalar leaf carries the adapter's own `dateTime`\n * representation — and a `Queries` instance is per-operation for writes, so\n * neither owner alone can hold them. The adapter is the second key and it is\n * held weakly, so a view store lives exactly as long as the adapter it\n * describes. What it may hold is what every view here may hold: facts\n * derived from the schema and the dialect, never an admitted input, an\n * alias, an operation demand or a provider row (rule 5).\n *\n * The accessor names its one fact, like every other view on this class, so\n * the store cannot be reached for a second shape: an anonymous\n * `scope(adapter, create)` would hand a second caller the first caller's\n * object under the second caller's type, and the cast would hide it.\n */\n readonly #queryViewsByAdapter = new WeakMap<EngineFacts, QueryViews>();\n queryViews(adapter: EngineFacts): QueryViews {\n return memo(this.#queryViewsByAdapter, adapter, createQueryViews);\n }\n storedFields(model: AnyModel): readonly string[] {\n return memo(this.#storedFieldLists, model, () =>\n buildStoredFieldsView(this, model)\n );\n }\n /**\n * The admitted payload's scalar fields, in the model's own scalar order.\n *\n * One pass into one object. The model's scalar order is already memoised by\n * the model itself (`schema/model/model.ts`, `_scalarFieldNames ??=`), so the\n * only per-call cost left was the three intermediates\n * `Object.fromEntries(names.filter(…).map(…))` built — on a normalization\n * every row of every `createMany` crosses (`g4/cutover/perf-diagnosis.md`\n * §4.2). Same keys, same order, same values.\n */\n scalars(model: AnyModel, admitted: Input): Input {\n const values: Input = {};\n for (const field of model[\"~\"].scalarFieldNames) {\n const value = admitted[field];\n if (value !== undefined) values[field] = value;\n }\n return values;\n }\n}\n"],"mappings":"mZA8DA,IAAsB,YAAtB,KAAkC,GAcrB,OAAb,cAA4B,WAAY,CACtC,SAAiB,CACf,MAAU,MAAM,sDAAsD,GAYpD,YAAtB,cAA0C,WAAY,GA4BtD,MAAa,EAAY,IAAI,QCjHhB,OAAU,GAA4B,EAAM,KAAK,MAAM,GAEvD,QAAW,GAA4B,EAAM,KAAK,MAAM,IAExD,UAAa,GAAoB,EAAM,KAA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W,EAAO,EAAK,CACnC,EACJ,EAAK,OAAS,WACV,EAAiB,EAAK,WAAW,CACjC,EAAK,OAAS,cAAgB,EAAK,QAAU,SAC3C,EAAmB,EAAK,CACxB,IAAA,IACJ,IAAW,YAAc,IAAW,aAAY,EAAM,KAAK,EAAK,CAEtE,OAAO,GACP,CAEJ,aAAa,EAA6C,CACxD,OAAO,KAAK,MAAA,EAAyB,MAAgB,CACnD,IAAM,EAAO,EAAoB,EAAS,CAE1C,OADI,EAAK,OAAS,WAAW,EAAK,OAC3B,GACP,CAEJ,cAAc,EAAiB,EAA8B,CAC3D,IAAI,EAAS,MAAA,EAAqB,IAAI,EAAM,CACvC,IACH,EAAS,IAAI,IACb,MAAA,EAAqB,IAAI,EAAO,EAAO,EAEzC,IAAI,EAAa,EAAO,IAAI,EAAM,CAKlC,OAJK,IACH,EAAa,uBAAuB,KAAM,EAAO,EAAM,CACvD,EAAO,IAAI,EAAO,EAAW,EAExB,EAoBT,GAAgC,IAAI,QACpC,WAAW,EAAkC,CAC3C,OAAO,KAAK,MAAA,EAA2B,EAAS,iBAAiB,CAEnE,aAAa,EAAoC,CAC/C,OAAO,KAAK,MAAA,EAAwB,MAClC,sBAAsB,KAAM,EAAM,CACnC,CAYH,QAAQ,EAAiB,EAAwB,CAC/C,IAAM,EAAgB,EAAE,CACxB,IAAK,IAAM,KAAS,EAAM,KAAK,iBAAkB,CAC/C,IAAM,EAAQ,EAAS,GACnB,IAAU,IAAA,KAAW,EAAO,GAAS,GAE3C,OAAO"}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{f as t,t as n}from"./validation--qS7OPmg.mjs";import{n as r,t as i}from"./routed-operations-wytpbYKv.mjs";import{x as a}from"./scalar-BHCh7aUz.mjs";import{n as o}from"./validator-CZLW7aR3.mjs";import{$ as s,it as c,nt as l,ot as u,tt as d}from"./query-BZVHfA0s.mjs";import{t as f}from"./hydration-A3zffFWP.mjs";import{i as p,r as m,u as h}from"./validation-CYaJ8ndO.mjs";import{t as g}from"./types-DtDnXhwa.mjs";import{t as _}from"./result-parsing-B0Y4KGDT.mjs";function classifyAggregateLeaf(e,t,n){let r=Object.hasOwn(n,t)?n[t]:void 0;return e===`_count`?t===`_all`||r?{kind:`count`,nullable:!1}:{kind:`unknown`}:r?e===`_avg`&&r[`~`].state.type!==`decimal`?{kind:`number`,nullable:!0}:e===`_sum`?{kind:`widenedSum`,nullable:!0,scalar:r}:{kind:`scalar`,nullable:!0,scalar:r}:{kind:`unknown`}}function classifyResultColumn(e,t,n){if(t===l)return{kind:`empty`};if(t===d)return{kind:`distance`,scalar:n.distanceScalar};let r=e[`~`].state.scalars,i=Object.hasOwn(r,t)?r[t]:void 0;if(i)return{kind:`scalar`,key:t,scalar:i};if(t===c)return{kind:`relationCounts`,relations:n.relationCounts};let a=e[`~`].state.relations,o=Object.hasOwn(a,t)?a[t]:void 0;if(o){if(g(o[`~`].state)){let e=n.polymorphic.get(t);return e?{kind:`polymorphic`,key:t,relation:o,expected:e}:{kind:`unknown`,key:t}}let e=n.relations.get(t);return e?{kind:`relation`,key:t,relation:o,expected:e}:{kind:`unknown`,key:t}}let s=u(t);if(s){let e=n.aggregates.get(t);return e?{kind:`aggregate`,name:s,expected:e}:{kind:`unknown`,key:t}}return{kind:`unknown`,key:t}}const v=/^[A-Za-z_$][A-Za-z0-9_$]*$/,y={kind:`atom`,value:`null`};function atom(e){return{kind:`atom`,value:e}}function arrayOf(e,t=!1){return{kind:`array`,element:e,immutable:t}}function objectOf(e){return{kind:`object`,fields:e}}function unionOf(...e){let t=[],n=new Set;for(let r of e){let e=r.kind===`union`?r.members:[r];for(let r of e){let e=renderType(r,0);n.has(e)||(n.add(e),t.push(r))}}let[r]=t;return r?t.length===1?r:{kind:`union`,members:t}:atom(`never`)}function renderPropertyName(e){return v.test(e)?e:JSON.stringify(e)}function indentation(e){return` `.repeat(e)}function renderType(e,n){switch(e.kind){case`atom`:return e.value;case`array`:return`${e.immutable?`ReadonlyArray`:`Array`}<${renderType(e.element,n)}>`;case`union`:return e.members.map(e=>renderType(e,n)).join(` | `);case`object`:{if(e.fields.length===0)return`{}`;let t=indentation(n+1);return`{
|
|
2
|
-
${e.fields.map(e=>{let r=e.immutable?`readonly `:``,i=e.optional?`?`:``;return`${t}${r}${renderPropertyName(e.name)}${i}: ${renderType(e.type,n+1)};`}).join(`
|
|
3
|
-
`)}
|
|
4
|
-
${indentation(n)}}`}default:throw new t(`The TypeScript renderer received an unknown node.`)}}function enumType(e){let n=Reflect.get(e[`~`].state.base,`values`);if(!(Array.isArray(n)&&n.every(e=>typeof e==`string`)))throw new t(`An enum scalar has no readable string values.`);return unionOf(...n.map(e=>atom(JSON.stringify(e))))}const b=Object.freeze({string:`string`,time:`string`,int:`number`,number:`number`,decimal:`import("viborm").Decimal`,boolean:`boolean`,datetime:`Date`,date:`Date`,bigint:`bigint`,json:`unknown`,blob:`Uint8Array`});function scalarType(e){let n=e[`~`].state,r;if(Object.hasOwn(b,n.type))r=atom(b[n.type]);else if(n.type===`vector`)r=arrayOf(atom(`number`));else if(n.type===`point`)r=objectOf([{name:`longitude`,type:atom(`number`)},{name:`latitude`,type:atom(`number`)}]);else if(n.type===`enum`)r=enumType(e);else throw new t(`The TypeScript renderer does not support this scalar type.`);return n.array&&(r=arrayOf(r)),n.nullable?unionOf(r,y):r}function requiredRelationShape(e,n){if(n)return n;throw new t(`The result shape for relation '${e}' is absent.`)}function requiredPolymorphicShape(e,n){if(n)return n;throw new t(`The result shape for polymorphic relation '${e}' is absent.`)}function aggregateLeafType(e){switch(e.kind){case`count`:case`number`:return e.nullable?unionOf(atom(`number`),y):atom(`number`);case`scalar`:case`widenedSum`:return unionOf(scalarType(e.scalar),y);case`unknown`:throw new t(`The aggregate result contains an unknown field.`);default:throw new t(`The TypeScript renderer received an unknown aggregate leaf.`)}}function aggregateType(e,n,r){if(n===`_count`&&r?.fields===void 0)return atom(`number`);if(!r?.fields)throw new t(`The result shape for aggregate '${n}' is absent.`);return objectOf([...r.fields].map(t=>({name:t,type:aggregateLeafType(classifyAggregateLeaf(n,t,e[`~`].state.scalars))})))}function polymorphicType(e,t){let n=[];for(let[r,i]of e.variants)n.push(objectOf([{name:`type`,type:atom(JSON.stringify(r)),immutable:!0},{name:`data`,type:rowType(i.model,i.shape,t),immutable:!0}]));let r=n.length===0?atom(`never`):unionOf(...n);return e.cardinality===`many`?arrayOf(r,!0):e.optional?unionOf(r,y):r}function relationValue(e,t){return e.cardinality===`many`?arrayOf(t):e.optional?unionOf(t,y):t}function recursiveRowType(e,t,n,r){let i={name:`VibORMRecursiveNode${r.length+1}`,type:atom(`never`)};r.push(i);let a=atom(i.name);return i.type=objectOf([...rowFields(t.model,t.shape,r),{name:e,type:relationValue(t,a),...n===!1?{}:{optional:!0}}]),a}function rowType(e,t,n){return objectOf(rowFields(e,t,n))}function rowFields(e,n,r){let i=[];for(let a of n.rawKeys){let o=classifyResultColumn(e,a,n);switch(o.kind){case`empty`:break;case`distance`:i.push({name:`_distance`,type:o.scalar?.[`~`].state.type===`point`&&o.scalar[`~`].state.nullable?unionOf(atom(`number`),y):atom(`number`)});break;case`scalar`:i.push({name:o.key,type:scalarType(o.scalar)});break;case`relation`:{let e=requiredRelationShape(o.key,o.expected),t=e.recurrence?recursiveRowType(o.key,e,e.recurrence.depth,r):rowType(e.model,e.shape,r);i.push({name:o.key,type:relationValue(e,t)});break}case`polymorphic`:i.push({name:o.key,type:polymorphicType(requiredPolymorphicShape(o.key,o.expected),r)});break;case`relationCounts`:if(!o.relations)throw new t(`The relation-count result shape is absent.`);i.push({name:`_count`,type:objectOf([...o.relations].map(e=>({name:e,type:atom(`number`)})))});break;case`aggregate`:i.push({name:o.name,type:aggregateType(e,o.name,o.expected)});break;case`unknown`:throw new t(`The result shape contains unknown column '${o.key}'.`);default:throw new t(`The TypeScript renderer received an unknown result column.`)}}return i}function countType(e){return e.rawKeys.length===1&&e.rawKeys[0]===_?atom(`number`):objectOf(e.rawKeys.map(e=>({name:e,type:atom(`number`)})))}function operationResultType(e,n,r,i,a){if((n===`createMany`||n===`updateMany`||n===`deleteMany`)&&r===n)return renderType(objectOf([{name:`count`,type:atom(`number`)}]),0);let o=s(e,r,i,a);if(!o)throw new t(`Operation '${n}' has no renderable result shape.`);let c=[],l=o.carrier===`existence`?atom(`boolean`):o.carrier===`count`?countType(o):rowType(e,o,c);return n===`findMany`||n===`groupBy`||r===`createManyAndReturn`||r===`updateManyAndReturn`||r===`deleteManyAndReturn`?l=arrayOf(l):(n===`findFirst`||n===`findUnique`)&&(l=unionOf(l,y)),c.length===0?renderType(l,0):[{name:`VibORMOperationResult`,type:l},...c].map(({name:e,type:t})=>`type ${e} = ${renderType(t,0)};`).join(`
|
|
5
|
-
`)}function settledModel(e,n){let r=e[`~`].settleTarget(n);if(r instanceof a)return r;throw new t(`A relation target is not a model.`)}function schemaModelReference(e){let n=e[`~`].names.ts;if(!n)throw new t(`A schema model has no hydrated TypeScript name.`);return atom(`VibORMSchema[${JSON.stringify(n)}]`)}function schemaRelationType(e,n,r,i){let a=i.get(e)?.get(n);if(!a)throw new t(`The resolved schema has no relation slot for '${n}'.`);let o=r[`~`].state;if(g(o)){let e=Object.keys(o.target.entries).map(e=>objectOf([{name:`type`,type:atom(JSON.stringify(e)),immutable:!0},{name:`data`,type:schemaModelReference(settledModel(r,e)),immutable:!0}])),t=e.length===0?atom(`never`):unionOf(...e);return o.cardinality===`many`?arrayOf(t,!0):h(a)?unionOf(t,y):t}let s=schemaModelReference(settledModel(r));return o.cardinality===`many`?arrayOf(s):h(a)?unionOf(s,y):s}function schemaModelType(e,n){let r=e[`~`].state,i=[];for(let a of Object.keys(r.shape)){let o=Object.hasOwn(r.scalars,a)?r.scalars[a]:void 0;if(o){i.push({name:a,type:scalarType(o)});continue}let s=Object.hasOwn(r.relations,a)?r.relations[a]:void 0;if(s){i.push({name:a,type:schemaRelationType(e,a,s,n)});continue}throw new t(`Model '${e[`~`].names.ts??`model`}' has unknown field '${a}'.`)}return objectOf(i)}function schemaType(e,t){return`type VibORMSchema = ${renderType(objectOf(Object.entries(e).map(([e,n])=>({name:e,type:schemaModelType(n,t)}))),0)};`}function publicOperationOrThrow(e,t){if(i.has(t))return t;throw new n({kind:`registry`,model:e,property:t},[{path:`operation`,message:`${t} does not exist`}])}function requireIdentifier(e,t){if(typeof e==`string`)return e;throw new n({kind:`registry`,property:t},[{path:t,message:`${t} must be a string`}])}function resultOperation(e,t){switch(e){case`createMany`:case`updateMany`:case`deleteMany`:return t.select===void 0?e:`${e}AndReturn`;default:return r(e)}}function getOperationPayloadSchema(e,t,n){requireIdentifier(t,`model`);let i=publicOperationOrThrow(t,requireIdentifier(n,`operation`));return p(e).proxy[t].args[r(i)]}function validateOperationPayload(e,t,n,i){let a=requireIdentifier(t,`model`),o=publicOperationOrThrow(a,requireIdentifier(n,`operation`));return p(e).validate(a,r(o),i??{})}function renderOperationResultType(e,t,i,a){let s=requireIdentifier(t,`model`),c=publicOperationOrThrow(s,requireIdentifier(i,`operation`)),l=r(c);f(e);let u=o(e),d=m(e,u).validate(s,l,a??{}),p=e[s];if(!p)throw new n({kind:`registry`,model:s},[{path:s,message:`${s} does not exist`}]);return operationResultType(p,c,resultOperation(c,d),d,u)}function renderSchemaType(e){return f(e),schemaType(e,o(e))}export{validateOperationPayload as i,renderOperationResultType as n,renderSchemaType as r,getOperationPayloadSchema as t};
|
|
6
|
-
//# sourceMappingURL=schema-introspection-D0f8cti4.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"schema-introspection-D0f8cti4.mjs","names":["expected"],"sources":["../src/query-engine/result/result-aggregate-leaf.ts","../src/query-engine/result/result-column.ts","../src/client/typescript-type-renderer.ts","../src/client/schema-introspection.ts"],"sourcesContent":["import type { Scalar } from \"@schema/scalars\";\nimport type { AggregateResultName } from \"../result-aliases\";\n\nexport type AggregateLeaf =\n | { readonly kind: \"count\"; readonly nullable: false }\n | { readonly kind: \"number\"; readonly nullable: true }\n | {\n readonly kind: \"scalar\";\n readonly nullable: true;\n readonly scalar: Scalar;\n }\n | {\n readonly kind: \"widenedSum\";\n readonly nullable: true;\n readonly scalar: Scalar;\n }\n | { readonly kind: \"unknown\" };\n\n/**\n * The one semantic classification of an aggregate result leaf. Provider\n * parsing and detached cache encoding must agree on widening and nullability.\n *\n * A `_sum` — admitted only on a decimal, bigint, number or int — is its OWN\n * leaf kind because it answers outside the column's declared domain: a number\n * sum may be `±Infinity`, an int sum may pass 2^53 (read as the nearest\n * double), a bigint sum may leave the int64 range, and summing\n * a million `precision: 10` rows is exact arithmetic whose result no single\n * column could store, so it keeps the field's scale and drops the field's\n * precision. Every other decimal aggregate stays in the field domain — `_min`\n * and `_max` are stored values, and `_avg` is quantized to the field's scale\n * by the shared half-even rounder before it leaves the database. Reading a sum\n * through the field decoder would refuse a correct answer; reading an average\n * through the widened one would accept a wrong one.\n */\nexport function classifyAggregateLeaf(\n name: AggregateResultName,\n field: string,\n scalars: Readonly<Record<string, Scalar>>\n): AggregateLeaf {\n const scalar: Scalar | undefined = Object.hasOwn(scalars, field)\n ? scalars[field]\n : undefined;\n if (name === \"_count\") {\n return field === \"_all\" || scalar\n ? { kind: \"count\", nullable: false }\n : { kind: \"unknown\" };\n }\n if (!scalar) return { kind: \"unknown\" };\n if (name === \"_avg\" && scalar[\"~\"].state.type !== \"decimal\") {\n return { kind: \"number\", nullable: true };\n }\n if (name === \"_sum\") return { kind: \"widenedSum\", nullable: true, scalar };\n return { kind: \"scalar\", nullable: true, scalar };\n}\n","import type { Model } from \"@schema/model\";\nimport { type AnyRelation, isVariantRelationState } from \"@schema/relation\";\nimport type { Scalar } from \"@schema/scalars\";\nimport {\n type AggregateResultName,\n DISTANCE_RESULT_KEY,\n EMPTY_ROW_RESULT_KEY,\n getAggregateResultName,\n RELATION_COUNTS_RESULT_KEY,\n} from \"../result-aliases\";\nimport type {\n ExpectedAggregateResultShape,\n ExpectedPolymorphicResultShape,\n ExpectedRelationResultShape,\n ExpectedResultShape,\n} from \"../types\";\n\nexport type ResultColumn =\n | { readonly kind: \"empty\" }\n | { readonly kind: \"distance\"; readonly scalar: Scalar | undefined }\n | {\n readonly kind: \"scalar\";\n readonly key: string;\n readonly scalar: Scalar;\n }\n | {\n readonly kind: \"relationCounts\";\n readonly relations: ReadonlySet<string>;\n }\n | {\n readonly kind: \"relation\";\n readonly key: string;\n readonly relation: AnyRelation;\n readonly expected: ExpectedRelationResultShape;\n }\n | {\n readonly kind: \"polymorphic\";\n readonly key: string;\n readonly relation: AnyRelation;\n readonly expected: ExpectedPolymorphicResultShape;\n }\n | {\n readonly kind: \"aggregate\";\n readonly name: AggregateResultName;\n readonly expected: ExpectedAggregateResultShape;\n }\n | { readonly kind: \"unknown\"; readonly key: string };\n\n/**\n * The one semantic classification of a compiled raw result column. SQL aliases\n * are translated to their public result owners here; parsing and detached cache\n * encoding consume the same decision.\n */\nexport function classifyResultColumn(\n model: Model<any>,\n key: string,\n shape: ExpectedResultShape\n): ResultColumn {\n if (key === EMPTY_ROW_RESULT_KEY) return { kind: \"empty\" };\n if (key === DISTANCE_RESULT_KEY) {\n return { kind: \"distance\", scalar: shape.distanceScalar };\n }\n\n const scalars = model[\"~\"].state.scalars;\n const scalar: Scalar | undefined = Object.hasOwn(scalars, key)\n ? scalars[key]\n : undefined;\n if (scalar) return { kind: \"scalar\", key, scalar };\n\n if (key === RELATION_COUNTS_RESULT_KEY) {\n return { kind: \"relationCounts\", relations: shape.relationCounts };\n }\n\n const relations = model[\"~\"].state.relations;\n const relation: AnyRelation | undefined = Object.hasOwn(relations, key)\n ? relations[key]\n : undefined;\n if (relation) {\n if (isVariantRelationState(relation[\"~\"].state)) {\n const expected = shape.polymorphic.get(key);\n if (!expected) return { kind: \"unknown\", key };\n return {\n kind: \"polymorphic\",\n key,\n relation,\n expected,\n };\n }\n const expected = shape.relations.get(key);\n if (!expected) return { kind: \"unknown\", key };\n return {\n kind: \"relation\",\n key,\n relation,\n expected,\n };\n }\n\n const name = getAggregateResultName(key);\n if (name) {\n const expected = shape.aggregates.get(key);\n if (!expected) return { kind: \"unknown\", key };\n return {\n kind: \"aggregate\",\n name,\n expected,\n };\n }\n\n return { kind: \"unknown\", key };\n}\n","import { COUNT_RESULT_KEY } from \"@adapters/shared/result-parsing\";\nimport { QueryEngineError } from \"@errors\";\nimport {\n type AggregateLeaf,\n classifyAggregateLeaf,\n} from \"@query-engine/result/result-aggregate-leaf\";\nimport { classifyResultColumn } from \"@query-engine/result/result-column\";\nimport { buildExpectedResultShape } from \"@query-engine/result/result-shape\";\nimport type {\n ExpectedAggregateResultShape,\n ExpectedPolymorphicResultShape,\n ExpectedRelationResultShape,\n ExpectedResultShape,\n Operation,\n} from \"@query-engine/types\";\nimport { type AnyModel, Model } from \"@schema/model\";\nimport {\n type AnyRelation,\n isVariantRelationState,\n slotMayBeEmpty,\n} from \"@schema/relation\";\nimport type { Scalar, ScalarType } from \"@schema/scalars\";\nimport type { ResolvedRelationIndex } from \"@schema/validation/relation-resolution\";\nimport type { Operations, Schema } from \"./types\";\n\ntype TypeNode =\n | { readonly kind: \"atom\"; readonly value: string }\n | {\n readonly kind: \"array\";\n readonly element: TypeNode;\n readonly immutable: boolean;\n }\n | { readonly kind: \"object\"; readonly fields: readonly TypeField[] }\n | { readonly kind: \"union\"; readonly members: readonly TypeNode[] };\n\ninterface TypeField {\n readonly name: string;\n readonly type: TypeNode;\n readonly immutable?: true;\n readonly optional?: true;\n}\n\n/**\n * One named alias a rendered result declares. A recursive relation is the\n * only type TypeScript cannot spell as one anonymous expression, so each\n * recursive slot is rendered once as a named alias whose repeated key refers\n * to the alias itself.\n */\ntype AliasDeclaration = { readonly name: string; type: TypeNode };\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\nconst NULL_TYPE: TypeNode = { kind: \"atom\", value: \"null\" };\n\nfunction atom(value: string): TypeNode {\n return { kind: \"atom\", value };\n}\n\nfunction arrayOf(element: TypeNode, immutable = false): TypeNode {\n return { kind: \"array\", element, immutable };\n}\n\nfunction objectOf(fields: readonly TypeField[]): TypeNode {\n return { kind: \"object\", fields };\n}\n\nfunction unionOf(...nodes: readonly TypeNode[]): TypeNode {\n const members: TypeNode[] = [];\n const seen = new Set<string>();\n for (const node of nodes) {\n const candidates = node.kind === \"union\" ? node.members : [node];\n for (const candidate of candidates) {\n const identity = renderType(candidate, 0);\n if (seen.has(identity)) continue;\n seen.add(identity);\n members.push(candidate);\n }\n }\n const [onlyMember] = members;\n if (!onlyMember) return atom(\"never\");\n return members.length === 1 ? onlyMember : { kind: \"union\", members };\n}\n\nfunction renderPropertyName(name: string): string {\n return IDENTIFIER.test(name) ? name : JSON.stringify(name);\n}\n\nfunction indentation(depth: number): string {\n return \" \".repeat(depth);\n}\n\nfunction renderType(node: TypeNode, depth: number): string {\n switch (node.kind) {\n case \"atom\":\n return node.value;\n case \"array\": {\n const typeConstructor = node.immutable ? \"ReadonlyArray\" : \"Array\";\n return `${typeConstructor}<${renderType(node.element, depth)}>`;\n }\n case \"union\":\n return node.members\n .map((member) => renderType(member, depth))\n .join(\" | \");\n case \"object\": {\n if (node.fields.length === 0) return \"{}\";\n const fieldIndentation = indentation(depth + 1);\n const fields = node.fields.map((field) => {\n const modifier = field.immutable ? \"readonly \" : \"\";\n const optional = field.optional ? \"?\" : \"\";\n return `${fieldIndentation}${modifier}${renderPropertyName(field.name)}${optional}: ${renderType(field.type, depth + 1)};`;\n });\n return `{\n${fields.join(\"\\n\")}\n${indentation(depth)}}`;\n }\n default:\n throw new QueryEngineError(\n \"The TypeScript renderer received an unknown node.\"\n );\n }\n}\n\nfunction enumType(scalar: Scalar): TypeNode {\n const values = Reflect.get(scalar[\"~\"].state.base, \"values\");\n if (\n !(\n Array.isArray(values) &&\n values.every((value) => typeof value === \"string\")\n )\n ) {\n throw new QueryEngineError(\"An enum scalar has no readable string values.\");\n }\n return unionOf(...values.map((value) => atom(JSON.stringify(value))));\n}\n\n/** Scalar kinds whose TypeScript type is one fixed atom. */\nconst SCALAR_ATOMS: Readonly<\n Record<Exclude<ScalarType, \"vector\" | \"point\" | \"enum\">, string>\n> = Object.freeze({\n string: \"string\",\n time: \"string\",\n int: \"number\",\n number: \"number\",\n decimal: 'import(\"viborm\").Decimal',\n boolean: \"boolean\",\n datetime: \"Date\",\n date: \"Date\",\n bigint: \"bigint\",\n // A custom Standard Schema carries its output only in an erased generic.\n json: \"unknown\",\n blob: \"Uint8Array\",\n});\n\nfunction scalarType(scalar: Scalar): TypeNode {\n const state = scalar[\"~\"].state;\n let value: TypeNode;\n if (Object.hasOwn(SCALAR_ATOMS, state.type)) {\n value = atom(SCALAR_ATOMS[state.type as keyof typeof SCALAR_ATOMS]);\n } else if (state.type === \"vector\") {\n value = arrayOf(atom(\"number\"));\n } else if (state.type === \"point\") {\n value = objectOf([\n { name: \"longitude\", type: atom(\"number\") },\n { name: \"latitude\", type: atom(\"number\") },\n ]);\n } else if (state.type === \"enum\") {\n value = enumType(scalar);\n } else {\n throw new QueryEngineError(\n \"The TypeScript renderer does not support this scalar type.\"\n );\n }\n if (state.array) value = arrayOf(value);\n return state.nullable ? unionOf(value, NULL_TYPE) : value;\n}\n\nfunction requiredRelationShape(\n relationName: string,\n expected: ExpectedRelationResultShape | undefined\n): ExpectedRelationResultShape {\n if (expected) return expected;\n throw new QueryEngineError(\n `The result shape for relation '${relationName}' is absent.`\n );\n}\n\nfunction requiredPolymorphicShape(\n relationName: string,\n expected: ExpectedPolymorphicResultShape | undefined\n): ExpectedPolymorphicResultShape {\n if (expected) return expected;\n throw new QueryEngineError(\n `The result shape for polymorphic relation '${relationName}' is absent.`\n );\n}\n\nfunction aggregateLeafType(leaf: AggregateLeaf): TypeNode {\n switch (leaf.kind) {\n case \"count\":\n case \"number\":\n return leaf.nullable\n ? unionOf(atom(\"number\"), NULL_TYPE)\n : atom(\"number\");\n case \"scalar\":\n case \"widenedSum\":\n return unionOf(scalarType(leaf.scalar), NULL_TYPE);\n case \"unknown\":\n throw new QueryEngineError(\n \"The aggregate result contains an unknown field.\"\n );\n default:\n throw new QueryEngineError(\n \"The TypeScript renderer received an unknown aggregate leaf.\"\n );\n }\n}\n\nfunction aggregateType(\n model: AnyModel,\n name: \"_count\" | \"_avg\" | \"_sum\" | \"_min\" | \"_max\",\n expected: ExpectedAggregateResultShape | undefined\n): TypeNode {\n if (name === \"_count\" && expected?.fields === undefined) {\n return atom(\"number\");\n }\n if (!expected?.fields) {\n throw new QueryEngineError(\n `The result shape for aggregate '${name}' is absent.`\n );\n }\n const fields = [...expected.fields].map((fieldName) => ({\n name: fieldName,\n type: aggregateLeafType(\n classifyAggregateLeaf(name, fieldName, model[\"~\"].state.scalars)\n ),\n }));\n return objectOf(fields);\n}\n\nfunction polymorphicType(\n expected: ExpectedPolymorphicResultShape,\n declarations: AliasDeclaration[]\n): TypeNode {\n const variants: TypeNode[] = [];\n for (const [publicType, variant] of expected.variants) {\n variants.push(\n objectOf([\n {\n name: \"type\",\n type: atom(JSON.stringify(publicType)),\n immutable: true,\n },\n {\n name: \"data\",\n type: rowType(variant.model, variant.shape, declarations),\n immutable: true,\n },\n ])\n );\n }\n const member = variants.length === 0 ? atom(\"never\") : unionOf(...variants);\n if (expected.cardinality === \"many\") return arrayOf(member, true);\n return expected.optional ? unionOf(member, NULL_TYPE) : member;\n}\n\n/** A relation slot's cardinality and emptiness around one row type. */\nfunction relationValue(\n expected: ExpectedRelationResultShape,\n row: TypeNode\n): TypeNode {\n if (expected.cardinality === \"many\") return arrayOf(row);\n return expected.optional ? unionOf(row, NULL_TYPE) : row;\n}\n\n/**\n * One recursive slot: the ordinary node row once, as a named alias whose own\n * key repeats the slot. A numeric cutoff may leave that key absent, so it is\n * optional; an exhaustive traversal publishes it on every occurrence.\n */\nfunction recursiveRowType(\n key: string,\n expected: ExpectedRelationResultShape,\n depth: number | false,\n declarations: AliasDeclaration[]\n): TypeNode {\n const declaration: AliasDeclaration = {\n name: `VibORMRecursiveNode${declarations.length + 1}`,\n type: atom(\"never\"),\n };\n declarations.push(declaration);\n const self = atom(declaration.name);\n declaration.type = objectOf([\n ...rowFields(expected.model, expected.shape, declarations),\n {\n name: key,\n type: relationValue(expected, self),\n ...(depth === false ? {} : { optional: true as const }),\n },\n ]);\n return self;\n}\n\nfunction rowType(\n model: AnyModel,\n shape: ExpectedResultShape,\n declarations: AliasDeclaration[]\n): TypeNode {\n return objectOf(rowFields(model, shape, declarations));\n}\n\nfunction rowFields(\n model: AnyModel,\n shape: ExpectedResultShape,\n declarations: AliasDeclaration[]\n): TypeField[] {\n const fields: TypeField[] = [];\n for (const rawKey of shape.rawKeys) {\n const column = classifyResultColumn(model, rawKey, shape);\n switch (column.kind) {\n case \"empty\":\n break;\n case \"distance\":\n fields.push({\n name: \"_distance\",\n type:\n column.scalar?.[\"~\"].state.type === \"point\" &&\n column.scalar[\"~\"].state.nullable\n ? unionOf(atom(\"number\"), NULL_TYPE)\n : atom(\"number\"),\n });\n break;\n case \"scalar\":\n fields.push({ name: column.key, type: scalarType(column.scalar) });\n break;\n case \"relation\": {\n const expected = requiredRelationShape(column.key, column.expected);\n const relatedRow = expected.recurrence\n ? recursiveRowType(\n column.key,\n expected,\n expected.recurrence.depth,\n declarations\n )\n : rowType(expected.model, expected.shape, declarations);\n fields.push({\n name: column.key,\n type: relationValue(expected, relatedRow),\n });\n break;\n }\n case \"polymorphic\":\n fields.push({\n name: column.key,\n type: polymorphicType(\n requiredPolymorphicShape(column.key, column.expected),\n declarations\n ),\n });\n break;\n case \"relationCounts\": {\n if (!column.relations) {\n throw new QueryEngineError(\n \"The relation-count result shape is absent.\"\n );\n }\n fields.push({\n name: \"_count\",\n type: objectOf(\n [...column.relations].map((relationName) => ({\n name: relationName,\n type: atom(\"number\"),\n }))\n ),\n });\n break;\n }\n case \"aggregate\":\n fields.push({\n name: column.name,\n type: aggregateType(model, column.name, column.expected),\n });\n break;\n case \"unknown\":\n throw new QueryEngineError(\n `The result shape contains unknown column '${column.key}'.`\n );\n default:\n throw new QueryEngineError(\n \"The TypeScript renderer received an unknown result column.\"\n );\n }\n }\n return fields;\n}\n\nfunction countType(shape: ExpectedResultShape): TypeNode {\n if (shape.rawKeys.length === 1 && shape.rawKeys[0] === COUNT_RESULT_KEY) {\n return atom(\"number\");\n }\n return objectOf(\n shape.rawKeys.map((fieldName) => ({\n name: fieldName,\n type: atom(\"number\"),\n }))\n );\n}\n\n/**\n * The schema-only result type of one admitted payload, from its expected\n * shape alone: no driver, no SQL, no client default-omit or extension.\n *\n * Almost every result renders as ONE type expression. A recursive relation\n * slot cannot: its node refers to itself, and TypeScript names recursion only\n * through a declaration (format: `renderOperationResultType`). The text names\n * no exported helper.\n */\nexport function operationResultType(\n model: AnyModel,\n publicOperation: Operations,\n engineOperation: Operation,\n args: Record<string, unknown>,\n index: ResolvedRelationIndex\n): string {\n if (\n (publicOperation === \"createMany\" ||\n publicOperation === \"updateMany\" ||\n publicOperation === \"deleteMany\") &&\n engineOperation === publicOperation\n ) {\n return renderType(objectOf([{ name: \"count\", type: atom(\"number\") }]), 0);\n }\n\n const shape = buildExpectedResultShape(model, engineOperation, args, index);\n if (!shape) {\n throw new QueryEngineError(\n `Operation '${publicOperation}' has no renderable result shape.`\n );\n }\n\n const declarations: AliasDeclaration[] = [];\n let value =\n shape.carrier === \"existence\"\n ? atom(\"boolean\")\n : shape.carrier === \"count\"\n ? countType(shape)\n : rowType(model, shape, declarations);\n\n if (\n publicOperation === \"findMany\" ||\n publicOperation === \"groupBy\" ||\n engineOperation === \"createManyAndReturn\" ||\n engineOperation === \"updateManyAndReturn\" ||\n engineOperation === \"deleteManyAndReturn\"\n ) {\n value = arrayOf(value);\n } else if (\n publicOperation === \"findFirst\" ||\n publicOperation === \"findUnique\"\n ) {\n value = unionOf(value, NULL_TYPE);\n }\n if (declarations.length === 0) return renderType(value, 0);\n return [{ name: \"VibORMOperationResult\", type: value }, ...declarations]\n .map(({ name, type }) => `type ${name} = ${renderType(type, 0)};`)\n .join(\"\\n\");\n}\n\nfunction settledModel(relation: AnyRelation, variant?: string): AnyModel {\n const target = relation[\"~\"].settleTarget(variant);\n if (target instanceof Model) return target;\n throw new QueryEngineError(\"A relation target is not a model.\");\n}\n\nfunction schemaModelReference(model: AnyModel): TypeNode {\n const modelName = model[\"~\"].names.ts;\n if (!modelName) {\n throw new QueryEngineError(\n \"A schema model has no hydrated TypeScript name.\"\n );\n }\n return atom(`VibORMSchema[${JSON.stringify(modelName)}]`);\n}\n\nfunction schemaRelationType(\n model: AnyModel,\n fieldName: string,\n relation: AnyRelation,\n index: ResolvedRelationIndex\n): TypeNode {\n const resolved = index.get(model)?.get(fieldName);\n if (!resolved) {\n throw new QueryEngineError(\n `The resolved schema has no relation slot for '${fieldName}'.`\n );\n }\n const state = relation[\"~\"].state;\n if (isVariantRelationState(state)) {\n const variants = Object.keys(state.target.entries).map((publicType) =>\n objectOf([\n {\n name: \"type\",\n type: atom(JSON.stringify(publicType)),\n immutable: true,\n },\n {\n name: \"data\",\n type: schemaModelReference(settledModel(relation, publicType)),\n immutable: true,\n },\n ])\n );\n const member = variants.length === 0 ? atom(\"never\") : unionOf(...variants);\n if (state.cardinality === \"many\") return arrayOf(member, true);\n return slotMayBeEmpty(resolved) ? unionOf(member, NULL_TYPE) : member;\n }\n\n const target = schemaModelReference(settledModel(relation));\n if (state.cardinality === \"many\") return arrayOf(target);\n return slotMayBeEmpty(resolved) ? unionOf(target, NULL_TYPE) : target;\n}\n\nfunction schemaModelType(\n model: AnyModel,\n index: ResolvedRelationIndex\n): TypeNode {\n const state = model[\"~\"].state;\n const fields: TypeField[] = [];\n for (const fieldName of Object.keys(state.shape)) {\n const scalar = Object.hasOwn(state.scalars, fieldName)\n ? state.scalars[fieldName]\n : undefined;\n if (scalar) {\n fields.push({ name: fieldName, type: scalarType(scalar) });\n continue;\n }\n const relation = Object.hasOwn(state.relations, fieldName)\n ? state.relations[fieldName]\n : undefined;\n if (relation) {\n fields.push({\n name: fieldName,\n type: schemaRelationType(model, fieldName, relation, index),\n });\n continue;\n }\n const modelName = model[\"~\"].names.ts ?? \"model\";\n throw new QueryEngineError(\n `Model '${modelName}' has unknown field '${fieldName}'.`\n );\n }\n return objectOf(fields);\n}\n\nexport function schemaType(\n schema: Schema,\n index: ResolvedRelationIndex\n): string {\n const models = Object.entries(schema).map(([modelName, model]) => ({\n name: modelName,\n type: schemaModelType(model, index),\n }));\n return `type VibORMSchema = ${renderType(objectOf(models), 0)};`;\n}\n","import { ValidationError } from \"@errors\";\nimport {\n baseOperation,\n ROUTED_OPERATIONS,\n} from \"@query-engine/routed-operations\";\nimport type { Operation } from \"@query-engine/types\";\nimport { hydrateSchemaNames } from \"@schema/hydration\";\nimport { resolveSchemaOrThrow } from \"@schema/validation\";\nimport {\n createResolvedSchemaRegistry,\n createSchemaRegistry,\n} from \"@validation/builder\";\nimport type {\n OperationPayloadSchema,\n Operations,\n Schema,\n ValidatedOperationPayload,\n} from \"./types\";\nimport { operationResultType, schemaType } from \"./typescript-type-renderer\";\n\nfunction publicOperationOrThrow(\n modelName: string,\n operation: string\n): Operations {\n if (ROUTED_OPERATIONS.has(operation)) return operation as Operations;\n throw new ValidationError(\n { kind: \"registry\", model: modelName, property: operation },\n [{ path: \"operation\", message: `${operation} does not exist` }]\n );\n}\n\nfunction requireIdentifier(\n value: unknown,\n path: \"model\" | \"operation\"\n): string {\n if (typeof value === \"string\") return value;\n throw new ValidationError({ kind: \"registry\", property: path }, [\n { path, message: `${path} must be a string` },\n ]);\n}\n\nfunction resultOperation(\n operation: Operations,\n args: Record<string, unknown>\n): Operation {\n switch (operation) {\n case \"createMany\":\n case \"updateMany\":\n case \"deleteMany\":\n return args.select === undefined ? operation : `${operation}AndReturn`;\n default:\n return baseOperation(operation);\n }\n}\n\n/** Return the canonical Standard Schema for one public operation payload. */\nexport function getOperationPayloadSchema<\n const S extends Schema,\n ModelName extends Extract<keyof S, string>,\n OperationName extends Operations,\n>(\n schema: S,\n modelName: ModelName,\n operation: OperationName\n): OperationPayloadSchema<OperationName, S[ModelName]>;\nexport function getOperationPayloadSchema<\n const S extends Schema,\n ModelName extends Extract<keyof S, string>,\n>(schema: S, modelName: ModelName, operation: unknown): unknown {\n requireIdentifier(modelName, \"model\");\n const validatedOperation = publicOperationOrThrow(\n modelName,\n requireIdentifier(operation, \"operation\")\n );\n return createSchemaRegistry(schema).proxy[modelName].args[\n baseOperation(validatedOperation)\n ];\n}\n\n/**\n * Validate one public model-operation payload and return its normalized value.\n * This is schema validation, not a driver-specific executability check.\n */\nexport function validateOperationPayload<\n const S extends Schema,\n ModelName extends Extract<keyof S, string>,\n OperationName extends Operations,\n>(\n schema: S,\n modelName: ModelName,\n operation: OperationName,\n payload: unknown\n): ValidatedOperationPayload<OperationName, S[ModelName]>;\nexport function validateOperationPayload(\n schema: Schema,\n modelName: unknown,\n operation: unknown,\n payload: unknown\n): unknown {\n const validatedModelName = requireIdentifier(modelName, \"model\");\n const validatedOperation = publicOperationOrThrow(\n validatedModelName,\n requireIdentifier(operation, \"operation\")\n );\n const registry = createSchemaRegistry(schema);\n return registry.validate(\n validatedModelName,\n baseOperation(validatedOperation),\n payload ?? {}\n );\n}\n\n/**\n * Render the concrete return type for one validated public operation payload.\n * Client extensions and `defaultOmit()` are not part of this schema-only view:\n * on a client whose rules hide rows, a to-one relation can read\n * `null` where the rendered type says it cannot.\n *\n * A payload with a recursive relation slot renders as declarations — a\n * `VibORMOperationResult` alias followed by one `VibORMRecursiveNodeN` alias per\n * recursive slot, numbered outer-first — because a finite recursive type needs\n * a name; every other result renders as one type expression.\n */\nexport function renderOperationResultType<\n const S extends Schema,\n ModelName extends Extract<keyof S, string>,\n>(\n schema: S,\n modelName: ModelName,\n operation: Operations,\n payload: unknown\n): string;\nexport function renderOperationResultType(\n schema: Schema,\n modelName: unknown,\n operation: unknown,\n payload: unknown\n): string {\n const validatedModelName = requireIdentifier(modelName, \"model\");\n const validatedOperation = publicOperationOrThrow(\n validatedModelName,\n requireIdentifier(operation, \"operation\")\n );\n const schemaOperation = baseOperation(validatedOperation);\n hydrateSchemaNames(schema);\n const index = resolveSchemaOrThrow(schema);\n const registry = createResolvedSchemaRegistry(schema, index);\n const validated = registry.validate(\n validatedModelName,\n schemaOperation,\n payload ?? {}\n );\n const model = schema[validatedModelName];\n if (!model) {\n throw new ValidationError({ kind: \"registry\", model: validatedModelName }, [\n {\n path: validatedModelName,\n message: `${validatedModelName} does not exist`,\n },\n ]);\n }\n return operationResultType(\n model,\n validatedOperation,\n resultOperation(validatedOperation, validated),\n validated,\n index\n );\n}\n\n/**\n * Render the complete schema graph as a recursive `VibORMSchema` declaration.\n * Custom JSON schema output is `unknown` because Standard Schema erases it at runtime.\n */\nexport function renderSchemaType<const S extends Schema>(schema: S): string {\n hydrateSchemaNames(schema);\n return schemaType(schema, resolveSchemaOrThrow(schema));\n}\n"],"mappings":"8fAkCA,SAAgB,sBACd,EACA,EACA,EACe,CACf,IAAM,EAA6B,OAAO,OAAO,EAAS,EAAM,CAC5D,EAAQ,GACR,IAAA,GAWJ,OAVI,IAAS,SACJ,IAAU,QAAU,EACvB,CAAE,KAAM,QAAS,SAAU,GAAO,CAClC,CAAE,KAAM,UAAW,CAEpB,EACD,IAAS,QAAU,EAAO,KAAK,MAAM,OAAS,UACzC,CAAE,KAAM,SAAU,SAAU,GAAM,CAEvC,IAAS,OAAe,CAAE,KAAM,aAAc,SAAU,GAAM,SAAQ,CACnE,CAAE,KAAM,SAAU,SAAU,GAAM,SAAQ,CAL7B,CAAE,KAAM,UAAW,CCMzC,SAAgB,qBACd,EACA,EACA,EACc,CACd,GAAI,IAAQ,EAAsB,MAAO,CAAE,KAAM,QAAS,CAC1D,GAAI,IAAQ,EACV,MAAO,CAAE,KAAM,WAAY,OAAQ,EAAM,eAAgB,CAG3D,IAAM,EAAU,EAAM,KAAK,MAAM,QAC3B,EAA6B,OAAO,OAAO,EAAS,EAAI,CAC1D,EAAQ,GACR,IAAA,GACJ,GAAI,EAAQ,MAAO,CAAE,KAAM,SAAU,MAAK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OAAO,EAAqB,EAAO,CAAC,MAAM,GAAW,KACnD,EAAc,EAAmB,EAkBrC,SAAgB,yBACd,EACA,EACA,EACA,EACS,CACT,IAAM,EAAqB,kBAAkB,EAAW,QAAQ,CAC1D,EAAqB,uBACzB,EACA,kBAAkB,EAAW,YAAY,CAC1C,CAED,OADiB,EAAqB,EAAO,CAC7B,SACd,EACA,EAAc,EAAmB,CACjC,GAAW,EAAE,CACd,CAuBH,SAAgB,0BACd,EACA,EACA,EACA,EACQ,CACR,IAAM,EAAqB,kBAAkB,EAAW,QAAQ,CAC1D,EAAqB,uBACzB,EACA,kBAAkB,EAAW,YAAY,CAC1C,CACK,EAAkB,EAAc,EAAmB,CACzD,EAAmB,EAAO,CAC1B,IAAM,EAAQ,EAAqB,EAAO,CAEpC,EADW,EAA6B,EAAQ,EAAM,CACjC,SACzB,EACA,EACA,GAAW,EAAE,CACd,CACK,EAAQ,EAAO,GACrB,GAAI,CAAC,EACH,MAAM,IAAI,EAAgB,CAAE,KAAM,WAAY,MAAO,EAAoB,CAAE,CACzE,CACE,KAAM,EACN,QAAS,GAAG,EAAmB,iBAChC,CACF,CAAC,CAEJ,OAAO,oBACL,EACA,EACA,gBAAgB,EAAoB,EAAU,CAC9C,EACA,EACD,CAOH,SAAgB,iBAAyC,EAAmB,CAE1E,OADA,EAAmB,EAAO,CACnB,WAAW,EAAQ,EAAqB,EAAO,CAAC"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./sql-3o4DOKm9.mjs";function createNamedConstraintIdentities(e){let identity=(e,t)=>({name:t,normalizedError:{table:e,constraint:t}});return{primaryKey:t=>identity(t,e(t)),unique:(e,t)=>identity(e,`${e}_${t}_key`)}}const n={primaryKey:(e,t)=>({name:`${e}_pkey`,normalizedError:{table:e,columns:[...t]}}),unique:(e,t,n)=>({name:`${e}_${t}_key`,normalizedError:{table:e,columns:[...n]}})};function installGeoPointSql(e,t){let n;if(t){let e=t.withinPolygon,r=t.distance;n=Object.freeze({value:t.value,longitude:t.longitude,latitude:t.latitude,equals:t.equals,withinBounds:t.withinBounds,...e?{withinPolygon:e}:{},...r?{distance:r}:{}})}Object.defineProperty(e,`geoPoint`,{value:n,writable:!1,enumerable:!0,configurable:!1})}const scaleFactorSql=e=>t.raw(`1${`0`.repeat(e)}`),scaleUnitSql=e=>t.raw(e===0?`1`:`0.${`0`.repeat(e-1)}1`),halfEvenQuotient=(e,n,r)=>{let i=e.quotient(n,r),a=e.remainder(n,r);return t`(${i} + (CASE WHEN ABS(${a}) > ${r} - ABS(${a}) OR (ABS(${a}) = ${r} - ABS(${a}) AND ${e.remainder(i,t.raw`2`)} <> 0) THEN (CASE WHEN ${a} < 0 THEN -1 ELSE 1 END) ELSE 0 END))`},signedNumerator=(e,n)=>t`(CASE WHEN ${n} < 0 THEN -${e} ELSE ${e} END)`,logicalDecimalMultiply=(e,n,r,i)=>t`${n} = ${halfEvenQuotient(e,t`(${n} * ${r} * ${scaleFactorSql(i.scale)})`,t.raw`1`)} * ${scaleUnitSql(i.scale)}`,logicalDecimalDivide=(e,n,r,i)=>t`${n} = ${halfEvenQuotient(e,signedNumerator(t`(${n} * ${scaleFactorSql(i.scale)})`,r),t`ABS(${r})`)} * ${scaleUnitSql(i.scale)}`,logicalDecimalAverage=(e,n,r)=>t`(${halfEvenQuotient(e,t`(SUM(${n}) * ${scaleFactorSql(r.scale)})`,t`COUNT(${n})`)} * ${scaleUnitSql(r.scale)})`;function createGeoPointCoordinatePredicates(e,n,r,i){return{equals(i,a){let o=e(i),s=r.eq(o,t`${a.longitude}`);return a.longitude===180&&(s=r.or(s,r.eq(o,t`${-180}`))),r.and(s,r.eq(n(i),t`${a.latitude}`))},withinBounds(a,o){let s=e(a),c=r.and(r.gte(n(a),t`${o.south}`),r.lte(n(a),t`${o.north}`)),l;if(o.west===-180&&o.east===180)l=c;else{let e=r.gte(s,t`${o.west}`),n=r.lte(s,t`${o.east}`),i=o.west>o.east?r.or(e,n):r.and(e,n);o.west===-180&&o.east<180&&(i=r.or(i,r.eq(s,t`${180}`))),o.east===180&&o.west>-180&&(i=r.or(i,r.eq(s,t`${-180}`))),l=r.and(c,i)}let u=i?.(a,o);return u?r.and(u,l):l}}}function geoBoundsIndexPolygons(e){return e.south===-90||e.north===90||e.south===e.north||e.west===e.east||e.west>e.east||e.west===-180||e.east===180?[]:[boundsPolygonJson(e.west,e.east,e.south,e.north)]}function boundsPolygonJson(e,t,n,r){let i=[e,...[-90,0,90].filter(n=>e<n&&n<t),t],a=i.map(e=>[e,n]),o=[...i].reverse().map(e=>[e,r]);return JSON.stringify({type:`Polygon`,coordinates:[[...a,...o,a[0]]]})}function geoPolygonJson(e){let t=[closedRing(e.outer)];if(e.holes)for(let n of e.holes)t.push(closedRing(n));return JSON.stringify({type:`Polygon`,coordinates:t})}function closedRing(e){let t=Array(e.length+1);for(let n=0;n<e.length;n+=1){let r=e[n];t[n]=[r.longitude,r.latitude]}let n=e[0];return t[e.length]=[n.longitude,n.latitude],t}const assembleSelectQuery=(e,n,r)=>{let i=[e,t`FROM ${n.from}`];return appendSelectParts(i,n,r),r.forUpdate===`append`&&n.forUpdate&&i.push(t.raw`FOR UPDATE`),t.join(i,` `)},appendSelectParts=(e,n,r)=>{appendFilterParts(e,n),n.orderBy&&e.push(t`ORDER BY ${n.orderBy}`),appendLimitOffset(e,n.limit,n.offset,r.noLimitValue)},appendFilterParts=(e,n)=>{n.joins&&n.joins.length>0&&e.push(...n.joins),n.where&&e.push(t`WHERE ${n.where}`),n.groupBy&&e.push(t`GROUP BY ${n.groupBy}`),n.having&&e.push(t`HAVING ${n.having}`)},appendLimitOffset=(e,n,r,i)=>{n?e.push(t`LIMIT ${n}`):r&&i&&e.push(t`LIMIT ${i}`),r&&e.push(t`OFFSET ${r}`)},assembleDistinctOnEmulation=(e,n,r,i)=>{let a=e.distinctOrderBy??e.orderBy??n,o=e.distinctOrder,s=[e.columns];o&&s.push(o.keys),s.push(t`ROW_NUMBER() OVER (PARTITION BY ${n} ORDER BY ${a}) AS ${r(`_rn`)}`);let c=[t`SELECT ${t.join(s,`, `)}`,t`FROM ${e.from}`];appendFilterParts(c,e);let l=t.join(c,` `),u=e.distinctColumnAliases.map(r),d=[t`SELECT ${t.join(u,`, `)} FROM (${l}) AS ${r(`_distinct_subquery`)}`,t`WHERE ${r(`_rn`)} = 1`];return o&&d.push(t`ORDER BY ${o.orderBy}`),appendLimitOffset(d,e.limit,e.offset,i),t.join(d,` `)};export{geoPolygonJson as a,logicalDecimalDivide as c,scaleUnitSql as d,signedNumerator as f,n as h,geoBoundsIndexPolygons as i,logicalDecimalMultiply as l,createNamedConstraintIdentities as m,assembleSelectQuery as n,halfEvenQuotient as o,installGeoPointSql as p,createGeoPointCoordinatePredicates as r,logicalDecimalAverage as s,assembleDistinctOnEmulation as t,scaleFactorSql as u};
|
|
2
|
-
//# sourceMappingURL=select-assembly-DVI7d3tf.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"select-assembly-DVI7d3tf.mjs","names":["sql","sql"],"sources":["../src/adapters/constraint-identity.ts","../src/adapters/database-adapter.ts","../src/adapters/shared/decimal-arithmetic.ts","../src/adapters/shared/geo-point.ts","../src/adapters/shared/select-assembly.ts"],"sourcesContent":["/** The exact normalized provider evidence that identifies one constraint. */\nexport interface NormalizedConstraintDescriptor {\n readonly table?: string;\n readonly constraint?: string;\n readonly columns?: readonly string[];\n}\n\nexport interface ConstraintIdentity {\n readonly name: string;\n readonly normalizedError: NormalizedConstraintDescriptor;\n}\n\n/** Private adapter projection from a schema key to its physical identity. */\nexport interface ConstraintIdentities {\n readonly primaryKey: (\n tableName: string,\n columns: readonly string[]\n ) => ConstraintIdentity;\n readonly unique: (\n tableName: string,\n keyName: string,\n columns: readonly string[]\n ) => ConstraintIdentity;\n}\n\n/** PostgreSQL/MySQL errors identify named constraints and their table. */\nexport function createNamedConstraintIdentities(\n primaryKeyName: (tableName: string) => string\n): ConstraintIdentities {\n const identity = (tableName: string, name: string): ConstraintIdentity => ({\n name,\n normalizedError: { table: tableName, constraint: name },\n });\n return {\n primaryKey: (tableName) => identity(tableName, primaryKeyName(tableName)),\n unique: (tableName, keyName) =>\n identity(tableName, `${tableName}_${keyName}_key`),\n };\n}\n\n/** Driver normalization separates SQLite's physical table and columns. */\nexport const sqliteConstraintIdentities: ConstraintIdentities = {\n primaryKey: (tableName, columns) => ({\n name: `${tableName}_pkey`,\n normalizedError: {\n table: tableName,\n columns: [...columns],\n },\n }),\n unique: (tableName, keyName, columns) => ({\n name: `${tableName}_${keyName}_key`,\n normalizedError: {\n table: tableName,\n columns: [...columns],\n },\n }),\n};\n","import type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport type { Sql } from \"@sql\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport type {\n GeoBounds,\n GeoPoint,\n GeoPolygon,\n} from \"@validation/primitives/geo-values\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport type { DatabaseAdapterCapabilities } from \"./adapter-capabilities\";\nimport type { ArithmeticTarget, CastType } from \"./adapter-core-types\";\nimport type { AdapterResultParser } from \"./adapter-result-parser\";\n\nexport type { DatabaseAdapterCapabilities } from \"./adapter-capabilities\";\nexport type {\n ArithmeticTarget,\n CastType,\n} from \"./adapter-core-types\";\nexport type { AdapterResultParser } from \"./adapter-result-parser\";\n\n/** The one physical SQL vocabulary for a logical EPSG:4326 GeoPoint. */\nexport interface GeoPointSql {\n /** Construct a stored point from already-bound longitude and latitude. */\n readonly value: (longitude: Sql, latitude: Sql) => Sql;\n /** Project the logical longitude from a stored point. */\n readonly longitude: (point: Sql) => Sql;\n /** Project the logical latitude from a stored point. */\n readonly latitude: (point: Sql) => Sql;\n /** Exact canonical coordinate equality. */\n readonly equals: (point: Sql, expected: GeoPoint) => Sql;\n /** Inclusive coordinate bounds, including antimeridian-crossing bounds. */\n readonly withinBounds: (point: Sql, bounds: GeoBounds) => Sql;\n /** Inclusive geographic polygon membership on full-tier providers. */\n readonly withinPolygon?: (point: Sql, polygon: GeoPolygon) => Sql;\n /** Fixed-radius spherical distance in meters on full-tier providers. */\n readonly distance?: (left: Sql, right: Sql) => Sql;\n}\n\n/** Install the adapter's settled GeoPoint protocol as one immutable fact. */\nexport function installGeoPointSql(\n adapter: object,\n geoPoint: GeoPointSql | undefined\n): void {\n let installed: GeoPointSql | undefined;\n if (geoPoint) {\n const withinPolygon = geoPoint.withinPolygon;\n const distance = geoPoint.distance;\n installed = Object.freeze<GeoPointSql>({\n value: geoPoint.value,\n longitude: geoPoint.longitude,\n latitude: geoPoint.latitude,\n equals: geoPoint.equals,\n withinBounds: geoPoint.withinBounds,\n ...(withinPolygon ? { withinPolygon } : {}),\n ...(distance ? { distance } : {}),\n });\n }\n Object.defineProperty(adapter, \"geoPoint\", {\n value: installed,\n writable: false,\n enumerable: true,\n configurable: false,\n });\n}\n\n/**\n * DatabaseAdapter Interface\n *\n * A monadic, composable interface for database-specific SQL generation.\n * Each method is a pure function that transforms Sql fragments or primitives\n * into new Sql fragments, enabling clean composition without side effects.\n *\n * DESIGN PRINCIPLES:\n * - Pure functions: Same inputs always produce same outputs\n * - Composable: Outputs can be inputs to other methods\n * - Database-agnostic inputs: Query engine speaks neutral language\n * - Database-specific outputs: Adapter handles syntax differences\n *\n * USAGE:\n * The query engine calls adapter methods to build SQL fragments,\n * then composes them into complete queries. The adapter never\n * needs to understand query semantics - just SQL syntax.\n */\n/** The three substring filters, as `insensitiveText` names them. */\nexport type TextMatch = \"contains\" | \"startsWith\" | \"endsWith\";\n\n/** A vector distance as an order key: see {@link DatabaseAdapter.vector}. */\nexport type VectorOrderKey = \"exact\" | \"servable\";\n\n/**\n * What the engine reads of a driver in any language: strategy and decoding, and\n * nothing that spells a statement. A database with no SQL declares only this.\n */\nexport interface EngineFacts\n extends Pick<DatabaseAdapter, \"namespace\" | \"capabilities\" | \"result\"> {\n /** Set when this database holds a geographic point, however it writes one. */\n readonly geoPoint?: object;\n readonly mutations: Pick<\n DatabaseAdapter[\"mutations\"],\n \"skipDuplicatesStrategy\" | \"upserted\"\n >;\n readonly aggregates: Partial<\n Pick<DatabaseAdapter[\"aggregates\"], \"numberSum\" | \"integerSum\">\n >;\n}\n\nexport interface DatabaseAdapter {\n /**\n * NAMESPACE\n * The one normalized SQL qualification value for this adapter's persistent\n * objects — a PostgreSQL schema, a MySQL database, or a requested Vitess\n * keyspace qualifier. `undefined` means deliberately unqualified: unbound\n * MySQL and every SQLite adapter. It is selected once at construction and\n * installed non-writable, and THAT INSTALL is where its immutability lives —\n * not a ban on copies: the two readers that capture it once, the bound\n * migration driver at bind time and the `readDriverIdentity` snapshot a cached\n * read takes, cannot go stale because the property they read can never be\n * reassigned.\n */\n readonly namespace?: string;\n\n /**\n * RAW\n * Escape hatch for raw SQL strings (use sparingly)\n */\n raw: (sqlString: string) => Sql;\n\n /**\n * IDENTIFIERS\n * Database-specific identifier escaping (table names, column names, aliases)\n */\n identifiers: {\n /** Escape a single identifier: \"name\" or `name` */\n escape: (name: string) => Sql;\n /** Create qualified column reference: \"alias\".\"field\" */\n column: (alias: string, field: string) => Sql;\n /**\n * The one renderer for a persistent model or junction table: applies the\n * adapter's namespace and, when an alias is given, the `AS` clause.\n * Statement-local names — CTEs, aliases, columns, constraints — use\n * `escape` instead, and an omitted alias is for a site that splices its own.\n */\n table: (tableName: string, alias?: string) => Sql;\n /** Create aliased expression: expr AS \"alias\" */\n aliased: (expression: Sql, alias: string) => Sql;\n };\n\n /**\n * LITERALS\n * Value wrapping with proper parameterization\n */\n literals: {\n /** Wrap a value as parameterized SQL */\n value: (v: unknown) => Sql;\n /** NULL keyword */\n null: () => Sql;\n /** TRUE literal (database-specific: TRUE vs 1) */\n true: () => Sql;\n /** FALSE literal (database-specific: FALSE vs 0) */\n false: () => Sql;\n /**\n * Returns the dialect's membership operand, valid only as `operators.in` /\n * `notIn` input: a parenthesized list, a PostgreSQL array parameter, or,\n * past 25 members, a SQLite `json_each` subquery.\n */\n list: (values: Sql[]) => Sql;\n /** JSON value (PG: native, MySQL/SQLite: JSON.stringify) */\n json: (v: unknown) => Sql;\n /**\n * Datetime operand from a validated ISO-8601 string, in the PHYSICAL form\n * the destination column holds (PG: as-is, MySQL: naive UTC\n * 'YYYY-MM-DD HH:MM:SS.mmm').\n *\n * `nativeType` is the field's own declaration, threaded because SQLite has\n * no temporal type: a `s.dateTime(SQLITE.DATETIME.INTEGER)` column holds\n * epoch milliseconds and a `REAL` one holds a Julian day, so an ISO string\n * bound into either compares against nothing and stores text the typed read\n * then refuses. The dialects that DO have a temporal type ignore it — their\n * own native types all name a column that accepts this same spelling.\n */\n dateTime: (\n iso: string,\n nativeType?: NativeTypeDeclaration,\n member?: boolean\n ) => Sql;\n /**\n * Decimal operand from a canonical decimal string, in the DOMAIN it is\n * being compared or assigned against.\n *\n * The value binds as text and the DIALECT decides how to read it, because\n * the reading is where precision is won or lost. PostgreSQL and MySQL cast\n * it into their exact decimal type — MySQL in particular compares a\n * `DECIMAL` column against an uncast string operand as a *double*, which\n * would make an exact column compare inexactly with nothing to show for it.\n * SQLite has no exact decimal type and stores the unscaled integer\n * coefficient, so there the operand becomes that same coefficient.\n *\n * The descriptor is the operand's domain, which is USUALLY the field's and\n * deliberately not always: a `having: { _sum: ... }` operand is compared\n * against a sum that may legitimately be wider than any single row's\n * column, so the aggregate's caller widens the precision it passes. The\n * scale is the field's on every path — it is what makes the operand and the\n * column the same physical kind of number.\n */\n decimal: (canonical: string, descriptor: DecimalDescriptor) => Sql;\n /**\n * Identifier operand, in the PHYSICAL representation its column holds.\n *\n * The value arrives already encoded by the codec — canonical public text,\n * canonical UUID text, or the payload's own bytes — so nothing here reads a\n * format, a prefix or an alphabet. What the dialect owns is the BINDING: a\n * PostgreSQL `uuid` column takes text and wants the operand typed as\n * `uuid`, because an untyped text operand against a `uuid` column is\n * `operator does not exist: uuid = text`; a `bytea`, `BINARY(n)` or `BLOB`\n * column takes the bytes as an ordinary binary parameter, which every\n * driver already serializes for blob scalars.\n *\n * Separate from {@link DatabaseAdapter.literals.value} for the reason\n * `decimal` is: the operand and the column have to be ONE physical kind, and\n * a generic parameter leaves that to inference at every site.\n */\n id: (\n physical: string | Uint8Array,\n representation: IdRepresentation\n ) => Sql;\n };\n\n /**\n * OPERATORS\n * Comparison and logical operators (pure Sql -> Sql)\n */\n operators: {\n // Comparison\n eq: (left: Sql, right: Sql) => Sql;\n neq: (left: Sql, right: Sql) => Sql;\n lt: (left: Sql, right: Sql) => Sql;\n lte: (left: Sql, right: Sql) => Sql;\n gt: (left: Sql, right: Sql) => Sql;\n gte: (left: Sql, right: Sql) => Sql;\n\n // Pattern matching\n /** Case-sensitive substring predicates, independent of database collation. */\n containsText: (column: Sql, value: Sql) => Sql;\n startsWithText: (column: Sql, value: Sql) => Sql;\n endsWithText: (column: Sql, value: Sql) => Sql;\n /**\n * The same three predicates under `mode: \"insensitive\"`: letter case is\n * ignored the way THIS database folds it (its own `LOWER`/`ILIKE`), so the\n * answer for a non-ASCII letter follows the database and its locale.\n * Accents and every other difference still count.\n *\n * Both operands arrive raw: neither folded nor wrapped in\n * `caseSensitiveText`. A plain string `value` is a bare bound parameter,\n * which an adapter matching with `LIKE` escapes client-side.\n */\n insensitiveText: (\n kind: TextMatch,\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n /**\n * `startsWithText` for a plain string operand, spelled so the dialect's\n * planner can turn it into an index range.\n *\n * Same answer as `startsWithText` on every input — it exists only because\n * `startsWithText` wraps the COLUMN in a function (`LEFT`/`substr`), which\n * no planner can range on. This one takes the raw JS string instead of a\n * bound `Sql` so the adapter can escape it into its own pattern language\n * and bind the finished pattern; a pattern assembled in SQL from the\n * operand would be non-constant and lose the range again.\n *\n * Only the where-builder's default-mode, plain-string, `string`-scalar path\n * reaches it. A field-reference operand, a JSON path, an enum column and\n * `mode: \"insensitive\"` all keep `startsWithText`: each of those either has\n * no client-side string to escape, or already wraps the column in a fold\n * that forecloses the range anyway.\n *\n * Each dialect's implementation must hold the case-sensitivity contract\n * `startsWithText` documents. See the per-adapter comments — the three\n * answers are not the same shape, and the measurements that forced that\n * are recorded in `docs/architecture/query-performance-plan.md`, §7.3.\n */\n startsWithPrefix: (\n column: Sql,\n value: string,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n\n /**\n * `column = value` and `column IN (values)` on a TEXT column, under the\n * case-sensitive semantics `caseSensitiveText` spells, written so the\n * dialect's planner can still use an index.\n *\n * `column` arrives unwrapped: each adapter applies its own\n * `caseSensitiveText` where its own semantics need it, and is free to put\n * an index-usable conjunct in front of it. On PostgreSQL and SQLite that\n * is exactly `caseSensitiveText(column) <op> …` and nothing more — their\n * case-sensitive spellings are already index-usable. MySQL's is not: the\n * `BINARY` cast is a function of the column, so the planner drops to a full\n * scan, and MySQL adds a collation-native conjunct in front. See\n * `docs/architecture/query-performance-plan.md`, §10.2 for the plans.\n *\n * The operands are BOUND values, never referenced columns — the caller\n * routes a reference to the plain comparison, which has no index lookup to\n * preserve.\n */\n exactTextEq: (\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n exactTextIn: (\n column: Sql,\n values: Sql,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n\n // Set membership\n in: (column: Sql, values: Sql) => Sql;\n notIn: (column: Sql, values: Sql) => Sql;\n\n // Null checks\n isNull: (expr: Sql) => Sql;\n isNotNull: (expr: Sql) => Sql;\n\n // Range\n between: (column: Sql, min: Sql, max: Sql) => Sql;\n notBetween: (column: Sql, min: Sql, max: Sql) => Sql;\n\n // Logical\n and: (...conditions: Sql[]) => Sql;\n or: (...conditions: Sql[]) => Sql;\n not: (condition: Sql) => Sql;\n\n // Subquery existence\n exists: (subquery: Sql) => Sql;\n notExists: (subquery: Sql) => Sql;\n };\n\n /**\n * EXPRESSIONS\n * Computed values and functions\n */\n expressions: {\n /** Portable searched CASE expression. */\n caseWhen: (\n branches: readonly { readonly when: Sql; readonly then: Sql }[],\n otherwise: Sql\n ) => Sql;\n\n // Arithmetic\n add: (left: Sql, right: Sql) => Sql;\n subtract: (left: Sql, right: Sql) => Sql;\n multiply: (left: Sql, right: Sql) => Sql;\n divide: (left: Sql, right: Sql) => Sql;\n /**\n * The integer quotient of two integer operands, truncated toward zero.\n *\n * The same fact {@link DatabaseAdapter.set.divide}'s `target.integer` flag\n * already carries, as an EXPRESSION rather than an assignment: naming the\n * value an integer column will hold after `{ divide }` needs the dialect's\n * own truncation, and `/` does not agree across dialects. SQLite and\n * PostgreSQL truncate natively once both operands are integers, while MySQL\n * `/` yields a DECIMAL quotient and needs `TRUNCATE(…, 0)`. Casting the\n * quotient afterwards is not a substitute: MySQL and PostgreSQL ROUND on\n * cast, only SQLite truncates.\n */\n integerDivide: (left: Sql, right: Sql) => Sql;\n\n // String operations\n concat: (...parts: Sql[]) => Sql;\n upper: (expr: Sql) => Sql;\n lower: (expr: Sql) => Sql;\n /**\n * Fold letter case the way this database does natively (its own `LOWER`),\n * for `mode: \"insensitive\"` equality, membership and ranges. The caller\n * compares the result under `caseSensitiveText`, so case is the only\n * difference it ignores. `expr` arrives raw, never wrapped in\n * `caseSensitiveText`, with the native type of the column it reads.\n */\n caseFold: (expr: Sql, nativeType?: NativeTypeDeclaration) => Sql;\n /** Force exact text comparison semantics independent of column/database collation. */\n caseSensitiveText: (\n expr: Sql,\n nativeType?: NativeTypeDeclaration,\n textOperation?: boolean\n ) => Sql;\n\n /** Cast a deferred value into one fixed-decimal field's exact domain. */\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor) => Sql;\n\n /**\n * Bind a DEFERRED identifier back into its column's physical type — the\n * INVERSE of the transport spelling a byte column travels in (lowercase\n * hex, `query-engine/raptor3/shared/identifier.ts`\n * `transportedIdentifier`).\n *\n * NO ENGINE CALLER since the Raptor 3 port: that engine has no deferred\n * identifier — a located key is a raw column sub-select, already physical,\n * and the batch scratch carries integers only. The member stays declared\n * and pinned (`tests/contracts/adapters/identifier-storage.core.test.ts`)\n * until its owner retires or re-adopts it; the provenance below is the\n * retired engine's.\n *\n * The sibling of {@link DatabaseAdapter.expressions.decimalCast}, and\n * needed for the same reason: a relation key whose value does not exist at\n * build time — a `Ref` into a located parent's captured column — cannot go\n * through `literals.id`, and the generic `text` cast names a type the\n * column does not have. `CAST($1 AS TEXT)` against a PostgreSQL `uuid`\n * column is the 42804 this exists to avoid.\n *\n * A deferred value has exactly ONE provenance — a step output, which is a\n * row the driver returned — so it arrives in the spelling that projection\n * published: LOWERCASE HEX for a `bytes` column, canonical text for a\n * `uuid` or text-stored one. A plain cast of that hex into the binary type\n * would bind the hex text's own bytes, so the binary arm decodes it\n * (`decode(…, 'hex')`, `UNHEX`, `unhex`). SQLite's `unhex()` arrived in\n * 3.41, above this adapter's 3.35 floor: a compact identifier on SQLite\n * needs 3.41, and so does a bytes list longer than `literals.list` keeps\n * parenthesized; nothing else here does.\n */\n idCast: (expr: Sql, representation: IdRepresentation) => Sql;\n\n // Utility\n coalesce: (...exprs: Sql[]) => Sql;\n /** Reserved — not called by the query engine yet. */\n greatest: (...exprs: Sql[]) => Sql;\n /** Reserved — not called by the query engine yet. */\n least: (...exprs: Sql[]) => Sql;\n cast: (expr: Sql, type: CastType) => Sql;\n /**\n * Hex-encode a binary column for JSON embedding — JSON can't hold binary\n * (PG: encode(x, 'hex'), MySQL/SQLite: lower(hex(x))).\n * The result parser decodes hex back to Uint8Array.\n */\n blobToHex: (expr: Sql) => Sql;\n };\n\n /**\n * AGGREGATES\n * Aggregate functions\n */\n aggregates: {\n count: (expr?: Sql) => Sql;\n countDistinct: (expr: Sql) => Sql;\n sum: (expr: Sql) => Sql;\n /**\n * A double column's sum as two `SUM`s no row count can overflow: its\n * members of magnitude at least 1e-288 divided by 2^64, and the smaller\n * ones as they are. Dividing such a double by 2^64 is exact, so the first\n * part is the plain sum scaled exactly, and the reader's\n * `high * 2^64 + low` is that sum — `±Infinity` past the double range,\n * where PostgreSQL's own `SUM` raises and MySQL's answers 0 (engine-10).\n *\n * `having` compares `value` and a grouped `orderBy` sorts by `order`, so\n * a group is kept and placed by the sum the projection publishes.\n */\n numberSum: (expr: Sql) => {\n readonly parts: readonly [high: Sql, low: Sql];\n /** The joined sum as one comparable expression. */\n readonly value: Sql;\n /** Sort keys, most significant first, ordering by the joined sum. */\n readonly order: readonly Sql[];\n };\n /**\n * Stated only where an integer `SUM` is int64 and raises past it\n * (SQLite): an int64 column's sum as two `SUM`s no realistic row count\n * can overflow — each member's high 32 bits and the rest — read back\n * exactly as `high * 2^32 + low` (engine-10), compared and sorted as\n * `numberSum` states. PostgreSQL and MySQL already sum integers as exact\n * numerics.\n */\n integerSum?: DatabaseAdapter[\"aggregates\"][\"numberSum\"];\n avg: (expr: Sql) => Sql;\n min: (expr: Sql, boolean?: boolean) => Sql;\n max: (expr: Sql, boolean?: boolean) => Sql;\n /**\n * The average of an EXACT decimal column, in the column's own physical\n * domain and quantized to the field's scale with round-half-to-even.\n *\n * Separate from {@link DatabaseAdapter.aggregates.avg} because `AVG()` is a\n * different function on a decimal: SQLite computes it in a double, and\n * PostgreSQL/MySQL choose the result's scale themselves. This one is\n * derived from the exact `SUM` and `COUNT(column)` — so it is NULL for an\n * empty or all-null group — and rounds by the one shared rule rather than\n * by a provider default.\n */\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor) => Sql;\n\n /**\n * The widened precision needed to cast this exact coefficient as a\n * `having _sum` operand, or `undefined` when the dialect cannot represent\n * that value exactly.\n *\n * `_sum` may exceed one row's precision, but its comparison domain is not\n * unbounded. PostgreSQL and MySQL admit by their exact decimal precision;\n * SQLite admits by signed-int64 VALUE, whose valid range contains some but\n * not all 19-digit coefficients. The adapter owns that provider fact so the\n * query engine never branches on a dialect or silently binds a saturated\n * value.\n */\n decimalSumOperandPrecision: (coefficient: string) => number | undefined;\n };\n\n /**\n * JSON\n * Database-specific JSON building and extraction\n */\n json: {\n /** Structural JSON equality: object key order is insignificant. */\n equals: (left: Sql, right: Sql) => Sql;\n /** Convert a SQL predicate into a JSON boolean value. */\n boolean: (condition: Sql) => Sql;\n /** Preserve a SQL expression as a JSON document when embedding it in JSON. */\n document: (expression: Sql) => Sql;\n /** Carry a finite number through JSON without losing binary precision. */\n number: (expression: Sql) => Sql;\n /** Build JSON object from key-value pairs */\n object: (pairs: [string, Sql][]) => Sql;\n /** Build JSON array from items */\n array: (items: Sql[]) => Sql;\n /** Empty JSON array literal: '[]'::json (PG), JSON_ARRAY() (MySQL), '[]' (SQLite) */\n emptyArray: () => Sql;\n /**\n * Aggregate rows into a JSON array. An empty aggregate is the empty array,\n * never SQL NULL, so no caller wraps it in its own COALESCE. `expr` is a\n * JSON value as built here (`object`, `array`): one read back through a\n * subquery column goes through `document` first, which SQLite needs to\n * keep it a JSON value rather than a quoted string.\n */\n agg: (expr: Sql) => Sql;\n /** Build JSON object from explicit column list (works on all databases) */\n objectFromColumns: (columns: [string, Sql][]) => Sql;\n /**\n * Extract the JSON value at a path (empty path = document root) in a\n * form comparable against `json.value` params. Integer segments address\n * array elements. Used by JSON path filters in the where-builder.\n */\n extract: (column: Sql, path: string[]) => Sql;\n /**\n * Extract the value at a path as text (strings unquoted; empty path =\n * document root). Used by JSON string_contains/starts_with/ends_with.\n */\n extractText: (column: Sql, path: string[]) => Sql;\n /**\n * The value at `path` as a double-precision number, or SQL NULL when the\n * path is absent or the JSON value there is NOT a JSON number. Every\n * dialect gates the cast behind its own JSON type test (PG jsonb_typeof,\n * MySQL JSON_TYPE, SQLite json_type) so a non-numeric value yields NULL\n * instead of a cast error. Used by JSON lt/lte/gt/gte with number\n * operands: NULL never satisfies a comparison, so mismatched types and\n * absent paths never match and never error.\n */\n numberAtPath: (column: Sql, path: string[]) => Sql;\n /**\n * The value at `path` as unquoted text under a byte-ordered collation\n * (PG COLLATE \"C\", MySQL VARBINARY, SQLite COLLATE BINARY), or SQL NULL\n * when the path is absent or the JSON value there is NOT a JSON string.\n * The forced collation makes `<`/`>` code-point ordering on every\n * dialect instead of the database's default (locale) collation. Used by\n * JSON lt/lte/gt/gte with string operands.\n */\n stringAtPath: (column: Sql, path: string[]) => Sql;\n /**\n * `stringAtPath` in the database's own text type and collation, for\n * `mode: \"insensitive\"`: the byte-ordered pin stops a database folding\n * case (`LOWER`/`ILIKE` under PG `COLLATE \"C\"` fold `A`-`Z` only, and\n * MySQL's `LOWER` leaves a binary string as it is).\n */\n foldableStringAtPath: (column: Sql, path: string[]) => Sql;\n /**\n * JSON array containment: target is an array containing every element\n * of the candidate JSON array value (PG @>, MySQL JSON_CONTAINS,\n * SQLite json_each). Used by the array_contains filter.\n */\n contains: (target: Sql, value: Sql) => Sql;\n /**\n * Last element of a JSON array (PG -> -1, MySQL $[last],\n * SQLite $[#-1]). Used by the array_ends_with filter.\n */\n lastElement: (target: Sql) => Sql;\n /**\n * Parameterized JSON value usable in comparisons against a JSON column.\n * PG: plain param (jsonb), MySQL: CAST(? AS JSON) so equality compares\n * JSON documents instead of coercing to a JSON string scalar,\n * SQLite: canonical JSON text param.\n */\n value: (v: unknown) => Sql;\n };\n\n /**\n * ARRAYS\n * Array operations (PG: native arrays, MySQL/SQLite: JSON-based)\n */\n arrays: {\n /**\n * Create array literal. Reserved — not called by the query engine yet.\n */\n literal: (items: Sql[]) => Sql;\n /**\n * Parameterized value for a complete list in the dialect's storage\n * format: native array param (PG), CAST(? AS JSON) (MySQL), canonical\n * JSON text param (SQLite). Used for list writes and equals/not filters.\n */\n value: (values: unknown[], temporal?: \"date\" | \"datetime\") => Sql;\n /**\n * Parameterized value for a complete ENUM list.\n *\n * The one list whose element type no driver can serialize: a PostgreSQL\n * managed enum is created by the estate, so its array OID is in no driver's\n * serializer table and the native array parameter above reaches the server\n * as `ADMIN,USER` (22P02). PostgreSQL binds the array literal as ONE\n * untyped parameter and lets the column or operand it meets resolve the\n * type, so the enum's NAME stays with the migration driver that generated\n * it and never appears in runtime SQL. The JSON-backed dialects answer with\n * the same container every other list uses — there, an enum list has no\n * element type to spell at all.\n */\n enumValue: (values: unknown[]) => Sql;\n /**\n * The values a one-column `query` answers, as one array, empty where it\n * answers none (PostgreSQL `ARRAY(…)`). A row tests a key set held this\n * way by {@link has} rather than by joining it: the array is computed once\n * per statement, where a joined set is read again for each row of a\n * correlated subquery. Absent where the dialect has no array value.\n */\n ofRows?: (query: Sql) => Sql;\n /** Check if array contains value */\n has: (column: Sql, value: Sql) => Sql;\n /** Check if array contains all values */\n hasEvery: (column: Sql, values: Sql) => Sql;\n /** Check if array contains any value */\n hasSome: (column: Sql, values: Sql) => Sql;\n /** Check if array is empty */\n isEmpty: (column: Sql) => Sql;\n /**\n * Project a numeric list without a provider/JSON carrier rounding members.\n *\n * Decimal, bigint and floating-point lists share this transport boundary.\n * On a native-array dialect the members are exact text, and\n * the whole-column TEXT cast every other decimal projection uses yields the\n * dialect's own array literal (`{1.20,-0.03}`) rather than an array of\n * members — while embedding the column in a JSON carrier uncast yields JSON\n * NUMBERS, which round past 2^53. Casting ELEMENT-WISE answers both: the\n * flat read gets an array of exact text and the carrier gets a JSON array of\n * strings. On a JSON-backed dialect the container is already an array of\n * coefficient strings and what this owns is that it arrives as TEXT rather\n * than as a driver-parsed document.\n *\n * One name, one meaning, three dialect spellings — the query engine asks for\n * a readable numeric list and never for a dialect cast.\n */\n exactNumericProjection: (column: Sql) => Sql;\n /** Get array length. Reserved — not called by the query engine yet. */\n length: (column: Sql) => Sql;\n /** Get element at index. Reserved — not called by the query engine yet. */\n get: (column: Sql, index: Sql) => Sql;\n /**\n * Append value to array. Reserved — not called by the query engine yet.\n */\n push: (column: Sql, value: Sql) => Sql;\n /** Set value at index. Reserved — not called by the query engine yet. */\n set: (column: Sql, index: Sql, value: Sql) => Sql;\n };\n\n /**\n * ORDER BY\n * Ordering helpers\n */\n orderBy: {\n asc: (column: Sql) => Sql;\n desc: (column: Sql) => Sql;\n /** Directed order placing NULLs first (native on PG, IS NULL sort-key emulation on MySQL/SQLite) */\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\") => Sql;\n /** Directed order placing NULLs last (native on PG, IS NULL sort-key emulation on MySQL/SQLite) */\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\") => Sql;\n };\n\n /**\n * CLAUSES\n * SQL clause keywords\n */\n /**\n * LIMIT value meaning \"no limit\", for dialects that reject OFFSET without\n * LIMIT (MySQL: 18446744073709551615, SQLite: -1).\n * Omit when the dialect supports bare OFFSET (PostgreSQL).\n *\n * It is also the bound an ORDERED derived table states when its caller asked\n * for no window: MySQL merges an unlimited derived table into the query that\n * reads it and the merge takes the ORDER BY with it, so a page whose order a\n * reader consumes (the to-many include's aggregate) spells this value rather\n * than losing it. A dialect that keeps a derived order unbounded declares\n * none and emits nothing.\n */\n noLimitValue?: Sql;\n\n clauses: {\n select: (columns: Sql) => Sql;\n selectDistinct: (columns: Sql) => Sql;\n from: (table: Sql) => Sql;\n where: (condition: Sql) => Sql;\n orderBy: (orders: Sql) => Sql;\n limit: (count: Sql) => Sql;\n offset: (count: Sql) => Sql;\n groupBy: (columns: Sql) => Sql;\n having: (condition: Sql) => Sql;\n };\n\n /**\n * SET\n * UPDATE SET operations\n */\n set: {\n /** Simple assignment: \"col\" = value */\n assign: (column: Sql, value: Sql) => Sql;\n /** Increment: \"col\" = \"col\" + value */\n increment: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /** Decrement: \"col\" = \"col\" - value */\n decrement: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Multiply: \"col\" = \"col\" * value.\n * A decimal target rounds the product back to its scale (see\n * {@link ArithmeticTarget}); every other target multiplies natively.\n */\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Divide: \"col\" = \"col\" / value.\n * `target.integer` tells the adapter the target column is integer-typed\n * so it can force integer division where the dialect would otherwise do\n * real division. SQLite binds the operand as REAL, while MySQL `/` returns\n * a decimal quotient even for integer columns; both adapters use the flag\n * to preserve truncation toward zero. PostgreSQL integer division already\n * has that behavior and ignores the flag. A decimal target instead rounds\n * the quotient to its scale.\n */\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Array push: append the complete provider-encoded `values` container.\n * The query engine selects the scalar's list vocabulary once; the adapter\n * owns only how its dialect concatenates two containers.\n */\n push: (column: Sql, values: Sql) => Sql;\n /** Array unshift: prepend the complete provider-encoded container. */\n unshift: (column: Sql, values: Sql) => Sql;\n };\n\n /**\n * FILTERS\n * Relation filter wrappers for subqueries\n */\n filters: {\n /** `EXISTS`: a row of the subquery exists (`some`, `is`). */\n some: (subquery: Sql) => Sql;\n /** `NOT EXISTS`: none does (`none`, `isNot`, and `every` over the negated condition). */\n none: (subquery: Sql) => Sql;\n };\n\n /**\n * SUBQUERIES\n * Subquery wrappers\n */\n subqueries: {\n /** Scalar subquery: (SELECT ...) */\n scalar: (query: Sql) => Sql;\n /** Correlated subquery with alias */\n correlate: (query: Sql, alias: string) => Sql;\n /** Build EXISTS-style subquery: SELECT 1 FROM table WHERE condition */\n existsCheck: (from: Sql, where: Sql) => Sql;\n /**\n * `condition`, a conjunct of a `WHERE` (a NULL and a false refuse its\n * row alike), placed where its own depth is not added to the\n * expression that holds it: the identity, except where the transport\n * bounds expression depth and the dialect sums nested heights.\n */\n isolated: (condition: Sql) => Sql;\n /**\n * A raw read's `FROM` item for one model's rows (`$rows`): `from` read\n * as `row`, filtered by `where` (every row without one), named `alias`.\n * `implicitRowid`: the table keeps a rowid `SELECT *` leaves out; SQLite\n * carries it as `rowid`, the key an FTS5 table joins on.\n */\n rows: (\n from: Sql,\n row: string,\n where: Sql | undefined,\n alias: string,\n implicitRowid: boolean\n ) => Sql;\n };\n\n /**\n * CTE\n * Common Table Expressions\n */\n cte: {\n /**\n * Build WITH clause: WITH name AS (query), ... A member `inlined` is read\n * correlated to each outer row through its own columns: PostgreSQL would\n * materialize a member read twice and scan it, without an index, once\n * per row, so it is written `NOT MATERIALIZED` there. A member\n * `inlined: false` is computed once: SQLite would inline it at every\n * use, so it is written `MATERIALIZED` there. Without `inlined`, the\n * database decides. A `recursive` member's query is its two terms,\n * `anchor UNION recursive`, and makes the clause `WITH RECURSIVE`.\n */\n with: (\n definitions: {\n name: string;\n query: Sql;\n inlined?: boolean;\n recursive?: boolean;\n }[]\n ) => Sql;\n /**\n * Build recursive CTE: WITH RECURSIVE name AS (anchor UNION ALL recursive).\n * The query engine calls only the `\"distinct\"` mode (`UNION`); the default\n * `\"all\"` mode is reserved — not called by the query engine yet.\n */\n recursive: (\n name: string,\n anchor: Sql,\n recursive: Sql,\n union?: \"all\" | \"distinct\"\n ) => Sql;\n /** Whether `query` opens with its own `WITH`: a statement holds only one. */\n opens: (query: Sql) => boolean;\n };\n\n /**\n * MUTATIONS\n * Insert, Update, Delete operations\n */\n mutations: {\n /** How top-level bulk create realizes duplicate-only skipping. */\n skipDuplicatesStrategy: \"sql\" | \"recoverableUniqueError\";\n /** INSERT INTO table (cols) from literal rows or a SELECT source. */\n insert: (\n table: Sql,\n columns: string[],\n source: Sql[][] | { readonly select: Sql },\n prefix?: Sql\n ) => Sql;\n /**\n * INSERT the rows that are not there, by `key`, the columns of one unique\n * constraint of `table`: a row that is there stays as it is, or takes\n * `sets`, unless it holds `unless` already. One statement where the\n * dialect names a conflict target, and elsewhere the statements that\n * leave the table the same.\n */\n insertAbsent: (\n table: Sql,\n columns: string[],\n rows: Sql[][],\n key: readonly string[],\n sets?: Sql,\n unless?: Sql\n ) => Sql[];\n /** Insert one row using only database defaults. */\n insertDefault: (table: Sql) => Sql;\n /** UPDATE table SET ... WHERE ... */\n update: (table: Sql, sets: Sql, where?: Sql) => Sql;\n /**\n * UPDATE table SET ... from `source` (a derived table, aliased) joined\n * `on` the row written, WHERE ...: `UPDATE … FROM` (PostgreSQL, SQLite),\n * `UPDATE … JOIN` (MySQL).\n */\n updateFrom: (\n table: Sql,\n sets: Sql,\n source: Sql,\n on: Sql,\n where?: Sql\n ) => Sql;\n /** DELETE FROM table WHERE ... */\n delete: (table: Sql, where?: Sql) => Sql;\n /** RETURNING clause (PG/SQLite) or empty (MySQL) */\n returning: (columns: Sql) => Sql;\n /**\n * A `RETURNING` expression true where an `INSERT … ON CONFLICT DO UPDATE`\n * inserted its row rather than updated it (PostgreSQL: `xmax = 0`).\n * Absent where the statement cannot say: an upsert that must report its\n * arm then reads the row first.\n */\n upserted?: Sql;\n /**\n * ON CONFLICT / ON DUPLICATE KEY\n * @param target - Conflict target columns (e.g., \"id\")\n * @param action - Action to take (e.g., UPDATE SET ...)\n * @param targetWhere - Optional WHERE for partial unique index matching\n * PostgreSQL: ON CONFLICT (id) WHERE <targetWhere> DO UPDATE ...\n */\n onConflict: (target: Sql | null, action: Sql, targetWhere?: Sql) => Sql;\n /**\n * Build update action for ON CONFLICT (PG/SQLite: UPDATE SET ..., MySQL: just the SET part)\n * @param sets - SET clause assignments\n * @param setWhere - Optional WHERE for conditional updates\n * PostgreSQL: ... DO UPDATE SET x = y WHERE <setWhere>\n */\n onConflictUpdate: (sets: Sql, setWhere?: Sql) => Sql;\n /**\n * The action that leaves a row in conflict as it is. Present where the\n * dialect has a targeted upsert (PostgreSQL, SQLite): MySQL's\n * `ON DUPLICATE KEY UPDATE` has no such action.\n */\n onConflictNothing?: () => Sql;\n /**\n * Skip duplicate key errors (for createMany with skipDuplicates: true)\n * PostgreSQL/SQLite: ON CONFLICT DO NOTHING (suffix)\n * MySQL: duplicate-key-only no-op update (suffix)\n *\n * UNTARGETED ON PURPOSE, and that is the whole distinction from\n * {@link DatabaseAdapter.mutations.onConflict}: `createMany({\n * skipDuplicates: true })` promises to skip a row that collides with ANY\n * unique constraint, so naming one would be the wrong answer. A JUNCTION\n * membership insert asks the opposite question — skip only an exact repeat\n * of this complete `(owner, target)` key, and let a target-side UNIQUE\n * (a singular polymorphic member's occupied slot) raise — so it goes\n * through the targeted door instead. See `junctionDuplicateSkip` in\n * `query-engine/builders/many-to-many-utils.ts`; do not route it back here.\n */\n skipDuplicates: (duplicateNoopColumn: string) => {\n prefix: Sql;\n suffix: Sql;\n };\n };\n\n /**\n * ASSERTIONS\n * Dialect-specific statements that abort a batch when a precondition fails.\n */\n assertions: {\n /** Abort unless the provided SELECT returns at least one row. */\n exists: (query: Sql) => Sql;\n /** Abort unless the provided SELECT returns no rows. */\n notExists: (query: Sql) => Sql;\n };\n\n capabilities: DatabaseAdapterCapabilities;\n\n /**\n * LAST INSERT ID\n * Returns SQL for getting the last auto-generated ID.\n * Used only where the provider exposes an exact statement-local identity.\n *\n * PostgreSQL: lastval() exists for legacy/direct SQL uses, but batchRefs does not\n * expose it because another generated column or trigger can change the session value\n * SQLite: last_insert_rowid() - returns last ROWID inserted\n * MySQL: LAST_INSERT_ID() - returns last AUTO_INCREMENT value\n */\n lastInsertId: () => Sql;\n\n /**\n * JOINS\n * Join operations\n */\n joins: {\n inner: (table: Sql, condition: Sql) => Sql;\n left: (table: Sql, condition: Sql) => Sql;\n right: (table: Sql, condition: Sql) => Sql;\n full: (table: Sql, condition: Sql) => Sql;\n cross: (table: Sql) => Sql;\n /**\n * LATERAL subquery join (PostgreSQL 9.3+, MySQL 8.0.14+)\n * Allows referencing columns from preceding tables in the subquery.\n * Used for efficient nested includes.\n *\n * @param subquery - The lateral subquery (must be a complete SELECT)\n * @param alias - Alias for the lateral result\n * @returns JOIN LATERAL (subquery) AS alias ON true\n */\n lateral: (subquery: Sql, alias: string) => Sql;\n /**\n * LEFT JOIN LATERAL - same as lateral but with LEFT JOIN semantics\n * Returns NULL for the joined columns when subquery returns no rows.\n *\n * @param subquery - The lateral subquery (must be a complete SELECT)\n * @param alias - Alias for the lateral result\n * @returns LEFT JOIN LATERAL (subquery) AS alias ON true\n */\n lateralLeft: (subquery: Sql, alias: string) => Sql;\n };\n\n /**\n * SET OPERATIONS\n * UNION, INTERSECT, EXCEPT operations\n */\n setOperations: {\n /** UNION (removes duplicates) */\n union: (...queries: Sql[]) => Sql;\n /** UNION ALL (keeps duplicates). */\n unionAll: (...queries: Sql[]) => Sql;\n /** INTERSECT */\n intersect: (...queries: Sql[]) => Sql;\n /** EXCEPT / MINUS */\n except: (left: Sql, right: Sql) => Sql;\n };\n\n /**\n * VECTOR\n * Vector operations for similarity search (pgvector)\n *\n * The `_distance` metrics `{ l2, cosine }`: the selected distance, and the\n * order key of a distance `orderBy`. Drivers that don't support vector\n * operations can override this property with an object that throws\n * FeatureNotSupportedError.\n *\n * Without `order` a metric is the distance VALUE. With it, an order key: an\n * `\"exact\"` key is one no index can serve, so the order is exact whatever\n * index the column has; a `\"servable\"` key is one a nearest-neighbour index\n * may serve, and is approximate where it does.\n */\n vector: {\n /** Create a vector literal from number array: '[1,2,3]'::vector */\n literal: (values: number[]) => Sql;\n /** L2 (Euclidean) distance: column <-> vector */\n l2: (column: Sql, vector: Sql, order?: VectorOrderKey) => Sql;\n /** Cosine distance: column <=> vector */\n cosine: (column: Sql, vector: Sql, order?: VectorOrderKey) => Sql;\n };\n\n /**\n * Exact EPSG:4326 point SQL. Absence means this adapter has no physical\n * GeoPoint tier; optional members distinguish the full polygon/distance tier.\n */\n readonly geoPoint?: GeoPointSql;\n\n result: AdapterResultParser;\n}\n","/**\n * The ONE round-half-to-even rule, spelled in each dialect's exact integer\n * vocabulary.\n *\n * Multiply, divide and average are the only operations that can create digits\n * beyond a decimal field's scale, so they are the only ones that round — and\n * they round the same way everywhere, because a rounding mode that came from\n * the provider would make the same query answer differently per database.\n * Nothing here consults a provider default: quotient, remainder and parity are\n * exact integer facts, and the arms are composed from them.\n *\n * WHY A QUOTIENT RULE AND NOT A ROUNDING FUNCTION. `ROUND()` is half-up on\n * MySQL, half-even-ish on PostgreSQL numerics, and absent on SQLite; every one\n * of them would have to be trusted at the exact tie this rule exists to decide.\n * Quotient/remainder/parity are the same three integers on all three.\n *\n * NO PATH CASTS THROUGH REAL. Every operand below is an integer or an exact\n * decimal, and every operator applied to them is exact in its dialect.\n */\n\nimport { type Sql, sql } from \"@sql\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\n\n/**\n * How one dialect spells EXACT truncated division and its remainder.\n *\n * `quotient(n, d)` truncates toward zero and `remainder(n, d)` carries the sign\n * of `n`, which is C semantics and what all three dialects already do — but\n * they spell it three ways, and one of the three (`n / d`) is only integer\n * division when both operands are integers. Each adapter declares its own pair\n * so this file never asks which database it is running against.\n */\nexport interface ExactIntegerArithmetic {\n /** `n / d` truncated toward zero. `d` is never zero unless `n` is NULL. */\n readonly quotient: (n: Sql, d: Sql) => Sql;\n /** `n - quotient(n, d) * d`; sign follows `n`. */\n readonly remainder: (n: Sql, d: Sql) => Sql;\n}\n\n/** `10^scale`, the factor between a logical value and its coefficient. */\nexport const scaleFactorSql = (scale: number): Sql =>\n sql.raw(`1${\"0\".repeat(scale)}`);\n\n/**\n * `10^-scale`: one unit in the last place of the field's domain, as an exact\n * decimal literal. Multiplying a coefficient by it is exact on PostgreSQL and\n * MySQL (scales add); DIVIDING by `10^scale` is not — MySQL computes a quotient\n * to `div_precision_increment` extra digits and rounds there, which would put a\n * provider default back in charge of the last digit.\n */\nexport const scaleUnitSql = (scale: number): Sql =>\n sql.raw(scale === 0 ? \"1\" : `0.${\"0\".repeat(scale - 1)}1`);\n\n/**\n * `n / d` rounded half to even, for `d > 0` and any sign of `n`.\n *\n * The three facts: `q` is the truncated quotient, `r` the remainder, and the\n * decision compares `|r|` against `d - |r|` — below is down, above is away from\n * zero, and EQUAL is the tie, resolved by `q`'s parity so the even neighbour\n * wins.\n *\n * WHY `|r| vs d - |r|` AND NOT `2|r| vs d`. They decide identically (`|r| >\n * d - |r|` is `2|r| > d` rearranged), but the doubled form is the only one that\n * can leave the dialect's exact domain: `|r| < d`, so `d - |r|` is bounded by\n * the divisor while `2|r|` needs one digit MORE than it. That extra digit is\n * the whole domain on the two dialects with a finite one — a 65-digit MySQL\n * divisor doubles to 66, and an int64 count doubles past int64 — so the\n * comparison is written in the form that never widens.\n *\n * The sign of the step reads `r`, not `n`: the step is taken only when `r <> 0`\n * (`|r| > d - |r| >= 0`, or `|r| = d - |r|` which needs `r <> 0` for a non-zero\n * `d`), and a non-zero remainder has exactly the sign of the dividend. Reading\n * `r` keeps one fewer copy of `n` in the emitted statement.\n *\n * `d` MUST be positive. A negative divisor would flip which neighbour is\n * \"away\", so the callers below normalize the sign onto the numerator instead.\n */\nexport const halfEvenQuotient = (\n integers: ExactIntegerArithmetic,\n n: Sql,\n d: Sql\n): Sql => {\n const q = integers.quotient(n, d);\n const r = integers.remainder(n, d);\n const parity = integers.remainder(q, sql.raw`2`);\n return sql`(${q} + (CASE WHEN ABS(${r}) > ${d} - ABS(${r}) OR (ABS(${r}) = ${d} - ABS(${r}) AND ${parity} <> 0) THEN (CASE WHEN ${r} < 0 THEN -1 ELSE 1 END) ELSE 0 END))`;\n};\n\n/**\n * `n` with the divisor's sign folded in, so the half-even rule always sees a\n * positive divisor. `n x sign(d)` and `|d|` name the same quotient as `n / d`.\n */\nexport const signedNumerator = (n: Sql, d: Sql): Sql =>\n sql`(CASE WHEN ${d} < 0 THEN -${n} ELSE ${n} END)`;\n\n/**\n * `column = halfEven(column x by)` where the column holds the LOGICAL decimal\n * in a dialect whose exact decimal domain is UNBOUNDED — PostgreSQL's\n * `NUMERIC`, which computes an expression at whatever width the value needs.\n *\n * The rule is stated on the COEFFICIENT, so the product is scaled up by `10^s`\n * — leaving a value whose integer part is the answer's coefficient and whose\n * fraction is what has to be rounded away — rounded to an integer against a\n * divisor of one, and scaled back by one exact multiplication.\n *\n * The widest intermediate is `column x by x 10^s`, which needs `2p + s` digits.\n * That is why MySQL does NOT use this form: its exact domain stops at 65\n * digits, and past it MySQL rounds an over-scaled product to 30 fractional\n * digits or answers ZERO without a warning. MySQL spells the same rule in its\n * own bounded, coefficient-space form (`mysql-adapter.ts`); this one is\n * PostgreSQL's, where no such ceiling exists.\n */\nexport const logicalDecimalMultiply = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const scaled = sql`(${column} * ${by} * ${scaleFactorSql(descriptor.scale)})`;\n const coefficient = halfEvenQuotient(integers, scaled, sql.raw`1`);\n return sql`${column} = ${coefficient} * ${scaleUnitSql(descriptor.scale)}`;\n};\n\n/**\n * `column = halfEven(column / by)` where the column holds the LOGICAL decimal\n * in an unbounded exact domain ({@link logicalDecimalMultiply}'s PostgreSQL).\n *\n * The quotient is never computed by the dialect's `/`: the answer's coefficient\n * is `halfEven((column x 10^s) / by)`, which is a quotient of an exact integer\n * by an exact decimal, so remainder and parity decide the last digit instead of\n * `div_precision_increment` or a numeric division's chosen scale.\n *\n * `by` is non-zero: division by canonical zero is refused before I/O, where the\n * operand's canonical text is still in hand (`set-builder.ts`).\n */\nexport const logicalDecimalDivide = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n integers,\n signedNumerator(sql`(${column} * ${scaleFactorSql(descriptor.scale)})`, by),\n sql`ABS(${by})`\n );\n return sql`${column} = ${coefficient} * ${scaleUnitSql(descriptor.scale)}`;\n};\n\n/**\n * The exact decimal average of a LOGICAL decimal column in an unbounded exact\n * domain ({@link logicalDecimalMultiply}'s PostgreSQL): the exact `SUM` over\n * `COUNT(column)`, quantized to the field's scale half to even.\n *\n * `COUNT(column)` counts NON-NULL values, which is what makes the empty and\n * all-null cases answer NULL rather than divide by zero: `SUM` of no non-null\n * rows is NULL, every operator below is null-strict, and the zero divisor is\n * therefore never reached with a non-null numerator.\n *\n * `AVG()` is deliberately unused. It is a double on SQLite, and on the other\n * two its result scale is the provider's choice rather than the field's.\n */\nexport const logicalDecimalAverage = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n integers,\n sql`(SUM(${column}) * ${scaleFactorSql(descriptor.scale)})`,\n sql`COUNT(${column})`\n );\n return sql`(${coefficient} * ${scaleUnitSql(descriptor.scale)})`;\n};\n","import type { GeoPointSql } from \"@adapters/database-adapter\";\nimport { type Sql, sql } from \"@sql\";\nimport type {\n GeoBounds,\n GeoPolygon,\n} from \"@validation/primitives/geo-area-codec\";\n\ntype CoordinateOperations = {\n readonly and: (...conditions: Sql[]) => Sql;\n readonly or: (...conditions: Sql[]) => Sql;\n readonly eq: (left: Sql, right: Sql) => Sql;\n readonly gte: (left: Sql, right: Sql) => Sql;\n readonly lte: (left: Sql, right: Sql) => Sql;\n};\n\ntype IndexableBounds = (point: Sql, bounds: GeoBounds) => Sql | undefined;\n\n/**\n * Coordinate equality and inclusive bounds are one logical contract on every\n * provider. Only coordinate extraction differs, so this is their single owner.\n */\nexport function createGeoPointCoordinatePredicates(\n longitude: GeoPointSql[\"longitude\"],\n latitude: GeoPointSql[\"latitude\"],\n operators: CoordinateOperations,\n indexableBounds?: IndexableBounds\n): Pick<GeoPointSql, \"equals\" | \"withinBounds\"> {\n return {\n equals(point, expected) {\n const pointLongitude = longitude(point);\n let longitudeCondition = operators.eq(\n pointLongitude,\n sql`${expected.longitude}`\n );\n // -180 and +180 are one canonical meridian. Storage written outside the\n // ORM may still contain the physical -180 spelling that the value codec\n // presents as +180.\n if (expected.longitude === 180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${-180}`)\n );\n }\n return operators.and(\n longitudeCondition,\n operators.eq(latitude(point), sql`${expected.latitude}`)\n );\n },\n withinBounds(point, bounds) {\n const pointLongitude = longitude(point);\n const latitudeCondition = operators.and(\n operators.gte(latitude(point), sql`${bounds.south}`),\n operators.lte(latitude(point), sql`${bounds.north}`)\n );\n\n let exactCondition: Sql;\n if (bounds.west === -180 && bounds.east === 180) {\n exactCondition = latitudeCondition;\n } else {\n const westArm = operators.gte(pointLongitude, sql`${bounds.west}`);\n const eastArm = operators.lte(pointLongitude, sql`${bounds.east}`);\n let longitudeCondition =\n bounds.west > bounds.east\n ? operators.or(westArm, eastArm)\n : operators.and(westArm, eastArm);\n\n // GeoPoint canonicalizes -180 to +180. A normal interval whose western\n // boundary is -180 still contains that one physical meridian.\n if (bounds.west === -180 && bounds.east < 180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${180}`)\n );\n }\n // The inverse endpoint is the same canonical meridian: an external\n // writer may have stored -180 while the logical interval ends at +180.\n if (bounds.east === 180 && bounds.west > -180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${-180}`)\n );\n }\n exactCondition = operators.and(latitudeCondition, longitudeCondition);\n }\n const indexCondition = indexableBounds?.(point, bounds);\n return indexCondition\n ? operators.and(indexCondition, exactCondition)\n : exactCondition;\n },\n };\n}\n\n/**\n * GeoJSON rectangles safe to use only as conservative spatial-index probes.\n * Empty means the exact coordinate predicate is the only portable shape for\n * this boundary (world, pole, zero-area, or the canonical -180 meridian case).\n */\nexport function geoBoundsIndexPolygons(bounds: GeoBounds): readonly string[] {\n if (\n bounds.south === -90 ||\n bounds.north === 90 ||\n bounds.south === bounds.north ||\n bounds.west === bounds.east ||\n bounds.west > bounds.east ||\n bounds.west === -180 ||\n bounds.east === 180\n ) {\n return [];\n }\n return [\n boundsPolygonJson(bounds.west, bounds.east, bounds.south, bounds.north),\n ];\n}\n\nfunction boundsPolygonJson(\n west: number,\n east: number,\n south: number,\n north: number\n): string {\n // Geography edges are great-circle arcs. Include every axis meridian so\n // their geocentric bounding box encloses the full coordinate rectangle.\n const meridians = [\n west,\n ...[-90, 0, 90].filter((x) => west < x && x < east),\n east,\n ];\n const southEdge = meridians.map((longitude) => [longitude, south]);\n const northEdge = [...meridians]\n .reverse()\n .map((longitude) => [longitude, north]);\n return JSON.stringify({\n type: \"Polygon\",\n coordinates: [[...southEdge, ...northEdge, southEdge[0]]],\n });\n}\n\n/** One bound GeoJSON document; callers never contribute SQL or WKT text. */\nexport function geoPolygonJson(polygon: GeoPolygon): string {\n const rings: number[][][] = [closedRing(polygon.outer)];\n if (polygon.holes) {\n for (const hole of polygon.holes) rings.push(closedRing(hole));\n }\n return JSON.stringify({ type: \"Polygon\", coordinates: rings });\n}\n\nfunction closedRing(ring: GeoPolygon[\"outer\"]): number[][] {\n const result = new Array<number[]>(ring.length + 1);\n for (let index = 0; index < ring.length; index += 1) {\n const point = ring[index]!;\n result[index] = [point.longitude, point.latitude];\n }\n const first = ring[0]!;\n result[ring.length] = [first.longitude, first.latitude];\n return result;\n}\n","import { type Sql, sql } from \"@sql\";\nimport type { QueryParts } from \"../adapter-query-parts\";\n\ninterface SelectAssemblyOptions {\n forUpdate: \"append\" | \"omit\";\n /** LIMIT value meaning \"no limit\", for dialects that reject OFFSET without LIMIT */\n noLimitValue?: Sql;\n}\n\nexport const assembleSelectQuery = (\n selectClause: Sql,\n parts: QueryParts,\n options: SelectAssemblyOptions\n): Sql => {\n const fragments: Sql[] = [selectClause, sql`FROM ${parts.from}`];\n\n appendSelectParts(fragments, parts, options);\n\n if (options.forUpdate === \"append\" && parts.forUpdate) {\n fragments.push(sql.raw`FOR UPDATE`);\n }\n\n return sql.join(fragments, \" \");\n};\n\nconst appendSelectParts = (\n fragments: Sql[],\n parts: QueryParts,\n options: SelectAssemblyOptions\n): void => {\n appendFilterParts(fragments, parts);\n\n if (parts.orderBy) {\n fragments.push(sql`ORDER BY ${parts.orderBy}`);\n }\n\n appendLimitOffset(fragments, parts.limit, parts.offset, options.noLimitValue);\n};\n\n/** Joins, WHERE, GROUP BY and HAVING: shared by the plain and the emulated-DISTINCT select. */\nconst appendFilterParts = (fragments: Sql[], parts: QueryParts): void => {\n if (parts.joins && parts.joins.length > 0) {\n fragments.push(...parts.joins);\n }\n\n if (parts.where) {\n fragments.push(sql`WHERE ${parts.where}`);\n }\n\n if (parts.groupBy) {\n fragments.push(sql`GROUP BY ${parts.groupBy}`);\n }\n\n if (parts.having) {\n fragments.push(sql`HAVING ${parts.having}`);\n }\n};\n\nconst appendLimitOffset = (\n fragments: Sql[],\n limit: Sql | undefined,\n offset: Sql | undefined,\n noLimitValue: Sql | undefined\n): void => {\n if (limit) {\n fragments.push(sql`LIMIT ${limit}`);\n } else if (offset && noLimitValue) {\n // Dialects like MySQL/SQLite have no bare OFFSET; emit their \"no limit\" sentinel\n fragments.push(sql`LIMIT ${noLimitValue}`);\n }\n\n if (offset) {\n fragments.push(sql`OFFSET ${offset}`);\n }\n};\n\n/**\n * Simulate `SELECT DISTINCT ON` using one ROW_NUMBER() window.\n *\n * Used by MySQL/SQLite (no DISTINCT ON support) and by PostgreSQL when an\n * ORDER BY is present: DISTINCT ON would require the ORDER BY to lead with\n * the distinct columns, which changes result ordering. This emulation keeps\n * Prisma semantics — rows are ordered by the user's ORDER BY, then the first\n * row of each distinct group is kept, preserving that order.\n *\n * Generates:\n * SELECT col1, col2, ... FROM (\n * SELECT columns,\n * order_term_1 AS _ord0, ... -- only when ORDER BY present\n * ROW_NUMBER() OVER (PARTITION BY distinct_cols ORDER BY order_cols) AS _rn\n * FROM table\n * WHERE ...\n * ) AS _distinct_subquery\n * WHERE _rn = 1\n * ORDER BY _ord0, ...\n * LIMIT ... OFFSET ...\n *\n * The outer ORDER BY reads the projected `_ordN` terms because the user's\n * ORDER BY references inner table aliases (and relation-order joins) that\n * are out of scope outside the subquery. Ordering the kept rows by those\n * values (and not by a second window ranking every row) spares one sort.\n */\nexport const assembleDistinctOnEmulation = (\n parts: QueryParts,\n distinct: Sql,\n escapeIdentifier: (name: string) => Sql,\n noLimitValue?: Sql\n): Sql => {\n // ORDER BY for ROW_NUMBER() - use provided orderBy or default to distinct columns\n const rowNumberOrder = parts.distinctOrderBy ?? parts.orderBy ?? distinct;\n const order = parts.distinctOrder;\n\n const selectColumns: Sql[] = [parts.columns];\n if (order) {\n selectColumns.push(order.keys);\n }\n selectColumns.push(\n sql`ROW_NUMBER() OVER (PARTITION BY ${distinct} ORDER BY ${rowNumberOrder}) AS ${escapeIdentifier(\"_rn\")}`\n );\n\n // Inner query with ROW_NUMBER()\n const innerFragments: Sql[] = [\n sql`SELECT ${sql.join(selectColumns, \", \")}`,\n sql`FROM ${parts.from}`,\n ];\n\n appendFilterParts(innerFragments, parts);\n\n const innerQuery = sql.join(innerFragments, \" \");\n\n // Outer query that filters for first row of each partition. It names the\n // output columns so _rn/_ordN stay inside: every engine DISTINCT carrier\n // states its aliases.\n const aliasColumns = parts.distinctColumnAliases!.map(escapeIdentifier);\n const outerFragments: Sql[] = [\n sql`SELECT ${sql.join(aliasColumns, \", \")} FROM (${innerQuery}) AS ${escapeIdentifier(\"_distinct_subquery\")}`,\n sql`WHERE ${escapeIdentifier(\"_rn\")} = 1`,\n ];\n\n if (order) {\n outerFragments.push(sql`ORDER BY ${order.orderBy}`);\n }\n\n appendLimitOffset(outerFragments, parts.limit, parts.offset, noLimitValue);\n\n return sql.join(outerFragments, \" \");\n};\n"],"mappings":"gFA0BA,SAAgB,gCACd,EACsB,CACtB,IAAM,UAAY,EAAmB,KAAsC,CACzE,OACA,gBAAiB,CAAE,MAAO,EAAW,WAAY,EAAM,CACxD,EACD,MAAO,CACL,WAAa,GAAc,SAAS,EAAW,EAAe,EAAU,CAAC,CACzE,QAAS,EAAW,IAClB,SAAS,EAAW,GAAG,EAAU,GAAG,EAAQ,MAAM,CACrD,CAIH,MAAa,EAAmD,CAC9D,YAAa,EAAW,KAAa,CACnC,KAAM,GAAG,EAAU,OACnB,gBAAiB,CACf,MAAO,EACP,QAAS,CAAC,GAAG,EAAQ,CACtB,CACF,EACD,QAAS,EAAW,EAAS,KAAa,CACxC,KAAM,GAAG,EAAU,GAAG,EAAQ,MAC9B,gBAAiB,CACf,MAAO,EACP,QAAS,CAAC,GAAG,EAAQ,CACtB,CACF,EACF,CCjBD,SAAgB,mBACd,EACA,EACM,CACN,IAAI,EACJ,GAAI,EAAU,CACZ,IAAM,EAAgB,EAAS,cACzB,EAAW,EAAS,SAC1B,EAAY,OAAO,OAAoB,CACrC,MAAO,EAAS,MAChB,UAAW,EAAS,UACpB,SAAU,EAAS,SACnB,OAAQ,EAAS,OACjB,aAAc,EAAS,aACvB,GAAI,EAAgB,CAAE,gBAAe,CAAG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,EAAI,KAAK,EAAc,KAAK,CAAC,SAAS,EAAW,OAAO,EAAiB,qBAAqB,GAC3G,CAAG,SAAS,EAAiB,MAAM,CAAC,MACrC,CAQD,OANI,GACF,EAAe,KAAK,CAAG,YAAY,EAAM,UAAU,CAGrD,kBAAkB,EAAgB,EAAM,MAAO,EAAM,OAAQ,EAAa,CAEnEA,EAAI,KAAK,EAAgB,IAAI"}
|
package/dist/sql-3o4DOKm9.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";var t=class Sql{rawStrings;rawValues;projection;statements;constructor(e,t){if(e.length-1!==t.length)throw e.length===0?TypeError(`Expected at least 1 string`):TypeError(`Expected ${e.length} strings to have ${e.length-1} values`);this.rawStrings=e,this.rawValues=t}get values(){return this.flatten().values}get strings(){return this.flatten().strings}static peek(e){if(e.projection!==void 0)return e.projection;let t=[],n=[],r=``,walk=(e,i)=>{r+=e[0];for(let a=0;a<i.length;a++){let o=i[a];o instanceof Sql?walk(o.rawStrings,o.rawValues):(n.push(o),t.push(r),r=``),r+=e[a+1]}};return walk(e.rawStrings,e.rawValues),t.push(r),{strings:t,values:n}}static leafText(e){return e.rawValues.length===0?e.rawStrings[0]:void 0}static peekRuns(e,t){let n=[],r=[],i=``,a=!1,cut=e=>{e!==a&&(n.push({text:i,opaque:a}),i=``,a=e)},walk=(e,o)=>{let s=o||t(e);cut(s),i+=e.rawStrings[0];for(let t=0;t<e.rawValues.length;t++){let o=e.rawValues[t];o instanceof Sql?(walk(o,s),cut(s)):(r.push(o),n.push({text:i,opaque:a}),i=``),i+=e.rawStrings[t+1]}};return walk(e,!1),n.push({text:i,opaque:a}),{runs:n,values:r}}static each(e,t){t(e);for(let n of e.rawValues)n instanceof Sql&&Sql.each(n,t)}static fill(e,t){e.rawStrings=[``,``],e.rawValues=[t]}flatten(){if(this.projection!==void 0)return this.projection;let e=[],t=[],n=``,walk=(r,i)=>{n+=r[0];for(let a=0;a<i.length;a++){let o=i[a];o instanceof Sql?walk(o.rawStrings,o.rawValues):(t.push(o),e.push(n),n=``),n+=r[a+1]}};walk(this.rawStrings,this.rawValues),e.push(n);let r={strings:e,values:t};return this.rawStrings=e,this.rawValues=t,this.projection=r,r}toStatement(e=`?`){let t=this.statements?.[e];if(t!==void 0)return t;let n=this.strings,r=n.length;if(r===1){let e=n[0];return this.statements={$n:e,":n":e,"?":e},e}let i;if(e===`?`)i=n.join(`?`);else{let t=e===`$n`?`$`:`:`,a=Array(r*2-1);a[0]=n[0];for(let e=1;e<r;e++)a[e*2-1]=t+e,a[e*2]=n[e];i=a.join(``)}let a=this.statements??{};return a[e]=i,this.statements=a,i}};function raw(e,...n){if(n.length!==0||typeof e!=`string`&&e.length!==1)throw TypeError(`raw templates cannot interpolate values; use sql for parameters or raw(trustedText) for explicit SQL text.`);return typeof e==`string`?new t([e],[]):new t(e,[])}function join(e,n=`,`,r=``,i=``){let a=e.length;if(a===0)return new t([r+i],[]);let o=Array(a+1);o[0]=r;for(let e=1;e<a;e++)o[e]=n;return o[a]=i,new t(o,e)}const n=raw``;function sql(e,...n){return new t(e,n)}const r=Object.assign(sql,{raw,empty:n,join});function isSql(e){if(e instanceof t)return!0;if(typeof e!=`object`||!e)return!1;let n=Reflect.get(e,`strings`);if(!Array.isArray(n))return!1;let r=Reflect.get(e,`values`);return Array.isArray(r)&&n.length===r.length+1&&n.every(e=>typeof e==`string`)&&typeof Reflect.get(e,`toStatement`)==`function`}export{raw as a,join as i,n,r as o,isSql as r,t};
|
|
2
|
-
//# sourceMappingURL=sql-3o4DOKm9.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sql-3o4DOKm9.mjs","names":["result"],"sources":["../src/sql/sql.ts"],"sourcesContent":["/**\n * Values supported by SQL engine.\n */\nexport type Value = unknown;\n\n/**\n * Supported value or SQL instance.\n */\nexport type RawValue = Value | Sql;\n\ntype Placeholder = \"$n\" | \":n\" | \"?\";\n\ninterface SqlProjection {\n strings: string[];\n values: Value[];\n}\n\ntype StatementCache = Partial<Record<Placeholder, string>>;\n\n/**\n * A SQL instance can be nested within each other to build SQL strings.\n *\n * Composition is lazy: constructing a Sql just stores the raw fragments.\n * The nested tree is flattened in a single pass over raw fragments when\n * `strings`/`values` is first read (typically only on the root query), so\n * intermediate fragments never pay flattening or allocation.\n */\nexport class Sql {\n private rawStrings: readonly string[];\n private rawValues: readonly RawValue[];\n\n private projection: SqlProjection | undefined;\n private statements: StatementCache | undefined;\n\n constructor(rawStrings: readonly string[], rawValues: readonly RawValue[]) {\n if (rawStrings.length - 1 !== rawValues.length) {\n if (rawStrings.length === 0) {\n throw new TypeError(\"Expected at least 1 string\");\n }\n throw new TypeError(\n `Expected ${rawStrings.length} strings to have ${\n rawStrings.length - 1\n } values`\n );\n }\n\n this.rawStrings = rawStrings;\n this.rawValues = rawValues;\n }\n\n get values(): Value[] {\n return this.flatten().values;\n }\n\n get strings(): string[] {\n return this.flatten().strings;\n }\n\n /**\n * The projection {@link flatten} makes of `fragment`, made without keeping\n * it: a fragment holding an open {@link SqlSlot} reads its provisional text\n * and stays open.\n */\n static peek(fragment: Sql): { strings: string[]; values: Value[] } {\n if (fragment.projection !== undefined) return fragment.projection;\n const strings: string[] = [];\n const values: Value[] = [];\n let current = \"\";\n const walk = (\n rawStrings: readonly string[],\n rawValues: readonly RawValue[]\n ): void => {\n current += rawStrings[0]!;\n for (let i = 0; i < rawValues.length; i++) {\n const child = rawValues[i]!;\n if (child instanceof Sql) {\n walk(child.rawStrings, child.rawValues);\n } else {\n values.push(child);\n strings.push(current);\n current = \"\";\n }\n current += rawStrings[i + 1]!;\n }\n };\n walk(fragment.rawStrings, fragment.rawValues);\n strings.push(current);\n return { strings, values };\n }\n\n /**\n * The text of a fragment that holds no value and no fragment (a\n * `sql.raw`), read without composing anything; `undefined` for any other.\n */\n static leafText(fragment: Sql): string | undefined {\n return fragment.rawValues.length === 0 ? fragment.rawStrings[0] : undefined;\n }\n\n /**\n * {@link peek}'s text, also cut where a fragment `opaque` accepts begins\n * and ends, each run saying whether it lies inside one: a reader rewriting\n * the text its owner wrote can leave the text another party wrote alone.\n * Without an opaque fragment the runs are {@link peek}'s strings.\n */\n static peekRuns(\n fragment: Sql,\n opaque: (fragment: Sql) => boolean\n ): { runs: { text: string; opaque: boolean }[]; values: Value[] } {\n const runs: { text: string; opaque: boolean }[] = [];\n const values: Value[] = [];\n let current = \"\";\n let inside = false;\n const cut = (next: boolean): void => {\n if (next === inside) return;\n runs.push({ text: current, opaque: inside });\n current = \"\";\n inside = next;\n };\n const walk = (node: Sql, within: boolean): void => {\n const here = within || opaque(node);\n cut(here);\n current += node.rawStrings[0]!;\n for (let i = 0; i < node.rawValues.length; i++) {\n const child = node.rawValues[i]!;\n if (child instanceof Sql) {\n walk(child, here);\n cut(here);\n } else {\n values.push(child);\n runs.push({ text: current, opaque: inside });\n current = \"\";\n }\n current += node.rawStrings[i + 1]!;\n }\n };\n walk(fragment, false);\n runs.push({ text: current, opaque: inside });\n return { runs, values };\n }\n\n /**\n * Visit `fragment` and every fragment composed into it, outermost first.\n * A flattened fragment holds no fragment any more: only its own visit.\n */\n static each(fragment: Sql, visit: (node: Sql) => void): void {\n visit(fragment);\n for (const child of fragment.rawValues)\n if (child instanceof Sql) Sql.each(child, visit);\n }\n\n /** `slot`'s text replaced by `content`'s (see {@link SqlSlot.settle}). */\n protected static fill(slot: Sql, content: Sql): void {\n slot.rawStrings = [\"\", \"\"];\n slot.rawValues = [content];\n }\n\n /**\n * Flatten the raw fragment tree in one pass, walking children's raw\n * fragments directly so nested Sql instances are never flattened themselves.\n * The flat arrays then replace the raw tree as the canonical representation,\n * releasing child fragments that are not referenced elsewhere.\n */\n private flatten(): SqlProjection {\n if (this.projection !== undefined) {\n return this.projection;\n }\n\n const strings: string[] = [];\n const values: Value[] = [];\n let current = \"\";\n\n const walk = (\n rawStrings: readonly string[],\n rawValues: readonly RawValue[]\n ): void => {\n current += rawStrings[0]!;\n for (let i = 0; i < rawValues.length; i++) {\n const child = rawValues[i]!;\n if (child instanceof Sql) {\n walk(child.rawStrings, child.rawValues);\n } else {\n values.push(child);\n strings.push(current);\n current = \"\";\n }\n current += rawStrings[i + 1]!;\n }\n };\n\n walk(this.rawStrings, this.rawValues);\n strings.push(current);\n\n const projection: SqlProjection = { strings, values };\n\n this.rawStrings = strings;\n this.rawValues = values;\n this.projection = projection;\n\n return projection;\n }\n\n /**\n * Build the final SQL statement string with placeholders.\n * Results are cached per placeholder type for reuse.\n */\n toStatement(placeholder: Placeholder = \"?\"): string {\n const cached = this.statements?.[placeholder];\n if (cached !== undefined) return cached;\n\n const strings = this.strings;\n const len = strings.length;\n\n if (len === 1) {\n const result = strings[0]!;\n this.statements = { $n: result, \":n\": result, \"?\": result };\n return result;\n }\n\n let result: string;\n\n if (placeholder === \"?\") {\n result = strings.join(\"?\");\n } else {\n const prefix = placeholder === \"$n\" ? \"$\" : \":\";\n const parts = new Array<string>(len * 2 - 1);\n parts[0] = strings[0]!;\n for (let i = 1; i < len; i++) {\n parts[i * 2 - 1] = prefix + i;\n parts[i * 2] = strings[i]!;\n }\n result = parts.join(\"\");\n }\n\n const statements = this.statements ?? {};\n statements[placeholder] = result;\n this.statements = statements;\n\n return result;\n }\n}\n\n/**\n * Splice text into a statement verbatim — nothing here is bound as a\n * parameter. Two shapes live under this one name:\n *\n * - `raw(\"ORDER BY name DESC\")` — Prisma's unsafe string splice. The caller\n * owns the escaping; never hand it user input.\n * - ``raw`TRUE` `` — the tagged-template form the adapters use for dialect\n * keywords. Interpolations are refused; use `sql` for bound values.\n */\nfunction raw(value: string | readonly string[]): Sql;\nfunction raw(\n strings: string | readonly string[],\n ...values: readonly RawValue[]\n): Sql {\n if (\n values.length !== 0 ||\n (typeof strings !== \"string\" && strings.length !== 1)\n )\n throw new TypeError(\n \"raw templates cannot interpolate values; use sql for parameters or raw(trustedText) for explicit SQL text.\"\n );\n if (typeof strings === \"string\") {\n return new Sql([strings], []);\n }\n return new Sql(strings, []);\n}\n\n/**\n * Create a SQL query for a list of values.\n *\n * Values are `RawValue`s, matching Prisma: a nested `Sql` is spliced as a\n * fragment, anything else becomes a bound parameter.\n */\nfunction join(\n values: readonly RawValue[],\n separator = \",\",\n prefix = \"\",\n suffix = \"\"\n) {\n const len = values.length;\n if (len === 0) {\n return new Sql([prefix + suffix], []);\n }\n\n // Pre-allocate array with exact size instead of spread + fill\n const strings = new Array<string>(len + 1);\n strings[0] = prefix;\n for (let i = 1; i < len; i++) {\n strings[i] = separator;\n }\n strings[len] = suffix;\n\n return new Sql(strings, values);\n}\n\n/**\n * Placeholder value for \"no text\".\n */\nconst empty = raw``;\n\n/**\n * Create a SQL object from a template string.\n */\nfunction sql(strings: readonly string[], ...values: readonly RawValue[]) {\n return new Sql(strings, values);\n}\n\nconst sqlTag = Object.assign(sql, { raw, empty, join });\n\nexport { empty, join, raw, sqlTag as sql };\n\n/**\n * Type guard for Sql fragments. Structural check rather than instanceof so it\n * also matches fragments from a duplicated module instance. A document with\n * strings/values arrays is data; executable SQL also has the renderer method.\n */\nexport function isSql(value: unknown): value is Sql {\n if (value instanceof Sql) return true;\n if (value === null || typeof value !== \"object\") return false;\n\n const strings = Reflect.get(value, \"strings\");\n if (!Array.isArray(strings)) return false;\n\n const values = Reflect.get(value, \"values\");\n return (\n Array.isArray(values) &&\n strings.length === values.length + 1 &&\n strings.every((part) => typeof part === \"string\") &&\n typeof Reflect.get(value, \"toStatement\") === \"function\"\n );\n}\n"],"mappings":"yCA2BA,IAAa,EAAb,MAAa,GAAI,CACf,WACA,UAEA,WACA,WAEA,YAAY,EAA+B,EAAgC,CACzE,GAAI,EAAW,OAAS,IAAM,EAAU,OAItC,MAHI,EAAW,SAAW,EACd,UAAU,6BAA6B,CAEzC,UACR,YAAY,EAAW,OAAO,mBAC5B,EAAW,OAAS,EACrB,SACF,CAGH,KAAK,WAAa,EAClB,KAAK,UAAY,EAGnB,IAAI,QAAkB,CACpB,OAAO,KAAK,SA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AM,EAAS,QAAQ,IAAI,EAAO,SAAS,CAC3C,OACE,MAAM,QAAQ,EAAO,EACrB,EAAQ,SAAW,EAAO,OAAS,GACnC,EAAQ,MAAO,GAAS,OAAO,GAAS,SAAS,EACjD,OAAO,QAAQ,IAAI,EAAO,cAAc,EAAK"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"standard-sql-qLcQyCtK.mjs","names":["sql"],"sources":["../src/adapters/shared/standard-sql.ts"],"sourcesContent":["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<\n DatabaseAdapter[\"mutations\"],\n \"update\" | \"updateFrom\" | \"delete\"\n>;\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 none: (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 updateFrom: (table, sets, source, on, where) =>\n sql`UPDATE ${table} SET ${sets} FROM ${source} WHERE (${on})${\n where ? sql` AND (${where})` : sql.empty\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\n/** One row's values, in order: `(a, b)`: a judged write's produced rows (`judged.ts`). */\nexport const rowValues = (row: readonly Sql[]): Sql =>\n sql`(${sql.join(row, \", \")})`;\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 * Whether `text` is exactly `<one quoted identifier>.<quotedName>`: a column\n * reference through a table alias whose column is the name itself.\n */\nconst isQualifiedColumnNamed = (\n text: string | undefined,\n quotedName: string,\n quote: string\n): boolean => {\n if (text === undefined || !text.endsWith(quotedName)) return false;\n const qualifier = text.slice(0, -quotedName.length - 1);\n return (\n text[qualifier.length] === \".\" &&\n qualifier.length >= 2 &&\n qualifier[0] === quote &&\n qualifier.at(-1) === quote &&\n !qualifier\n .slice(1, -1)\n .replaceAll(quote + quote, \"\")\n .includes(quote)\n );\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 *\n * `namesQualifiedColumns`: the dialect names an unaliased `\"t\".\"c\"` result\n * column `c` (PostgreSQL, MySQL), so `aliased` leaves out an alias that only\n * repeats the column's own name. SQLite promises no name for an unaliased\n * column, so it always states the alias.\n */\nexport const createIdentifiers = (\n quoteIdent: IdentifierQuoter,\n namespace?: string,\n namesQualifiedColumns = false\n): DatabaseAdapter[\"identifiers\"] => {\n const qualify = createQualifiedIdentifierRenderer(quoteIdent, namespace);\n const quote = quoteIdent(\"\")[0]!;\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 const quoted = quoteIdent(alias);\n return namesQualifiedColumns &&\n isQualifiedColumnNamed(Sql.leafText(expression), quoted, quote)\n ? expression\n : new Sql([\"\", ` AS ${quoted}`], [expression]);\n },\n };\n};\n\nexport const createSubqueries = (\n quoteIdent: IdentifierQuoter,\n rowid = false\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 isolated: (condition: Sql): Sql => condition,\n\n rows: (from, row, where, alias, implicitRowid) =>\n sql`(SELECT ${\n rowid && implicitRowid\n ? sql.raw(`${quoteIdent(row)}.${quoteIdent(\"rowid\")} AS rowid, *`)\n : sql.raw(\"*\")\n } FROM ${from} WHERE ${where ?? sql.raw(\"1 = 1\")}) AS ${sql.raw(\n quoteIdent(alias)\n )}`,\n});\n\n/**\n * `hints` spell a member's form where the dialect would otherwise pick the\n * other one: `inlining` is PostgreSQL 12+'s `NOT MATERIALIZED` (it\n * materializes a member read twice), `materializing` SQLite 3.35+'s\n * `MATERIALIZED` (it inlines every member, compiling its body again at each\n * use). Neither, where the database decides alone.\n */\nexport const createCteBuilders = (\n quoteIdent: IdentifierQuoter,\n hints: { readonly inlining?: Sql; readonly materializing?: Sql } = {}\n): DatabaseAdapter[\"cte\"] => ({\n with: (\n definitions: {\n name: string;\n query: Sql;\n inlined?: boolean;\n recursive?: boolean;\n }[]\n ): Sql => {\n const defs = definitions.map(({ name, query, inlined }) => {\n // A member stating no form (`inlined` absent) is left to the database.\n let hint: Sql | undefined;\n if (inlined !== undefined)\n hint = inlined ? hints.inlining : hints.materializing;\n return hint\n ? sql`${sql.raw(quoteIdent(name))} AS ${hint} (${query})`\n : sql`${sql.raw(quoteIdent(name))} AS (${query})`;\n });\n // One recursive member makes the whole list `WITH RECURSIVE`.\n return definitions.some((definition) => definition.recursive)\n ? sql`WITH RECURSIVE ${sql.join(defs, \", \")}`\n : 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 opens: (query: Sql): boolean =>\n Sql.peek(query).strings[0]!.trimStart().startsWith(\"WITH\"),\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/** `INSERT … ON CONFLICT (key) DO NOTHING | UPDATE SET …`: PostgreSQL and SQLite. */\nexport const createInsertAbsent =\n (\n quoteIdent: IdentifierQuoter\n ): DatabaseAdapter[\"mutations\"][\"insertAbsent\"] =>\n (table, columns, rows, key, sets, unless) => [\n sql`${createInsertStatement(quoteIdent)(table, columns, rows)} ON CONFLICT (${sql.join(\n key.map((column) => sql.raw(quoteIdent(column))),\n \", \"\n )}) DO ${sets ? sql`UPDATE SET ${sets}` : sql`NOTHING`}${\n unless ? sql` WHERE NOT (${unless})` : sql.empty\n }`,\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\" | \"onConflictNothing\" | \"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 onConflictNothing: (): Sql => sql`NOTHING`,\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":"sIAyCA,MAAa,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,GAGI,4BAAkD,CAC7D,MAAQ,GAAoB,CAAG,GAAG,IAClC,SAAiBA,EAAI,IAAI,OAAO,CAChC,KAAO,GACD,EAAO,SAAW,EAAUA,EAAI,IAAI,KAAK,CACtC,CAAG,I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