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,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { d as SchemaDocument } from "../document-
|
|
1
|
+
import { p as AnyDriver } from "../database-adapter-D62c-uC6.mjs";
|
|
2
|
+
import { d as SchemaDocument } from "../document-o5Bd5ZoJ.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/migrations/introspect/types.d.ts
|
|
5
5
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"../introspect-
|
|
1
|
+
import{t as e}from"../introspect-C4T5gt9O.mjs";export{e as introspectSchema};
|
package/dist/schema/json.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as IndexDocument, c as RelationFieldDocument, d as SchemaDocument, f as VariantJunctionDocument, i as GenerateDocument, l as SCHEMA_DOCUMENT_VERSION, n as EnumDocument, o as JunctionDocument, r as FieldDocument, s as ModelDocument, t as CompoundKeyDocument, u as ScalarFieldDocument } from "../document-
|
|
1
|
+
import { Zr as Schema, mt as VibORMConfig, pt as VibORMClient } from "../database-adapter-D62c-uC6.mjs";
|
|
2
|
+
import { a as IndexDocument, c as RelationFieldDocument, d as SchemaDocument, f as VariantJunctionDocument, i as GenerateDocument, l as SCHEMA_DOCUMENT_VERSION, n as EnumDocument, o as JunctionDocument, r as FieldDocument, s as ModelDocument, t as CompoundKeyDocument, u as ScalarFieldDocument } from "../document-o5Bd5ZoJ.mjs";
|
|
3
3
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
4
4
|
|
|
5
5
|
//#region src/schema/json/interpret.d.ts
|
package/dist/schema/json.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e,n as t,r as n,t as r}from"../json-
|
|
1
|
+
import{i as e,n as t,r as n,t as r}from"../json-CHdgejCt.mjs";export{e as SCHEMA_DOCUMENT_VERSION,r as attachFieldSchemas,t as parseSchema,n as serializeSchema};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{f as t,m as n,t as r}from"./validation--qS7OPmg.mjs";import{o as i}from"./sql-
|
|
2
|
-
//# sourceMappingURL=schema-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{f as t,m as n,t as r}from"./validation--qS7OPmg.mjs";import{o as i}from"./sql-BGjAsoBE.mjs";import{o as a}from"./value-guards-CBuxSC66.mjs";import{tt as o}from"./native-types-DspZ0Z5E.mjs";import{c as s,h as c,l,n as u}from"./validator-CDYlO9HV.mjs";import{t as d}from"./hydration-D7U8HACL.mjs";import{d as f,r as p,t as m}from"./validation-D0LG854o.mjs";var InsertValue=class{},Stored=class extends InsertValue{compute(){throw Error(`Stored is no value: the update leaves its field out`)}},JoinedValue=class extends InsertValue{};const h=new WeakMap,nameOf=e=>e[`~`].names.ts,tableOf=e=>e[`~`].names.sql,scalarsOf=e=>e[`~`].state.scalars,listed=e=>i.join(e,`, `),same=(e,t)=>e instanceof Date||t instanceof Date?e!=null&&t!=null&&+new Date(e)==+new Date(t):String(e)===String(t);function unsupported(e){throw new n(e)}function engineFault(e){throw new t(e)}function parseValidated(e,t,n,i,a){let s=m(e,t);if(s.issues){let e=i?[i]:[];throw new r(n,s.issues.map(t=>({path:[...e,...t.path?.map(String)??[]].join(`.`)||`root`,message:t.message})),{cause:o(s),meta:{model:nameOf(a)}})}return s.value}function linkMembers(e){let t=new Set,n=[];for(let r of[e.sourceSide,e.targetSide])for(let e of r.members)t.has(e.junctionField)||(t.add(e.junctionField),n.push({side:r,pair:e}));return n}function linkJudgement(e){if(e.kind===`reference`&&e.owner===`source`)return;let t=e.scope.edge,n=e.kind===`reference`&&t.kind===`foreignKey`?e.pairs.map(e=>e.target):[],own=t=>t.source===e.source&&t.field===e.name,r=t.kind===`foreignKey`||t.kind===`junction`?t.endpoints.find(e=>!own(e)):own(t.carrier)?e.scope.member?.inverse:t.carrier;return r&&n.push(r.field),{kind:`update`,writes:n}}function bindMembership(e,t,n,r){return e.membership(t,n,r)}function buildMembershipView(e,t,n,r){let i=e.index.get(t).get(n),a=i.edge,o=e.clearability(i),s=t[`~`].state.relations[n][`~`].state.cardinality===`many`,arm=e=>{let c=i.member??e.find(e=>e.variant===r),l=i.member===void 0;return{member:c,direct:l,base:{scope:{edge:a,member:c},clearability:o,name:l?`${n}.${c.variant}`:n,source:t,many:s}}};if(a.kind===`variantRowCarrier`){let{member:e,direct:t,base:n}=arm(a.members);return{...n,target:t?e.targetModel:a.carrier.source,kind:`reference`,owner:t?`source`:`target`,pairs:[{source:t?a.storage.idColumn.name:e.referencedField,target:t?e.referencedField:a.storage.idColumn.name}],discriminator:{side:t?`source`:`target`,field:a.storage.typeColumn.name,value:e.entry.storedValue}}}if(a.kind===`variantJunctionCarrier`){let{member:e,direct:t,base:n}=arm(a.members);return{...n,target:t?e.topology.target.model:e.topology.source.model,kind:`junction`,table:e.topology.table,sourceSide:t?e.topology.source:e.topology.target,targetSide:t?e.topology.target:e.topology.source,uniqueSide:e.uniqueTarget?t?`target`:`source`:void 0}}let c=a.endpoints[0],l=c.source===t&&c.field===n?a.endpoints[1]:c,u={scope:i,clearability:o,name:n,source:t,target:l.source,many:s};if(a.kind===`foreignKey`){let e=a.owner.source===t&&a.owner.field===n;return{...u,kind:`reference`,owner:e?`source`:`target`,reference:a.reference,pairs:a.reference.members.map(t=>({source:e?t.foreignField:t.referencedField,target:e?t.referencedField:t.foreignField}))}}let d=a.topology,f=l===a.endpoints[1];return{...u,kind:`junction`,table:d.table,sourceSide:f?d.source:d.target,targetSide:f?d.target:d.source,declared:d.declared}}function hopFieldsOf(e){return e.kind===`reference`?sideFields(e,`source`):e.sourceSide.members.map(e=>e.referencedField)}const sideFields=(e,t)=>[...e.discriminator?.side===t?[e.discriminator.field]:[],...e.pairs.map(e=>e[t])];function physicalField(e,t,n){return e.physicalField(t,n)}function carrierColumns(e,t){let n=[];for(let{edge:r,member:i}of e.index.get(t).values())r.kind===`variantRowCarrier`&&!i&&n.push(r.storage.typeColumn,r.storage.idColumn);return n}function buildPhysicalFieldView(e,t,n){let r=scalarsOf(t)[n],i=r?{name:t[`~`].getFieldName(n).sql,scalar:r,nullable:r[`~`].state.nullable===!0}:carrierColumns(e,t).find(e=>e.name===n),{state:a,nativeType:o}=i.scalar[`~`];return{...i,state:a,nativeType:o}}function buildStoredFieldsView(e,t){return[...t[`~`].scalarFieldNames,...carrierColumns(e,t).map(e=>e.name)]}const g=new Set([`findMany`,`findUnique`,`findFirst`,`count`,`exist`,`aggregate`,`groupBy`]);function isReadOperation(e){return g.has(e)}const _=[`multiply`,`divide`],v=[`set`,`increment`,`decrement`,`multiply`,`divide`];function record(e){return e}function entries(e){return Array.isArray(e)?e:[record(e)]}function memo(e,t,n){let r=e.get(t);return r===void 0&&(r=n(),e.set(t,r)),r}const createQueryViews=()=>({leaves:new WeakMap,defaultProjections:new WeakMap,defaultRelations:new WeakMap}),y=[];var EngineSchema=class{index;registry;#e=new WeakMap;#t=new WeakMap;#n=new WeakMap;#r=new WeakMap;#i=new WeakMap;#a=new WeakMap;schema;constructor(e,t){if(this.schema=e,t){this.index=t.index,this.registry=t.registry;return}d(e),this.index=u(e),this.registry=p(e,this.index)}admit(e,t,n){let r=this.#o(e,t,n);if(t===`update`||t===`updateMany`){let t=this.keyPortabilityRefusal(e,r.data);if(t)throw t}return r}#o(e,t,n){let r=this.registry.getModelSchemas(e).args[t],i={},o=[],s=parseValidated(r,(t===`update`||t===`updateMany`)&&a(n)&&a(n.data)?{...n,data:Object.fromEntries(Object.entries(n.data).filter(([e,t])=>t instanceof InsertValue?(t instanceof Stored?o.push(e):i[e]=t,!1):!0).sort(([t],[n])=>{let isVariant=t=>e[`~`].state.relations[t]?.[`~`].state.target.kind===`variants`;return Number(isVariant(t))-Number(isVariant(n))}))}:n,t,``,e);if(Object.keys(i).length===0&&o.length===0)return s;let c={...s.data,...i};for(let e of o)delete c[e];return{...s,data:c}}keyPortabilityRefusal(e,t){if(a(t))for(let r of this.keys(e)){let i=t[r];if(!a(i))continue;let o=v.filter(e=>i[e]!==void 0);if(o.length!==1)return new n(`Primary key field '${r}' accepts exactly one update operation; received ${o.join(`, `)||`none`}.`);let s=o[0];if(s===`set`)continue;let c=scalarsOf(e)[r]?.[`~`].state.type;if(c===`number`||c===`decimal`&&_.includes(s))return new n(`Arithmetic updates are not portable for ${c} primary key field '${r}'. Use an explicit set value.`);if(i.divide===0||i.divide===0n)return new n(`Cannot divide primary key field '${r}' by zero.`)}}createValues(e,t){let n=this.registry.getModelSchemas(e).scalars,r={};for(let[i,a]of Object.entries(t))r[i]=parseValidated(n[i].create,a,`create`,i,e);return r}linkFields(e,t){return memo(this.#e,e,()=>{let n=scalarsOf(e),r=Object.keys(n).filter(n=>!t.includes(this.physicalField(e,n).name));return{required:r.filter(e=>n[e][`~`].state.optional!==!0),defaults:r.filter(t=>n[t][`~`].state.hasDefault===!0&&this.createValues(e,{[t]:void 0})[t]!==void 0)}})}update(e,t){return record(parseValidated(this.registry.getModelSchemas(e).core.update,t,`updateMany`,`data`,e))}keys(e){return c(e).rowKey?.fields??y}identity(e,t){let n={};for(let r of this.keys(e))n[r]=t[r];return n}membership(e,t,n){return memo(memo(memo(this.#t,e,()=>new Map),t,()=>new Map),n,()=>buildMembershipView(this,e,t,n))}restrictingSlots(e){return memo(this.#a,e,()=>{let t=[];for(let[n,r]of this.index.get(e)??[]){let i=r.edge;if(i.kind!==`foreignKey`&&i.kind!==`junction`)continue;let a=this.membership(e,n),o=a.kind===`junction`?l(a.sourceSide):i.kind===`foreignKey`&&a.owner===`target`?s(i):void 0;(o===`restrict`||o===`noAction`)&&t.push(n)}return t})}clearability(e){return memo(this.#i,e,()=>{let t=f(e);return t.kind===`columns`&&t.fields,t})}physicalField(e,t){let n=this.#n.get(e);n||(n=new Map,this.#n.set(e,n));let r=n.get(t);return r||(r=buildPhysicalFieldView(this,e,t),n.set(t,r)),r}#s=new WeakMap;queryViews(e){return memo(this.#s,e,createQueryViews)}storedFields(e){return memo(this.#r,e,()=>buildStoredFieldsView(this,e))}scalars(e,t){let n={};for(let r of e[`~`].scalarFieldNames){let e=t[r];e!==void 0&&(n[r]=e)}return n}};export{h as S,tableOf as _,record as a,JoinedValue as b,linkJudgement as c,sideFields as d,engineFault as f,scalarsOf as g,same as h,memo as i,linkMembers as l,nameOf as m,entries as n,bindMembership as o,listed as p,isReadOperation as r,hopFieldsOf as s,EngineSchema as t,physicalField as u,unsupported as v,Stored as x,InsertValue as y};
|
|
2
|
+
//# sourceMappingURL=schema-MB-pPNTO.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-MB-pPNTO.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 { GroupByMember } from \"@validation/model/args/time-step\";\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 {\n Leaf,\n PreparedProjection,\n PreparedProjectionField,\n Shape,\n} 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?: readonly GroupByMember[];\n /** A grouped read's IANA zone for its time steps (`time-step.ts`). */\n timeZone?: 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 * Every member is 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` (an\n * operation-level `omit` reaches the projection owner desugared into a\n * `select`, which shares it only where it names exactly those scalars); a\n * relation read at its target's default projection is its edge, an empty\n * window and that projection. Nothing admitted and nothing a provider\n * answered is stored (rule 5): the sharing is keyed by schema objects alone.\n *\n * The 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 * A relation of a model read at its target's default projection (`rel:\n * true`, or a node naming every projectable scalar and nothing else) on a\n * read under no row domain: its edge, an empty window and the target's\n * default projection, all facts of the schema and the dialect.\n */\n readonly defaultRelations: WeakMap<AnyModel, Map<string, DefaultRelation>>;\n};\n\n/** A relation member at its default projection, and its decoded shape. */\nexport type DefaultRelation = {\n readonly field: PreparedProjectionField;\n readonly shape: Shape;\n};\n\nconst createQueryViews = (): QueryViews => ({\n leaves: new WeakMap(),\n defaultProjections: new WeakMap(),\n defaultRelations: 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,KAAK,MAAM,QAElD,OAAU,GAA+BA,EAAI,KAAK,EAAO,KAAK,CAK9D,MAAQ,EAAY,IAC/B,aAAa,MAAQ,aAAa,KAC9B,GAAK,MAAQ,GAAK,MAAQ,CAAC,IAAI,KAAK,EAAU,EAAK,CAAC,IAAI,KAAK,EAAU,CACvE,OAAO,EAAE,GAAK,OAAO,EAAE,CAG7B,SAAgB,YAAY,EAAwB,CAClD,MAAM,IAAI,EAA0B,EAAQ,CAI9C,SAAgB,YAAY,EAAwB,CAClD,MAAM,IAAI,EAAiB,EAAQ,CCMrC,SAAgB,eACd,EACA,EACA,EACA,EACA,EACgB,CAChB,IAAM,EAAS,EAAM,EAAQ,EAAM,CACnC,GAAI,EAAO,OAAQ,C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,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,2 +1,2 @@
|
|
|
1
|
-
import{E as e,T as t,t as n}from"./scalar-
|
|
2
|
-
//# sourceMappingURL=schema-
|
|
1
|
+
import{E as e,T as t,t as n}from"./scalar-B9WizsvR.mjs";import{_ as r,a as i,f as a,g as o,h as s,i as c,m as l,n as u,o as d,p as f,r as p,s as m,t as h,u as g}from"./to-many-DiP6cOSQ.mjs";const _={model:t,string:n,boolean:s,int:d,number:c,decimal:g,bigInt:r,dateTime:f,date:l,time:a,json:i,blob:o,enum:m,point:p,vector:u,toOne:e,toMany:h};export{_ as t};
|
|
2
|
+
//# sourceMappingURL=schema-TthAXPVP.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-
|
|
1
|
+
{"version":3,"file":"schema-TthAXPVP.mjs","names":[],"sources":["../src/schema/index.ts"],"sourcesContent":["// Schema Builder Entry Point\n// Main API for defining models, scalars, and relations\n\nimport { model } from \"./model\";\nimport { toMany, toOne } from \"./relation\";\nimport {\n bigInt,\n blob,\n boolean,\n date,\n dateTime,\n decimal,\n enumScalar,\n int,\n json,\n number,\n point,\n string,\n time,\n vector,\n} from \"./scalars\";\n\n// =============================================================================\n// SCHEMA BUILDER API\n// =============================================================================\n\n/**\n * Main schema builder object\n * Use this to define models, scalars, and relations\n *\n * A relation states two independent facts: `s.toOne` / `s.toMany` states the\n * SLOT CARDINALITY, and the argument states the TARGET DOMAIN — one model\n * (`() => model`) or named variants (`{ post: () => post, video: () => video }`).\n * Everything else about an edge is derived from the full schema graph.\n *\n * @example\n * ```ts\n * import { s } from \"viborm\";\n *\n * const user = s.model({\n * id: s.string().id().ulid(),\n * name: s.string(),\n * email: s.string().unique(),\n * posts: s.toMany(() => post),\n * profile: s.toOne(() => profile),\n * }).map(\"users\");\n *\n * const post = s.model({\n * id: s.string().id().ulid(),\n * authorId: s.string(),\n * author: s.toOne(() => user).fields(\"authorId\").references(\"id\"),\n * }).map(\"posts\");\n * ```\n */\nexport const s = {\n // Model factory\n model,\n\n // Scalar factories\n string,\n boolean,\n /**\n * @description Creates a new int scalar.\n * @param nativeType - The native type to use for the scalar.\n * @returns A new int scalar.\n */\n int,\n number,\n decimal,\n bigInt,\n dateTime,\n date,\n time,\n json,\n blob,\n enum: enumScalar,\n point,\n vector,\n\n // Relation factories: slot cardinality here, target domain in the argument\n toOne,\n toMany,\n};\n\n// =============================================================================\n// RE-EXPORTS\n// =============================================================================\n\n// Hydration exports (excluding Schema type which conflicts with validation)\nexport {\n getFieldSqlName,\n getModelSqlName,\n hydrateSchemaNames,\n isSchemaHydrated,\n} from \"./hydration\";\n// JSON null sentinels — the two nulls of a nullable JSON column, told apart\nexport {\n type AnyJsonNullSentinel,\n AnyNull,\n DbNull,\n isJsonNullSentinel,\n JsonNull,\n type JsonNullKind,\n JsonNullSentinel,\n} from \"./json-null\";\nexport * from \"./model\";\nexport { Model } from \"./model\";\nexport * from \"./relation\";\n// Types\nexport type { NumericScalar, Scalar } from \"./scalars\";\n// Export all from submodules\nexport * from \"./scalars\";\n// Classes for advanced usage\nexport {\n BigIntScalar,\n BlobScalar,\n BooleanScalar,\n DateScalar,\n DateTimeScalar,\n EnumScalar,\n IntScalar,\n JsonScalar,\n NumberScalar,\n PointScalar,\n StringScalar,\n TimeScalar,\n VectorScalar,\n} from \"./scalars\";\nexport * as TYPES from \"./scalars/native-types\";\nexport * from \"./validation\";\n\n// =============================================================================\n// TYPE INFERENCE EXPORTS\n// =============================================================================\n\n// Re-export core types from common\nexport type {\n AutoGenerate,\n AutoGenerateType,\n InferBaseType,\n InferCreateType,\n ScalarState as ScalarStateType,\n} from \"./scalars/common\";\n"],"mappings":"8LAsDA,MAAa,EAAI,CAEf,QAGA,SACA,UAMA,MACA,SACA,UACA,SACA,WACA,OACA,OACA,OACA,OACA,KAAM,EACN,QACA,SAGA,QACA,SACD"}
|
|
@@ -0,0 +1,6 @@
|
|
|
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-B9WizsvR.mjs";import{n as o}from"./validator-CDYlO9HV.mjs";import{at as s,et as c,nt as l,rt as u,st as d}from"./query-Cdy8E2jM.mjs";import{t as f}from"./hydration-D7U8HACL.mjs";import{f as p,i as m,r as h}from"./validation-D0LG854o.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===u)return{kind:`empty`};if(t===l)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===s)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 c=d(t);if(c){let e=n.aggregates.get(t);return e?{kind:`aggregate`,name:c,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 periodType(e){return e[`~`].state.nullable?unionOf(atom(`string`),y):atom(`string`)}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:n.periods?.has(o.key)?periodType(o.scalar):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=c(e,r,i,a);if(!o)throw new t(`Operation '${n}' has no renderable result shape.`);let s=[],l=o.carrier===`existence`?atom(`boolean`):o.carrier===`count`?countType(o):rowType(e,o,s);return n===`findMany`||n===`groupBy`||r===`createManyAndReturn`||r===`updateManyAndReturn`||r===`deleteManyAndReturn`?l=arrayOf(l):(n===`findFirst`||n===`findUnique`)&&(l=unionOf(l,y)),s.length===0?renderType(l,0):[{name:`VibORMOperationResult`,type:l},...s].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):p(a)?unionOf(t,y):t}let s=schemaModelReference(settledModel(r));return o.cardinality===`many`?arrayOf(s):p(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 m(e).proxy[t].args[r(i)]}function validateOperationPayload(e,t,n,i){let a=requireIdentifier(t,`model`),o=publicOperationOrThrow(a,requireIdentifier(n,`operation`));return m(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=h(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-wMVZowIF.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-introspection-wMVZowIF.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\n/** A period's first day, `YYYY-MM-DD`; `null` too where the column is nullable. */\nfunction periodType(scalar: Scalar): TypeNode {\n return scalar[\"~\"].state.nullable\n ? unionOf(atom(\"string\"), NULL_TYPE)\n : atom(\"string\");\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({\n name: column.key,\n type: shape.periods?.has(column.key)\n ? periodType(column.scalar)\n : scalarType(column.scalar),\n });\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":"+fAkCA,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,SAAQ,CAElD,GAAI,IAAQ,EACV,MAAO,CAAE,KAAM,iBAAkB,UAAW,EAAM,eAAgB,CAGpE,IAAM,EAAY,EAAM,KAAK,MAAM,UAC7B,EAAoC,OAAO,OAAO,EAAW,EAAI,CACnE,EAAU,GACV,IAAA,GACJ,GAAI,EAAU,CACZ,GAAI,EAAuB,EAAS,KAAK,MAAM,CAAE,CAC/C,IAAMA,EAAW,EAA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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"}
|
package/dist/schema.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Ai as BooleanScalar, At as AutoGenerate, Di as TimeScalar, Dt as VariantToOneRelation, Ea as BlobSchema, Ei as ModelToManyRelation, Et as VariantToManyRelation, Fi as VectorSchema, Go as PG, Ha as RelationCardinality, Ho as NativeType, Ii as StringSchema, It as UpdateState$1, Ji as InitialModelState, Ko as SQLITE, Mt as GeneratorDefaultBrand, Nt as InitialScalarState, Oa as BigIntSchema, Oi as DateTimeScalar, Ot as Scalar, Pt as ScalarState, Qi as UpdateState, Ra as AnyRelation, Ri as PointSchema, Ti as ReferencesStage, Tt as ScalarKeys, Ua as RelationSlot, Va as ReferentialAction, Vo as MYSQL, Wi as AnyModel, Wo as NativeTypeMap, Xi as ModelInternal, Yi as Model, Zi as ModelState, aa as JsonSchema, an as VectorScalar, ba as DecimalSchema, cn as NumberScalar, da as IsoTimeSchema, dn as EnumScalar, fa as IsoTimestampSchema, fn as DecimalScalar, ha as GeoPoint, in as NumericScalar, ji as BlobScalar, ki as DateScalar, kt as BigIntScalar, ln as JsonScalar, na as NumberSchema, on as StringScalar, pn as s, sn as PointScalar, ta as IntegerSchema, ua as IsoDateSchema, un as IntScalar, wa as BooleanSchema, wi as ModelToOneRelation, wt as ModelShape, xa as DecimalDescriptor, ya as EnumSchema, za as Getter } from "./database-adapter-D62c-uC6.mjs";
|
|
2
2
|
export { type AnyModel, type AnyRelation, type AutoGenerate, type BigIntScalar, type BigIntSchema, type BlobScalar, type BlobSchema, type BooleanScalar, type BooleanSchema, type DateScalar, type DateTimeScalar, type DecimalDescriptor, type DecimalScalar, type DecimalSchema, type EnumScalar, type EnumSchema, type GeneratorDefaultBrand, type GeoPoint, type Getter, type InitialModelState, type InitialScalarState, type IntScalar, type IntegerSchema, type IsoDateSchema, type IsoTimeSchema, type IsoTimestampSchema, type JsonScalar, type JsonSchema as JsonValueSchema, MYSQL, type Model, type ModelInternal, type ModelShape, type ModelState, type ModelToManyRelation, type ModelToOneRelation, type UpdateState as ModelUpdateState, type NativeType, type NativeTypeMap, type NumberScalar, type NumberSchema, type NumericScalar, PG, type PointScalar, type PointSchema, type ReferencesStage, type ReferentialAction, type RelationCardinality, type RelationSlot, SQLITE, type Scalar, type ScalarKeys, type ScalarState, type UpdateState$1 as ScalarUpdateState, type StringScalar, type StringSchema, type TimeScalar, type VariantToManyRelation, type VariantToOneRelation, type VectorScalar, type VectorSchema, s };
|
package/dist/schema.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e,r as t,t as n}from"./native-types-
|
|
1
|
+
import{i as e,r as t,t as n}from"./native-types-DspZ0Z5E.mjs";import{t as r}from"./schema-TthAXPVP.mjs";export{n as MYSQL,t as PG,e as SQLITE,r as s};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t,t as n}from"./sql-BGjAsoBE.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 r={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 clause=(e,t,n)=>{e.strings.push(t),e.values.push(n)},begun=(e,t,n,r)=>{let i=[e,t,``,``,``,``,``,``],a=[n,r,n,n,n,n];return i.length=2,a.length=2,{strings:i,values:a}},closed=(e,t=``)=>(e.strings.push(t),new n(e.strings,e.values)),assembleSelectQuery=(e,t,n)=>{let r=n?{strings:[`SELECT DISTINCT ON (`,`) `,` FROM `],values:[n,e.columns,e.from]}:begun(`SELECT `,` FROM `,e.columns,e.from);return appendFilterParts(r,e),e.orderBy&&clause(r,` ORDER BY `,e.orderBy),appendLimitOffset(r,e.limit,e.offset,t.noLimitValue),closed(r,t.forUpdate===`append`&&e.forUpdate?` FOR UPDATE`:``)},appendFilterParts=(e,t)=>{if(t.joins)for(let n of t.joins)clause(e,` `,n);t.where&&clause(e,` WHERE `,t.where),t.groupBy&&clause(e,` GROUP BY `,t.groupBy),t.having&&clause(e,` HAVING `,t.having)},appendLimitOffset=(e,t,n,r)=>{t?clause(e,` LIMIT `,t):n&&r&&clause(e,` LIMIT `,r),n&&clause(e,` OFFSET `,n)},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={strings:[`SELECT `,` FROM `],values:[t.join(s,`, `),e.from]};appendFilterParts(c,e);let l=closed(c),u=e.distinctColumnAliases.map(r),d={strings:[``],values:[t`SELECT ${t.join(u,`, `)} FROM (${l}) AS ${r(`_distinct_subquery`)} WHERE ${r(`_rn`)} = 1`]};return o&&clause(d,` ORDER BY `,o.orderBy),appendLimitOffset(d,e.limit,e.offset,i),closed(d)};export{geoPolygonJson as a,logicalDecimalDivide as c,scaleUnitSql as d,signedNumerator as f,r 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-SuVxJjps.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"select-assembly-SuVxJjps.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 { TimeStep } from \"@validation/model/args/time-step\";\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/**\n * The column a time-step period is taken of: a calendar date or a date and\n * time, whether it declares a zone, and its native type, which may state the\n * zone instead.\n */\nexport interface PeriodSource {\n readonly date: boolean;\n readonly withTimezone: boolean;\n readonly nativeType: NativeTypeDeclaration | undefined;\n}\n\n/** A `groupBy` time step's period: computed once, then spelled. */\nexport interface PeriodSql {\n /**\n * The first day of the `step` period holding `column`, as a date: what a\n * grouped read groups and orders. A column that stores an instant is read\n * as wall time in `zone` (an admitted IANA name); a date, or a date and\n * time with no zone, as written.\n */\n readonly of: (\n column: Sql,\n step: TimeStep,\n source: PeriodSource,\n zone: string\n ) => Sql;\n /**\n * That date as the text the engine publishes from, `YYYY-MM-DD AD` or\n * `YYYY-MM-DD BC`, whatever the session's date style or the driver.\n */\n readonly text: (period: Sql) => Sql;\n}\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 /**\n * The periods of a `by` member grouped by a time step. Absence means this\n * adapter groups by no time step, and the engine refuses such a call before\n * any statement is sent.\n */\n readonly period?: PeriodSql;\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 { 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\n/**\n * A statement's clauses, each word before its operand, as ONE fragment: a\n * fragment per clause and their join were up to seven more for every SELECT\n * the engine assembles, each made here and walked again where the statement\n * is rendered (2 % to 4 % of a read's client CPU).\n */\ninterface Clauses {\n readonly strings: string[];\n readonly values: Sql[];\n}\n\nconst clause = (into: Clauses, word: string, operand: Sql): void => {\n into.strings.push(word);\n into.values.push(operand);\n};\n\n/**\n * A SELECT's clauses, begun with room for the ones it takes next. A list of\n * two members that takes a third by `push` is copied into a store of\n * nineteen: 240 bytes more for every SELECT the engine assembles, seven of\n * them in a read of two relation levels. The lists are written longer and cut\n * back, which keeps their store, so a WHERE, an ORDER BY, a LIMIT and an\n * OFFSET land in place.\n */\nconst begun = (first: string, second: string, a: Sql, b: Sql): Clauses => {\n const strings = [first, second, \"\", \"\", \"\", \"\", \"\", \"\"];\n const values = [a, b, a, a, a, a];\n strings.length = 2;\n values.length = 2;\n return { strings, values };\n};\n\nconst closed = (clauses: Clauses, last = \"\"): Sql => {\n clauses.strings.push(last);\n return new Sql(clauses.strings, clauses.values);\n};\n\n/** `distinctOn`: the columns of PostgreSQL's `DISTINCT ON`, where the page is one. */\nexport const assembleSelectQuery = (\n parts: QueryParts,\n options: SelectAssemblyOptions,\n distinctOn?: Sql\n): Sql => {\n const query: Clauses = distinctOn\n ? {\n strings: [\"SELECT DISTINCT ON (\", \") \", \" FROM \"],\n values: [distinctOn, parts.columns, parts.from],\n }\n : begun(\"SELECT \", \" FROM \", parts.columns, parts.from);\n\n appendFilterParts(query, parts);\n\n if (parts.orderBy) {\n clause(query, \" ORDER BY \", parts.orderBy);\n }\n\n appendLimitOffset(query, parts.limit, parts.offset, options.noLimitValue);\n\n return closed(\n query,\n options.forUpdate === \"append\" && parts.forUpdate ? \" FOR UPDATE\" : \"\"\n );\n};\n\n/** Joins, WHERE, GROUP BY and HAVING: shared by the plain and the emulated-DISTINCT select. */\nconst appendFilterParts = (into: Clauses, parts: QueryParts): void => {\n if (parts.joins) {\n for (const join of parts.joins) clause(into, \" \", join);\n }\n\n if (parts.where) {\n clause(into, \" WHERE \", parts.where);\n }\n\n if (parts.groupBy) {\n clause(into, \" GROUP BY \", parts.groupBy);\n }\n\n if (parts.having) {\n clause(into, \" HAVING \", parts.having);\n }\n};\n\nconst appendLimitOffset = (\n into: Clauses,\n limit: Sql | undefined,\n offset: Sql | undefined,\n noLimitValue: Sql | undefined\n): void => {\n if (limit) {\n clause(into, \" LIMIT \", limit);\n } else if (offset && noLimitValue) {\n // Dialects like MySQL/SQLite have no bare OFFSET; emit their \"no limit\" sentinel\n clause(into, \" LIMIT \", noLimitValue);\n }\n\n if (offset) {\n clause(into, \" 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 inner: Clauses = {\n strings: [\"SELECT \", \" FROM \"],\n values: [sql.join(selectColumns, \", \"), parts.from],\n };\n\n appendFilterParts(inner, parts);\n\n const innerQuery = closed(inner);\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 outer: Clauses = {\n strings: [\"\"],\n values: [\n sql`SELECT ${sql.join(aliasColumns, \", \")} FROM (${innerQuery}) AS ${escapeIdentifier(\"_distinct_subquery\")} WHERE ${escapeIdentifier(\"_rn\")} = 1`,\n ],\n };\n\n if (order) {\n clause(outer, \" ORDER BY \", order.orderBy);\n }\n\n appendLimitOffset(outer, parts.limit, parts.offset, noLimitValue);\n\n return closed(outer);\n};\n"],"mappings":"uFA0BA,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,SAA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