viborm 1.14.2 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-namespace-DaRiTIIf.mjs → adapter-namespace-DD-BQ2Wk.mjs} +2 -2
- package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DD-BQ2Wk.mjs.map} +1 -1
- package/dist/adapters.d.mts +15 -3
- package/dist/adapters.mjs +1 -1
- package/dist/{args-764KdWMr.mjs → args-BvA37zBZ.mjs} +2 -2
- package/dist/{args-764KdWMr.mjs.map → args-BvA37zBZ.mjs.map} +1 -1
- package/dist/{batch-refs-C-gx7A4-.mjs → batch-refs-BmEpMmjI.mjs} +2 -2
- package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-BmEpMmjI.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +2 -2
- package/dist/cache.mjs +1 -1
- package/dist/{call-Cz8XUmrl.mjs → call-BWFI7-vU.mjs} +2 -2
- package/dist/{call-Cz8XUmrl.mjs.map → call-BWFI7-vU.mjs.map} +1 -1
- package/dist/cli.mjs +2 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/client-CVCC-D1j.mjs +2 -0
- package/dist/client-CVCC-D1j.mjs.map +1 -0
- package/dist/{client-CRxfhw2y.d.mts → client-DZ39sYy2.d.mts} +2 -2
- package/dist/{client-y7TV0PRZ.mjs → client-DtPTegtA.mjs} +2 -2
- package/dist/{client-y7TV0PRZ.mjs.map → client-DtPTegtA.mjs.map} +1 -1
- package/dist/client.d.mts +3 -3
- package/dist/client.mjs +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/{confine-DqFBTUw6.mjs → confine-BGGv2du0.mjs} +2 -2
- package/dist/{confine-DqFBTUw6.mjs.map → confine-BGGv2du0.mjs.map} +1 -1
- package/dist/{coordination-6qZHx_kl.mjs → coordination-BY6Np3xV.mjs} +2 -2
- package/dist/{coordination-6qZHx_kl.mjs.map → coordination-BY6Np3xV.mjs.map} +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-D62c-uC6.d.mts} +604 -473
- package/dist/{datetime-physical-codec-Dj-APo9f.mjs → datetime-physical-codec-BS2T81sD.mjs} +2 -2
- package/dist/{datetime-physical-codec-Dj-APo9f.mjs.map → datetime-physical-codec-BS2T81sD.mjs.map} +1 -1
- package/dist/{defaults-DwOHWI_M.mjs → defaults-CrtGVdEC.mjs} +2 -2
- package/dist/{defaults-DwOHWI_M.mjs.map → defaults-CrtGVdEC.mjs.map} +1 -1
- package/dist/{document-BVTQ-cF-.d.mts → document-o5Bd5ZoJ.d.mts} +1 -1
- package/dist/{driver-BBEmaJZy.d.mts → driver-0cdCF_KD.d.mts} +1 -1
- package/dist/{driver-BGVcgnIX.mjs → driver-D1grnHEr.mjs} +2 -2
- package/dist/{driver-BGVcgnIX.mjs.map → driver-D1grnHEr.mjs.map} +1 -1
- package/dist/{driver-BIXhOH2_.mjs → driver-Df88hu4U.mjs} +2 -2
- package/dist/{driver-BIXhOH2_.mjs.map → driver-Df88hu4U.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/durable-object.d.mts +1 -1
- package/dist/durable-object.mjs +1 -1
- package/dist/error-mapping-DIRlrmDK.mjs +2 -0
- package/dist/error-mapping-DIRlrmDK.mjs.map +1 -0
- package/dist/every-BHEmfLOW.mjs +2 -0
- package/dist/{every-tOgQmaIE.mjs.map → every-BHEmfLOW.mjs.map} +1 -1
- package/dist/execution-context-VMQm-9CH.mjs +2 -0
- package/dist/execution-context-VMQm-9CH.mjs.map +1 -0
- package/dist/{exports-COCJ8f2f.d.mts → exports-Bzvtum3F.d.mts} +1 -1
- package/dist/geo-area-codec-BDvW7IH-.mjs +2 -0
- package/dist/{geo-area-codec-mHrM3b9A.mjs.map → geo-area-codec-BDvW7IH-.mjs.map} +1 -1
- package/dist/{hydration-A3zffFWP.mjs → hydration-D7U8HACL.mjs} +2 -2
- package/dist/{hydration-A3zffFWP.mjs.map → hydration-D7U8HACL.mjs.map} +1 -1
- package/dist/{identifier-conversion-DHYPTgzr.mjs → identifier-conversion-Ci_iaJ0b.mjs} +2 -2
- package/dist/{identifier-conversion-DHYPTgzr.mjs.map → identifier-conversion-Ci_iaJ0b.mjs.map} +1 -1
- package/dist/identifiers-BTCfD5ic.mjs +2 -0
- package/dist/identifiers-BTCfD5ic.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{introspect-Bm6xnXcG.mjs → introspect-C4T5gt9O.mjs} +2 -2
- package/dist/{introspect-Bm6xnXcG.mjs.map → introspect-C4T5gt9O.mjs.map} +1 -1
- package/dist/{json-DgMc8-GU.mjs → json-CHdgejCt.mjs} +2 -2
- package/dist/{json-DgMc8-GU.mjs.map → json-CHdgejCt.mjs.map} +1 -1
- package/dist/judge-words-DpwxOfre.mjs +2 -0
- package/dist/judge-words-DpwxOfre.mjs.map +1 -0
- package/dist/{key-hxFFCKed.mjs → key-B3xgpu0M.mjs} +2 -2
- package/dist/{key-hxFFCKed.mjs.map → key-B3xgpu0M.mjs.map} +1 -1
- package/dist/{keys-BQxM4c_a.mjs → keys-1Z6WKrnE.mjs} +1 -1
- package/dist/{keys-BQxM4c_a.mjs.map → keys-1Z6WKrnE.mjs.map} +1 -1
- package/dist/{libsql-DuGR904j.mjs → libsql-DJRsCDT_.mjs} +2 -2
- package/dist/{libsql-DuGR904j.mjs.map → libsql-DJRsCDT_.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-G4cSuc6A.mjs → memory-gjKMy3Ql.mjs} +2 -2
- package/dist/{memory-G4cSuc6A.mjs.map → memory-gjKMy3Ql.mjs.map} +1 -1
- package/dist/methods-part-DoTrY6b9.mjs +2 -0
- package/dist/methods-part-DoTrY6b9.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/snowflake.d.mts +4 -4
- package/dist/migrations/snowflake.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/surrealdb.d.mts +4 -4
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-BNXWfTOo.mjs → mysql-BH0Z3PlH.mjs} +2 -2
- package/dist/{mysql-BNXWfTOo.mjs.map → mysql-BH0Z3PlH.mjs.map} +1 -1
- package/dist/mysql-adapter-B06Ve3ds.mjs +2 -0
- package/dist/mysql-adapter-B06Ve3ds.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/named-statements-Bdz2GD5R.d.mts +13 -0
- package/dist/named-statements-CMj1QEyw.mjs +2 -0
- package/dist/named-statements-CMj1QEyw.mjs.map +1 -0
- package/dist/{native-types-DgjMUikz.mjs → native-types-DspZ0Z5E.mjs} +2 -2
- package/dist/{native-types-DgjMUikz.mjs.map → native-types-DspZ0Z5E.mjs.map} +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/{object-store-B_YMoW8u.d.mts → object-store-D5x-Yf7w.d.mts} +3 -3
- package/dist/{object-store-DS0F0yZX.mjs → object-store-WIE0DGGG.mjs} +1 -1
- package/dist/{object-store-DS0F0yZX.mjs.map → object-store-WIE0DGGG.mjs.map} +1 -1
- package/dist/{on-ylYaKuRu.mjs → on-DvrfHGje.mjs} +2 -2
- package/dist/{on-ylYaKuRu.mjs.map → on-DvrfHGje.mjs.map} +1 -1
- package/dist/on.d.mts +1 -1
- package/dist/on.mjs +1 -1
- package/dist/ordering/keys.mjs +1 -1
- package/dist/ordering.d.mts +1 -1
- package/dist/ordering.mjs +1 -1
- package/dist/pending-operation-Dq4rv-Ml.mjs +2 -0
- package/dist/pending-operation-Dq4rv-Ml.mjs.map +1 -0
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/pg.d.mts +27 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/{physical-CeE2nYmI.mjs → physical-wboFLAg9.mjs} +2 -2
- package/dist/{physical-CeE2nYmI.mjs.map → physical-wboFLAg9.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-DHjdvjwk.d.mts → planner-Ckoxeruk.d.mts} +1 -1
- package/dist/{postgres-CDdh5dSP.mjs → postgres-DQ_pO0hi.mjs} +2 -2
- package/dist/{postgres-CDdh5dSP.mjs.map → postgres-DQ_pO0hi.mjs.map} +1 -1
- package/dist/{postgres-adapter-axapXX8d.mjs → postgres-adapter-Byp7Zpop.mjs} +2 -2
- package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-Byp7Zpop.mjs.map} +1 -1
- package/dist/postgres-adapter-Ia4u0-Ht.mjs +2 -0
- package/dist/postgres-adapter-Ia4u0-Ht.mjs.map +1 -0
- package/dist/postgres-result-CiS5OWp1.mjs +2 -0
- package/dist/postgres-result-CiS5OWp1.mjs.map +1 -0
- package/dist/postgres.d.mts +17 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-Ccsb8PTb.mjs → provider-limits-CCOa4d1E.mjs} +2 -2
- package/dist/{provider-limits-Ccsb8PTb.mjs.map → provider-limits-CCOa4d1E.mjs.map} +1 -1
- package/dist/{provider-parameter-snapshot-BikrgKqI.mjs → provider-parameter-snapshot-C0ehKSAA.mjs} +2 -2
- package/dist/{provider-parameter-snapshot-BikrgKqI.mjs.map → provider-parameter-snapshot-C0ehKSAA.mjs.map} +1 -1
- package/dist/query-Cdy8E2jM.mjs +2 -0
- package/dist/query-Cdy8E2jM.mjs.map +1 -0
- package/dist/{query-inspection-BoG-yAln.mjs → query-inspection-C-T2ttRx.mjs} +2 -2
- package/dist/{query-inspection-BoG-yAln.mjs.map → query-inspection-C-T2ttRx.mjs.map} +1 -1
- package/dist/{raw-Dyq6Y6UX.mjs → raw-uaVIxHcE.mjs} +2 -2
- package/dist/{raw-Dyq6Y6UX.mjs.map → raw-uaVIxHcE.mjs.map} +1 -1
- package/dist/{relation-bound-ku_cMdye.mjs → relation-bound-BaU-LuuI.mjs} +1 -1
- package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-BaU-LuuI.mjs.map} +1 -1
- package/dist/{rule-words-ZIGm7cDm.mjs → rule-words-C4lXzgW2.mjs} +2 -2
- package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-C4lXzgW2.mjs.map} +1 -1
- package/dist/scalar-B9WizsvR.mjs +4 -0
- package/dist/scalar-B9WizsvR.mjs.map +1 -0
- package/dist/schema/introspect.d.mts +2 -2
- package/dist/schema/introspect.mjs +1 -1
- package/dist/schema/json.d.mts +2 -2
- package/dist/schema/json.mjs +1 -1
- package/dist/{schema-BYA-_bpk.mjs → schema-MB-pPNTO.mjs} +2 -2
- package/dist/schema-MB-pPNTO.mjs.map +1 -0
- package/dist/{schema-CFIaebgi.mjs → schema-TthAXPVP.mjs} +2 -2
- package/dist/{schema-CFIaebgi.mjs.map → schema-TthAXPVP.mjs.map} +1 -1
- package/dist/schema-introspection-wMVZowIF.mjs +6 -0
- package/dist/schema-introspection-wMVZowIF.mjs.map +1 -0
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/select-assembly-SuVxJjps.mjs +2 -0
- package/dist/select-assembly-SuVxJjps.mjs.map +1 -0
- package/dist/{serializer-rBq3v1xr.mjs → serializer-B2kk7NAR.mjs} +5 -5
- package/dist/{serializer-rBq3v1xr.mjs.map → serializer-B2kk7NAR.mjs.map} +1 -1
- package/dist/{settled-BjyuA76m.mjs → settled-Dkk5w1vE.mjs} +2 -2
- package/dist/{settled-BjyuA76m.mjs.map → settled-Dkk5w1vE.mjs.map} +1 -1
- package/dist/{snowflake-UOCC820W.mjs → snowflake-6sBLJi34.mjs} +2 -2
- package/dist/{snowflake-UOCC820W.mjs.map → snowflake-6sBLJi34.mjs.map} +1 -1
- package/dist/snowflake.d.mts +2 -2
- package/dist/snowflake.mjs +1 -1
- package/dist/snowflake.mjs.map +1 -1
- package/dist/soft-delete.d.mts +1 -1
- package/dist/soft-delete.mjs +1 -1
- package/dist/{spans-XDUFeTzC.mjs → spans-BE-EjlZK.mjs} +1 -1
- package/dist/{spans-XDUFeTzC.mjs.map → spans-BE-EjlZK.mjs.map} +1 -1
- package/dist/sql-BGjAsoBE.mjs +2 -0
- package/dist/sql-BGjAsoBE.mjs.map +1 -0
- package/dist/{sql-Dl6nykFV.mjs → sql-CFxGrk3K.mjs} +2 -2
- package/dist/{sql-Dl6nykFV.mjs.map → sql-CFxGrk3K.mjs.map} +1 -1
- package/dist/{sql-BVZ8QefY.d.mts → sql-CXtSIPzy.d.mts} +11 -5
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/{sqlite-adapter-Ad0d-m2t.mjs → sqlite-adapter-fIbNDvwO.mjs} +2 -2
- package/dist/{sqlite-adapter-Ad0d-m2t.mjs.map → sqlite-adapter-fIbNDvwO.mjs.map} +1 -1
- package/dist/{sqlite-utils-BRvbmlQ1.mjs → sqlite-utils-DcQct689.mjs} +2 -2
- package/dist/{sqlite-utils-BRvbmlQ1.mjs.map → sqlite-utils-DcQct689.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/{standard-sql-qLcQyCtK.mjs → standard-sql-Bsf5nrla.mjs} +3 -3
- package/dist/standard-sql-Bsf5nrla.mjs.map +1 -0
- package/dist/surrealdb.d.mts +2 -2
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/{surrealql-C1dp1sWw.mjs → surrealql-DY7sgVnJ.mjs} +2 -2
- package/dist/{surrealql-C1dp1sWw.mjs.map → surrealql-DY7sgVnJ.mjs.map} +1 -1
- package/dist/{to-many-BybuKQM1.mjs → to-many-DiP6cOSQ.mjs} +2 -2
- package/dist/{to-many-BybuKQM1.mjs.map → to-many-DiP6cOSQ.mjs.map} +1 -1
- package/dist/{unit-BhHbZyuJ.mjs → unit-CSaAB0su.mjs} +2 -2
- package/dist/{unit-BhHbZyuJ.mjs.map → unit-CSaAB0su.mjs.map} +1 -1
- package/dist/{unit-words-CT0yeqfZ.mjs → unit-words-BGMVZ1MX.mjs} +2 -2
- package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BGMVZ1MX.mjs.map} +1 -1
- package/dist/{utils-CpAojrCj.mjs → utils-BLlgSQIo.mjs} +2 -2
- package/dist/{utils-CpAojrCj.mjs.map → utils-BLlgSQIo.mjs.map} +1 -1
- package/dist/validation-D0LG854o.mjs +2 -0
- package/dist/validation-D0LG854o.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-CZLW7aR3.mjs → validator-CDYlO9HV.mjs} +2 -2
- package/dist/{validator-CZLW7aR3.mjs.map → validator-CDYlO9HV.mjs.map} +1 -1
- package/dist/{values-B4aj1i1f.mjs → values-Byqn5wAh.mjs} +2 -2
- package/dist/{values-B4aj1i1f.mjs.map → values-Byqn5wAh.mjs.map} +1 -1
- package/dist/version-B_ZLWzLW.mjs +2 -0
- package/dist/{version-CXGIA82S.mjs.map → version-B_ZLWzLW.mjs.map} +1 -1
- package/package.json +35 -35
- package/dist/client-DRpX3-vw.mjs +0 -2
- package/dist/client-DRpX3-vw.mjs.map +0 -1
- package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
- package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
- package/dist/every-tOgQmaIE.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
- package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
- package/dist/identifiers-s00pGES8.mjs +0 -2
- package/dist/identifiers-s00pGES8.mjs.map +0 -1
- package/dist/judge-words-CzUyXtJ6.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
- package/dist/methods-part-ZY0f2AV_.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
- package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
- package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
- package/dist/pending-operation-C_eOFOBE.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
- package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
- package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
- package/dist/postgres-result-DF6DmW3r.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
- package/dist/query-BZVHfA0s.mjs +0 -2
- package/dist/query-BZVHfA0s.mjs.map +0 -1
- package/dist/scalar-BHCh7aUz.mjs +0 -4
- package/dist/scalar-BHCh7aUz.mjs.map +0 -1
- package/dist/schema-BYA-_bpk.mjs.map +0 -1
- package/dist/schema-introspection-D0f8cti4.mjs +0 -6
- package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
- package/dist/select-assembly-DVI7d3tf.mjs +0 -2
- package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
- package/dist/sql-3o4DOKm9.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs.map +0 -1
- package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
- package/dist/validation-CYaJ8ndO.mjs +0 -2
- package/dist/validation-CYaJ8ndO.mjs.map +0 -1
- package/dist/version-CXGIA82S.mjs +0 -2
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mysql-adapter-C69j1sKh.mjs","names":["sql","#batchRefs","#assemble"],"sources":["../src/adapters/databases/mysql/mysql-adapter.ts"],"sourcesContent":["import { unsupportedVector } from \"@errors\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { type Sql, sql } from \"@sql\";\nimport { encodeMySqlDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type { ArithmeticTarget } from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport {\n type AdapterResultParser,\n passThroughParseResult,\n} from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n type TextMatch,\n} from \"../../database-adapter\";\nimport { createMySqlBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n halfEvenQuotient,\n scaleFactorSql,\n scaleUnitSql,\n signedNumerator,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport { parseIntegerBoolean } from \"../../shared/result-parsing\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n buildJsonPath,\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createEmulatedNullsOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n stringifyJson,\n} from \"../../shared/standard-sql\";\n\nconst quoteIdent = createIdentifierQuoter(\"`\");\nconst MYSQL_CONSTRAINTS = createNamedConstraintIdentities(() => \"PRIMARY\");\n\n/**\n * MySQL has `MOD()` but no exact integer-quotient function for decimals: `DIV`\n * converts both sides to BIGINT (so it overflows and truncates a wide\n * `DECIMAL`), and `TRUNCATE(n / d, 0)` computes `n / d` to\n * `div_precision_increment` extra digits and ROUNDS there first, which can turn\n * a value just below a half into an exact-looking tie.\n *\n * `(n - MOD(n, d)) / d` avoids both: the numerator is exactly divisible by `d`,\n * so the division's true result has no fractional digits and the extra digits\n * MySQL computes are all zero.\n */\nconst MYSQL_INTEGERS: ExactIntegerArithmetic = {\n // The CAST is not decoration. MySQL's `/` ALWAYS returns\n // `div_precision_increment` (four, by default) fractional digits, so an exact\n // integer quotient arrives typed `DECIMAL(w, 4)` — four digits of the 65-digit\n // exact domain spent on zeros, and any product taking that value as an operand\n // would carry them into ITS width. Casting back to the widest exact integer\n // domain is exact here (the value has no fraction to lose) and is what keeps\n // every downstream term integer-typed.\n quotient: (n: Sql, d: Sql): Sql =>\n sql`CAST((${n} - MOD(${n}, ${d})) / ${d} AS DECIMAL(65,0))`,\n remainder: (n: Sql, d: Sql): Sql => sql`MOD(${n}, ${d})`,\n};\n\n/**\n * MySQL's exact decimal domain, in digits — the ceiling every expression below\n * is written to stay under (plan 5.3: \"MySQL expressions avoid an intermediate\n * wider than its 65-digit exact domain\").\n */\nconst MYSQL_EXACT_DIGITS = 65;\n\nconst mysqlMaximumCoefficient = (digits: number): Sql =>\n sql.raw(\"9\".repeat(digits));\n\nconst mysqlStrictMode = sql`(FIND_IN_SET('STRICT_TRANS_TABLES', @@SESSION.sql_mode) > 0 OR FIND_IN_SET('STRICT_ALL_TABLES', @@SESSION.sql_mode) > 0)`;\n\nconst mysqlArithmeticFailure = sql`JSON_EXTRACT('x', '$')`;\n\n/** `CAST(<expr> AS DECIMAL(precision,scale))`, the width-declaring device. */\nconst decimalCast = (expr: Sql, precision: number, scale: number): Sql =>\n sql`CAST(${expr} AS ${sql.raw(`DECIMAL(${precision},${scale})`)})`;\n\n/**\n * The signed unscaled COEFFICIENT of a logical `DECIMAL(p,s)` expression, as an\n * exact integer — WITHOUT ever multiplying the whole value by `10^s`.\n *\n * `column * 10^s` is the obvious spelling and it is the unsafe one. MySQL types\n * a product as `DECIMAL(p1+p2, s1+s2)` capped at `(65, 30)`, so multiplying a\n * `DECIMAL(65,30)` column by a `DECIMAL(31,0)` factor asks for a 96-digit type,\n * gets a 65-digit one whose 30 fractional digits leave 35 for an integer that\n * needs 65 — and MySQL answers ZERO, with no warning and no error (measured on\n * 8.4: `SELECT CAST(REPEAT('9',50) AS DECIMAL(65,0)) * 0.<29 zeros>1` is\n * `0.000…0`). Splitting the value first is what keeps every factor small:\n *\n * whole = TRUNCATE(v, 0) |whole| < 10^(p-s), scale 0\n * fraction = v - whole |fraction| < 1, scale s\n * coefficient = whole * 10^s + fraction * 10^s\n *\n * Widths, by construction, for every descriptor MySQL admits (`p <= 65`,\n * `s <= 30`, `p + s <= 65`): `whole * 10^s` is typed\n * `DECIMAL(min(p+2,65), 0)` and valued\n * below `10^p`; `fraction * 10^s` is typed `DECIMAL(2s+2, s)` — at most 62\n * digits — and valued below `10^s`, so its cast to `DECIMAL(s,0)` is exact.\n * Neither product's operands sum past the exact domain, so neither can take the\n * silent arm above.\n */\nconst mysqlCoefficient = (value: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return value;\n const factor = scaleFactorSql(scale);\n const whole = sql`TRUNCATE(${value}, 0)`;\n const fraction = decimalCast(sql`(${value} - ${whole})`, scale + 1, scale);\n return sql`(${whole} * ${factor} + ${decimalCast(sql`(${fraction} * ${factor})`, scale, 0)})`;\n};\n\n/**\n * The logical `DECIMAL(p,s)` value of an exact integer COEFFICIENT — the\n * inverse of {@link mysqlCoefficient}, and unsafe for the same reason in the\n * same place.\n *\n * `coefficient * 10^-s` would multiply a `p`-digit integer by a\n * `DECIMAL(s+1,s)` literal: `p + s + 1` digits of type for a value that needs\n * `p`, which is the silent-zero arm again for a wide descriptor. So the\n * coefficient is split by `10^s` FIRST — an integer part that is already the\n * answer's integer part, and a remainder below `10^s` that is the only thing\n * the tiny `10^-s` literal ever multiplies:\n *\n * integer part = (coefficient - MOD(coefficient, 10^s)) / 10^s\n * fraction = MOD(coefficient, 10^s) * 10^-s\n *\n * Widths: the division is typed `DECIMAL(w, 4)` over a value below `10^(p-s)`,\n * and the fractional product's operands sum to `2s + 1` — at most 61 digits.\n */\nconst mysqlLogical = (coefficient: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return coefficient;\n const factor = scaleFactorSql(scale);\n const remainder = sql`MOD(${coefficient}, ${factor})`;\n return sql`((${coefficient} - ${remainder}) / ${factor} + ${decimalCast(remainder, scale, 0)} * ${scaleUnitSql(scale)})`;\n};\n\n/**\n * Assign one coefficient-space answer without letting a non-strict MySQL\n * session turn overflow into a clipped value. Strict sessions retain their\n * native error. A non-strict session reaches the answer only after the caller's\n * operation-specific precondition proves its intermediate is exact and the\n * target-domain check proves the final coefficient fits.\n *\n * The session-mode arm is deliberately first. `CASE` is the same lazy error\n * primitive used by this adapter's assertion queries, so a safe or NULL arm\n * never evaluates the invalid JSON expression that raises the provider error.\n */\nconst mysqlGuardedDecimalAssignment = (\n column: Sql,\n coefficient: Sql,\n descriptor: DecimalDescriptor,\n intermediateFits: Sql\n): Sql => {\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const logical = mysqlLogical(coefficient, descriptor);\n return sql`${column} = CASE WHEN ${mysqlStrictMode} THEN ${logical} WHEN ${column} IS NULL THEN NULL WHEN ${intermediateFits} THEN CASE WHEN ${coefficient} BETWEEN -${maximum} AND ${maximum} THEN ${logical} ELSE ${mysqlArithmeticFailure} END ELSE ${mysqlArithmeticFailure} END`;\n};\n\nconst mysqlDecimalIncrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = sql`CASE WHEN ${operand} > 0 THEN ${current} <= ${maximum} - ${operand} WHEN ${operand} < 0 THEN ${current} >= -${maximum} - ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n sql`(${current} + ${operand})`,\n descriptor,\n fits\n );\n};\n\nconst mysqlDecimalDecrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = sql`CASE WHEN ${operand} > 0 THEN ${current} >= -${maximum} + ${operand} WHEN ${operand} < 0 THEN ${current} <= ${maximum} + ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n sql`(${current} - ${operand})`,\n descriptor,\n fits\n );\n};\n\n/**\n * `column = halfEven(column x by)`, computed on COEFFICIENTS.\n *\n * This is plan 5.3's rule verbatim — `multiply = halfEven((x * y) / F)` — and\n * it is stated on integers because MySQL cannot state it on logical values: the\n * exact product of two `DECIMAL(p,s)` values carries `2s` fractional digits,\n * and MySQL caps an expression's scale at 30, ROUNDING anything finer away\n * before the tie this rule exists to decide is ever visible (measured: `1e-30 *\n * 1e-30` is `0.000…0` at `DECIMAL(65,30)`, no warning). Coefficients have no\n * fractional digits at all, so nothing can be rounded away underneath the rule.\n *\n * WIDTH, BY CONSTRUCTION. `|x|, |y| < 10^p`, and the answer is in the field's\n * domain exactly when `|x * y| < 10^(p+s)`, so the product needs at most\n * `p + s` digits: within the 65-digit exact domain for every descriptor with\n * `precision + scale <= 65`. The quotient is `< 10^p`, the remainder `< 10^s`,\n * and the tie test compares `|r|` against `10^s - |r|` — the non-doubling form,\n * so nothing widens there either.\n *\n * Outside that bound the operation is loud on every session. A strict session\n * reaches MySQL's native overflow error. A non-strict session first proves the\n * product can be formed inside 65 digits and that the rounded coefficient fits\n * the field; a failed proof evaluates the adapter's lazy error expression\n * instead of letting MySQL clip the assignment. Both leave the row unchanged.\n */\nconst mysqlDecimalMultiply = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const left = mysqlCoefficient(column, descriptor);\n const right = mysqlCoefficient(by, descriptor);\n const maximumIntermediate = mysqlMaximumCoefficient(MYSQL_EXACT_DIGITS);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`(${left} * ${right})`,\n scaleFactorSql(descriptor.scale)\n );\n const intermediateFits = sql`CASE WHEN ${right} = 0 THEN TRUE ELSE ABS(${left}) <= ${MYSQL_INTEGERS.quotient(maximumIntermediate, sql`ABS(${right})`)} END`;\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n intermediateFits\n );\n};\n\n/**\n * `column = halfEven(column / by)`, computed on COEFFICIENTS — plan 5.3's\n * `divide = halfEven((x * F) / y)`.\n *\n * The divisor is the operand's COEFFICIENT rather than its logical value: an\n * exact quotient is spelled `(n - MOD(n, d)) / d`, and with a fractional `d`\n * the numerator `n - MOD(n, d)` is `q * d` — a `p`-digit magnitude carrying `s`\n * fractional digits, `p + s` digits for a value the integer form states in `p`.\n * Integers on both sides keep every term at its own width.\n *\n * WIDTH, BY CONSTRUCTION: `|x * F| < 10^(p+s)` — inside the exact domain for\n * every descriptor with `precision + scale <= 65`, and unconditionally, not\n * only when the answer fits. The quotient is the answer's coefficient\n * (`< 10^p` when it fits the field), the remainder is below `|y| < 10^p`, and\n * the tie compares `|r|` against `|y| - |r|`, which is why the doubled form was\n * dropped: `2|r|` at `p = 65` needs 66.\n *\n * `by` is never zero — division by canonical zero is refused before I/O.\n */\nconst mysqlDecimalDivide = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const divisor = mysqlCoefficient(by, descriptor);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n signedNumerator(\n sql`(${mysqlCoefficient(column, descriptor)} * ${scaleFactorSql(descriptor.scale)})`,\n divisor\n ),\n sql`ABS(${divisor})`\n );\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n sql.raw`TRUE`\n );\n};\n\n/**\n * The exact decimal average, on coefficients: `SUM` of the column's\n * coefficients over `COUNT(column)`, quantized half to even.\n *\n * Summing the COEFFICIENTS rather than scaling the sum is what removes the last\n * `x 10^s` from this expression: `SUM(column) * 10^s` multiplies a value MySQL\n * already types up to 65 digits by a 31-digit factor, which is the silent-zero\n * arm {@link mysqlCoefficient} exists to avoid. Every row's coefficient is\n * below `10^p`, so the only way the sum leaves the exact domain is by genuinely\n * exceeding it, and MySQL raises there.\n *\n * `COUNT(column)` counts non-nulls, so an empty or all-null group answers NULL\n * through the null-strict operators instead of dividing by zero.\n */\nconst mysqlDecimalAverage = (\n column: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`SUM(${mysqlCoefficient(column, descriptor)})`,\n sql`COUNT(${column})`\n );\n return mysqlLogical(coefficient, descriptor);\n};\n// MySQL's own case folding: `LOWER` maps every letter by the string's\n// character set (Unicode for utf8mb4). It must see the raw text — on a\n// `BINARY` string it does nothing — and its result is compared as bytes, so a\n// case- AND accent-insensitive collation (`utf8mb4_0900_ai_ci`) never decides.\nconst caseFold = (expr: Sql): Sql => sql`LOWER(${expr})`;\n\n// MySQL DATETIME rejects ISO-8601's 'Z' suffix (\"Incorrect datetime value\"),\n// so datetimes are stored as naive UTC wall-clock 'YYYY-MM-DD HH:MM:SS.mmm'.\n\n// Naive datetime string as it comes back from MySQL (top-level on string\n// drivers, or inside JSON_ARRAYAGG/JSON_OBJECT includes): no 'Z'/offset.\nconst NAIVE_DATETIME_REGEX =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2})(\\.\\d+)?$/;\n\n/** Reattach UTC to a naive MySQL datetime string so it parses as the stored instant. */\nconst naiveDateTimeToIso = (value: string): string | undefined => {\n const match = NAIVE_DATETIME_REGEX.exec(value);\n if (!match) return undefined;\n const fraction = match[3] ? match[3].padEnd(4, \"0\").slice(0, 4) : \".000\";\n return `${match[1]}T${match[2]}${fraction}Z`;\n};\n\n/** Replace a single-integer-parameter fragment with an inline literal. */\nconst inlineIntegerLiteral = (fragment: Sql): Sql => {\n const value = fragment.values.length === 1 ? fragment.values[0] : undefined;\n return typeof value === \"number\" && Number.isInteger(value)\n ? sql.raw(String(value))\n : fragment;\n};\n\nconst mysqlJsonObject = (pairs: [string, Sql][]): Sql => {\n if (pairs.length === 0) return sql.raw`JSON_OBJECT()`;\n const args = pairs.flatMap(([key, value]) => [sql`${key}`, value]);\n return sql`JSON_OBJECT(${sql.join(args, \", \")})`;\n};\n\n/** The one JSON list container every MySQL list value crosses as. */\nconst mysqlJsonListValue = (values: unknown[]): Sql =>\n sql`CAST(${stringifyJson(values)} AS JSON)`;\n\nexport class MySQLAdapter implements DatabaseAdapter {\n /**\n * The bound database, or `undefined` for the unqualified mode a\n * provider-configured MySQL2 client and every PlanetScale client keep. Under\n * Vitess the value is the keyspace qualifier submitted before routing rules\n * apply, not a proof of the routed backend.\n */\n declare readonly namespace: string | undefined;\n\n constructor(namespace?: string) {\n installAdapterNamespace(this, namespace, \"mysql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(quoteIdent, this.namespace, true);\n installGeoPointSql(this, this.geoPoint);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: MYSQL_CONSTRAINTS,\n // Qualified by the bound database; an unbound adapter cannot pin.\n ...(this.namespace !== undefined && {\n pinnedTable: this.identifiers.table,\n }),\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // MySQL requires JSON values to be stringified\n json: (v: unknown): Sql => sql`${JSON.stringify(v)}`,\n\n dateTime: (\n iso: string,\n _nativeType?: NativeTypeDeclaration,\n member?: boolean\n ): Sql =>\n sql`${member || iso.length === 10 ? iso : encodeMySqlDateTime(iso)}`,\n\n // The cast is load-bearing, not decoration. MySQL's comparison rules say\n // that when one side is a number and the other a string, BOTH are converted\n // to double and compared as floating point — so `amount = '0.1'` against a\n // `DECIMAL` column would silently answer at float precision on an otherwise\n // exact column. Casting the operand into the SAME `DECIMAL(p,s)` the DDL\n // emits keeps the whole comparison in MySQL's exact decimal domain, and\n // names one domain for the operand and the column instead of two.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${encodePhysicalDecimal(canonical, descriptor, \"text\")} AS ${sql.raw(decimalColumnType(\"mysql\", descriptor))})`,\n\n // MySQL has no `uuid` type: every compact domain is a `BINARY(n)` column\n // and takes the payload's bytes as an ordinary binary parameter, which is\n // the same parameter a blob scalar already binds. A text-stored domain\n // takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n _representation: IdRepresentation\n ): Sql => sql`${physical}`,\n };\n\n operators = {\n ...createComparisonOperators(),\n\n containsText: (column: Sql, value: Sql): Sql =>\n sql`LOCATE(BINARY ${value}, BINARY ${column}) > 0`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`RIGHT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n insensitiveText: (kind: TextMatch, column: Sql, value: Sql): Sql =>\n this.operators[`${kind}Text`](caseFold(column), caseFold(value)),\n // Two conjuncts, because on MySQL no single predicate is both exact and\n // index-usable. The index stores the column's own collation's sort keys —\n // `utf8mb4_0900_ai_ci` on a default install, which is case- AND\n // accent-insensitive — so any comparison forced to BINARY cannot range on\n // it. Measured on MySQL 8 (Docker, 20k rows): `col LIKE 'x%'` is a `range`\n // over 111 rows, while both `col LIKE BINARY 'x%'` and the\n // `LEFT(BINARY col, …)` spelling above degrade to a full `index` scan of\n // all 19731 entries.\n //\n // So the collation-native LIKE goes first as an index accelerator, and the\n // BINARY predicate — byte-identical to `startsWithText` above — follows as\n // the semantics. The accelerator can never drop a row the BINARY conjunct\n // would keep: byte-equal strings compare equal under every collation, so a\n // binary prefix match implies the collation-native one. It is not a second\n // guard on the same invariant — it decides no row's membership, only which\n // rows the server has to look at.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`(${column} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\\\\\' AND LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value})`,\n\n // `startsWithPrefix`'s twin, for the same reason and in the same shape\n // (plan §10.2). `BINARY col` is a FUNCTION of the column, so MySQL cannot\n // range on it: measured on MySQL 8.4 over 20,000 rows in the collation\n // viborm's own DDL declares, `BINARY name = ?` planned `index` over 20,455\n // rows where `name = ?` planned `ref` over 1, and `BINARY name IN (…)`\n // planned `index` over 20,455 where `name IN (…)` planned `range` over 3.\n //\n // The collation-native conjunct is the accelerator and decides no row's\n // membership: byte-identical strings compare equal under every collation\n // of the charset, so the BINARY comparison IMPLIES it. On the tables\n // viborm creates (`utf8mb4_0900_bin`) the two conjuncts say the same\n // thing; on a table viborm did not create the BINARY one is what keeps the\n // case-sensitivity contract, and the same measurement shows the pair still\n // plans `ref` over 1 row there.\n //\n // `notIn` and `not` deliberately have no such pair. Their implication runs\n // the other way — `BINARY col NOT IN ('X')` KEEPS a row spelled `x` that\n // `col NOT IN ('X')` drops on a case-insensitive column, measured at\n // 20,000 rows against 19,999 — so a conjunct would remove rows. There is\n // also nothing to win: both spellings of `NOT IN` scan all 20,442 rows.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n exactTextEq: (column: Sql, value: Sql): Sql =>\n sql`(${column} = ${value} AND BINARY ${column} = ${value})`,\n exactTextIn: (column: Sql, values: Sql): Sql =>\n sql`(${column} IN ${values} AND BINARY ${column} IN ${values})`,\n\n ...createMembershipOperators(),\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n caseFold,\n caseSensitiveText: (expr: Sql): Sql => sql`BINARY ${expr}`,\n\n // String operations - MySQL uses CONCAT() function\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`CONCAT(${sql.join(parts, \", \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // The expression form of `set.divide`'s integer arm: MySQL `/` yields a\n // DECIMAL quotient even for two integers, so the truncation is explicit.\n integerDivide: (left: Sql, right: Sql): Sql =>\n sql`TRUNCATE(${left} / ${right}, 0)`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n decimalCast(expr, descriptor.precision, descriptor.scale),\n\n // `CHAR` rather than `TEXT`: MySQL's CAST target list has no `TEXT`, which\n // is why `cast` below maps the generic text cast to `CHAR` too.\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`UNHEX(${expr})`\n : sql`CAST(${expr} AS CHAR)`,\n\n cast: createCastExpression({\n text: \"CHAR\",\n integer: \"SIGNED\",\n bigint: \"SIGNED\",\n boolean: \"UNSIGNED\",\n numeric: \"DECIMAL\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`LOWER(HEX(${expr}))`,\n };\n\n aggregates = {\n ...createAggregateFunctions(),\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n mysqlDecimalAverage(column, descriptor),\n\n // MySQL's widest exact DECIMAL cast operand. SUM itself can return more\n // than 65 digits; this bound belongs to exact HAVING operand lowering.\n decimalSumOperandPrecision:\n createDecimalSumOperandPrecision(MYSQL_EXACT_DIGITS),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql => sql`${left} = ${right}`,\n number: (expression: Sql): Sql => expression,\n boolean: (condition: Sql): Sql =>\n sql`JSON_EXTRACT(CASE WHEN ${condition} THEN 'true' ELSE 'false' END, '$')`,\n document: (expression: Sql): Sql => expression,\n\n object: mysqlJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw`JSON_ARRAY()`,\n\n agg: (expr: Sql): Sql =>\n sql`COALESCE(JSON_ARRAYAGG(${expr}), JSON_ARRAY())`,\n\n objectFromColumns: mysqlJsonObject,\n\n // buildJsonPath quotes/escapes key segments and maps integer segments\n // to array indices; '$' alone extracts the document root\n extract: (column: Sql, path: string[]): Sql =>\n sql`JSON_EXTRACT(${column}, ${buildJsonPath(path)})`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`JSON_UNQUOTE(JSON_EXTRACT(${column}, ${buildJsonPath(path)}))`,\n\n // JSON_TYPE spells numbers three ways depending on how the literal was\n // stored; anything else (including an absent path, where JSON_TYPE is\n // NULL) falls through the CASE to NULL\n numberAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS DOUBLE) END)`;\n },\n\n // CAST(... AS BINARY) yields VARBINARY, so < / > compare bytes instead of\n // the column's (case- and accent-insensitive by default) collation\n stringAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS BINARY) END)`;\n },\n foldableStringAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) = 'STRING' THEN JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) END)`;\n },\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${target}, ${value})`,\n\n lastElement: (target: Sql): Sql => sql`JSON_EXTRACT(${target}, '$[last]')`,\n\n // Comparing a JSON column to a plain string coerces the string to a JSON\n // string scalar (always-false for documents); CAST parses it as JSON\n value: (v: unknown): Sql => sql`CAST(${stringifyJson(v)} AS JSON)`,\n };\n\n arrays = {\n // MySQL uses JSON arrays\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\n\n value: mysqlJsonListValue,\n\n // Deliberately the same container, by identity: MySQL stores an enum LIST\n // as JSON like every other list, so its members are ordinary JSON strings\n // and there is no element type to spell. The inline `ENUM(...)` describes\n // one member.\n enumValue: mysqlJsonListValue,\n\n // JSON_CONTAINS requires a JSON document as candidate; a bare string\n // parameter throws ER_INVALID_JSON_TEXT. JSON_ARRAY keeps the parameter's\n // type (strings quoted, numbers not): [x] ⊆ column ⟺ x ∈ column\n has: (column: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, JSON_ARRAY(${value}))`,\n\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, ${values})`,\n\n hasSome: (column: Sql, values: Sql): Sql =>\n sql`JSON_OVERLAPS(${column}, ${values})`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(JSON_LENGTH(${column}) = 0 OR ${column} IS NULL)`,\n\n // The container as TEXT, so it reaches the decode as the exact bytes the\n // codec wrote: uncast, mysql2 parses a JSON column into a JavaScript\n // document and JSON_OBJECT nests it as a live array, and the coefficient\n // grammar would then be read off values a JSON parser already interpreted.\n exactNumericProjection: (column: Sql): Sql => sql`CAST(${column} AS CHAR)`,\n\n length: (column: Sql): Sql => sql`JSON_LENGTH(${column})`,\n\n get: (column: Sql, index: Sql): Sql =>\n sql`JSON_EXTRACT(${column}, CONCAT('$[', ${index}, ']'))`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`JSON_ARRAY_APPEND(${column}, '$', ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`JSON_SET(${column}, CONCAT('$[', ${index}, ']'), ${value})`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n // MySQL doesn't support NULLS FIRST/LAST natively - emulated\n ...createEmulatedNullsOrderBy(),\n };\n\n // mysql2's binary protocol binds JS numbers as DOUBLE, which MySQL rejects\n // in integer-only positions (\"Incorrect arguments to mysqld_stmt_execute\").\n // Inline integer LIMIT/OFFSET values instead of parameterizing them.\n clauses = {\n ...createStandardClauses(),\n limit: (count: Sql): Sql => sql`LIMIT ${inlineIntegerLiteral(count)}`,\n offset: (count: Sql): Sql => sql`OFFSET ${inlineIntegerLiteral(count)}`,\n };\n\n // JSON_MERGE_PRESERVE concatenates arrays element-wise; JSON_ARRAY_APPEND\n // would append the whole param as a single (stringified) element.\n set = {\n ...createNumericSetOperations(),\n\n increment: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalIncrement(column, by, target.decimal)\n : sql`${column} = ${column} + ${by}`,\n\n decrement: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalDecrement(column, by, target.decimal)\n : sql`${column} = ${column} - ${by}`,\n\n // A decimal target rounds the product back to the field's scale; every\n // other numeric column keeps MySQL's native multiplication.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalMultiply(column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n // MySQL `/` yields DECIMAL and rounds when assigned to an integer column.\n // Truncate explicitly so integer division matches PostgreSQL and SQLite.\n // A decimal target takes neither: `/` would round at\n // `div_precision_increment` digits, so the exact half-even quotient rule\n // decides the last digit instead.\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n if (target?.decimal) {\n return mysqlDecimalDivide(column, by, target.decimal);\n }\n return target?.integer\n ? sql`${column} = TRUNCATE(${column} / ${by}, 0)`\n : sql`${column} = ${column} / ${by}`;\n },\n\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(COALESCE(${column}, JSON_ARRAY()), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(${values}, COALESCE(${column}, JSON_ARRAY()))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n // MySQL has no bare OFFSET; per the manual, use an all-ones LIMIT sentinel\n noLimitValue = sql.raw`18446744073709551615`;\n\n readonly #assemble = {\n select: (rawParts: QueryParts): Sql => {\n // Inline integer LIMIT/OFFSET (see clauses above for why)\n const parts: QueryParts = {\n ...rawParts,\n limit: rawParts.limit && inlineIntegerLiteral(rawParts.limit),\n offset: rawParts.offset && inlineIntegerLiteral(rawParts.offset),\n };\n\n // MySQL doesn't support DISTINCT ON natively\n // Simulate using ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)\n if (parts.distinct) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape,\n this.noLimitValue\n );\n }\n\n return assembleSelectQuery(sql`SELECT ${parts.columns}`, parts, {\n forUpdate: \"append\",\n noLimitValue: this.noLimitValue,\n });\n },\n };\n\n // MySQL 8.0+ common table expressions\n cte = createCteBuilders(quoteIdent);\n\n mutations = {\n skipDuplicatesStrategy: \"recoverableUniqueError\" as const,\n insert: createInsertStatement(quoteIdent),\n // `ON DUPLICATE KEY UPDATE` names no key: each row is selected where no\n // row holds its key, and what a row that is there takes is written after.\n insertAbsent: (\n table: Sql,\n columns: string[],\n rows: Sql[][],\n key: readonly string[],\n sets?: Sql,\n unless?: Sql\n ): Sql[] => {\n const name = (column: string) => sql.raw(quoteIdent(column));\n return rows.flatMap((row) => [\n sql`INSERT INTO ${table} (${sql.join(columns.map(name), \", \")}) SELECT * FROM (SELECT ${sql.join(\n row.map((value, at) => sql`${value} AS ${name(columns[at]!)}`),\n \", \"\n )}) AS \\`new\\` WHERE NOT EXISTS (SELECT 1 FROM ${table} AS \\`old\\` WHERE ${sql.join(\n key.map(\n (column) => sql`\\`old\\`.${name(column)} = \\`new\\`.${name(column)}`\n ),\n \" AND \"\n )})`,\n ...(sets\n ? [\n sql`UPDATE ${table} SET ${sets} WHERE ${sql.join(\n key.map(\n (column) =>\n sql`${name(column)} = ${row[columns.indexOf(column)]!}`\n ),\n \" AND \"\n )}${unless ? sql` AND NOT (${unless})` : sql.empty}`,\n ]\n : []),\n ]);\n },\n insertDefault: (table: Sql): Sql => sql`INSERT INTO ${table} () VALUES ()`,\n\n ...createMutationCommands(),\n updateFrom: (table, sets, source, on, where) =>\n sql`UPDATE ${table} JOIN ${source} ON ${on} SET ${sets}${\n where ? sql` WHERE ${where}` : sql.empty\n }`,\n\n // MySQL doesn't support RETURNING - returns empty\n // Use LAST_INSERT_ID() or SELECT after mutation\n returning: (_columns: Sql): Sql => sql.empty,\n\n // This low-level MySQL primitive ignores `_target`: ON DUPLICATE KEY UPDATE\n // fires on any unique collision. Public non-returning upserts therefore do\n // not execute this primitive; the query engine uses a locked, target-aware\n // branch so an unrelated unique collision still throws on every database.\n onConflict: (_target: Sql | null, action: Sql, _targetWhere?: Sql): Sql => {\n return sql`ON DUPLICATE KEY UPDATE ${action}`;\n },\n\n // MySQL doesn't need UPDATE SET prefix - onConflict already includes UPDATE\n onConflictUpdate: (sets: Sql, _setWhere?: Sql): Sql => sets,\n\n // A self-assignment reacts only to duplicate-key conflicts. Unlike\n // INSERT IGNORE, unrelated constraint and conversion failures still abort.\n //\n // It stays the JUNCTION insert's clause on MySQL as well, because\n // `ON DUPLICATE KEY UPDATE` cannot name a target (`onConflict` above says\n // so) — correct for every junction whose PK is its sole unique constraint,\n // which is every ordinary pair table. A polymorphic member table with a\n // SINGULAR inverse also carries a target-side UNIQUE that this clause would\n // swallow; the seam for that case is documented at `junctionDuplicateSkip`\n // in `query-engine/builders/many-to-many-utils.ts`.\n skipDuplicates: (duplicateNoopColumn: string) => {\n const column = sql.raw(quoteIdent(duplicateNoopColumn));\n return {\n prefix: sql.empty,\n suffix: sql`ON DUPLICATE KEY UPDATE ${column} = ${column}`,\n };\n },\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n notExists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n };\n\n joins = {\n ...createCoreJoins(),\n\n // MySQL doesn't support FULL OUTER JOIN (would need a UNION of LEFT and\n // RIGHT joins). Never silently downgrade to LEFT JOIN: that drops rows.\n // The query engine never calls this today.\n full: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.\"\n );\n },\n\n // MySQL 8.0.14+ supports LATERAL\n ...createLateralJoins(quoteIdent),\n };\n\n setOperations = createSetOperations();\n\n capabilities = {\n supportsReturning: false,\n supportsCteWithMutations: false, // MySQL CTEs are read-only\n supportsFullOuterJoin: false,\n supportsLateralJoins: true, // MySQL 8.0.14+\n supportsVector: false,\n supportsUpsertWhere: false, // ON DUPLICATE KEY UPDATE doesn't support WHERE clauses\n // ON DUPLICATE KEY UPDATE carries no conflict target and fires on ANY unique\n // collision — see the `onConflict` note above. A targeted upsert cannot be\n // spelled here, so the ON CONFLICT fold never opens on MySQL.\n supportsTargetedUpsert: false,\n // ERROR 1093: UPDATE/DELETE can't select from the mutated table in a\n // subquery. The engine wraps relation-filter subqueries in a derived\n // table when this is false (requires MySQL 8.0.14+ for outer references\n // in derived tables).\n supportsMutationTargetInSubquery: false,\n // MySQL's single-table UPDATE/DELETE take a native LIMIT, which is also the\n // only portable spelling here: the PK-subquery form would re-read the\n // mutated table and trip the same ERROR 1093 as above.\n supportsMutationRowLimit: true,\n supportsRowLocks: true,\n // InnoDB answers a locking miss on a unique index with a gap lock that\n // concurrent misses share and their INSERTs wait on (`ER_LOCK_DEADLOCK`).\n locksMissingKeys: true,\n boundsRecursionIterations: true,\n };\n\n lastInsertId = (): Sql => sql.raw`LAST_INSERT_ID()`;\n\n readonly #batchRefs = createMySqlBatchRefs({\n table: sql.raw`\\`__viborm_batch_refs\\``,\n batchIdColumn: sql.raw`\\`batch_id\\``,\n keyColumn: sql.raw`\\`ref_key\\``,\n valueColumn: sql.raw`\\`ref_value\\``,\n duplicateValue: sql.raw`VALUES(\\`ref_value\\`)`,\n createTable: sql.raw`CREATE TEMPORARY TABLE IF NOT EXISTS \\`__viborm_batch_refs\\` (\\`batch_id\\` VARCHAR(191) NOT NULL, \\`ref_key\\` VARCHAR(191) NOT NULL, \\`ref_value\\` TEXT, PRIMARY KEY (\\`batch_id\\`, \\`ref_key\\`))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS CHAR)`,\n lastInsertId: () => this.lastInsertId(),\n });\n\n vector = unsupportedVector;\n\n readonly geoPoint: GeoPointSql = (() => {\n const longitude = (point: Sql): Sql => sql`ST_Longitude(${point})`;\n const latitude = (point: Sql): Sql => sql`ST_Latitude(${point})`;\n return {\n // EPSG:4326 is latitude-longitude in MySQL's SRS catalog. The explicit\n // WKT option makes the two bound coordinates longitude-latitude instead.\n value: (pointLongitude, pointLatitude) =>\n sql`ST_GeomFromText(CONCAT('POINT(', ${pointLongitude}, ' ', ${pointLatitude}, ')'), 4326, 'axis-order=long-lat')`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators,\n (point, bounds) => {\n const polygons = geoBoundsIndexPolygons(bounds);\n if (polygons.length === 0) return;\n return this.operators.or(\n ...polygons.map(\n (polygon) =>\n sql`MBRIntersects(${point}, ST_GeomFromGeoJSON(${polygon}, 1, 4326))`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}, 1, 4326)`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) =>\n sql`ST_Distance_Sphere(${left}, ${right}, ${GEO_POINT_EARTH_RADIUS_METERS})`,\n };\n })();\n\n // RESULT PARSING\n // MySQL: booleans and naive UTC datetimes - both ROW VALUES.\n // This adapter says nothing about a RESULT: the engine's decoder asks for\n // the alias `_count` and reads it back, and mysql2 preserves that alias\n // (Arnaud's D-40, measured live).\n // Relation carriers decode at the query-engine boundary that knows their\n // value is JSON, so the adapter never sniffs ordinary strings.\n result: AdapterResultParser = {\n // A MySQL SCALAR decimal is `DECIMAL(p,s)` and answers with exact text, so\n // `decimalRepresentation` stays at its default. A decimal LIST is JSON,\n // which has no exact decimal at all, so its members are stored and returned\n // as unscaled coefficient strings (plan 6.1). This adapter is the reason\n // the two are separate declarations.\n decimalListRepresentation: \"coefficient\",\n\n // Derived from the ONE storage owner, so the column the migration creates\n // and the value this reads back cannot be two decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"mysql\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing on all 20 asks D-40 measured over\n // seven operations and both routes on live MySQL - the `count`/`exist` arm\n // was entered on 10 of them and answered `undefined` every time\n // (`g4/rulings/o2/receipts/leg-probe-mysql.log`). A RESULT is the\n // decoder's, and D-28's chain ends there.\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n\n parseField: (\n value: unknown,\n scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // MySQL stores booleans as TINYINT(1) - 0/1\n if (scalarType === \"boolean\") {\n const parsed = parseIntegerBoolean(\n value === \"0\" ? 0 : value === \"1\" ? 1 : value\n );\n if (parsed !== undefined) {\n return next(parsed);\n }\n }\n // Datetime strings are naive UTC wall-clock; without this, the default\n // parser's new Date(str) would shift them by the process timezone\n if (scalarType === \"datetime\" && typeof value === \"string\") {\n const iso = naiveDateTimeToIso(value);\n if (iso !== undefined) {\n return next(iso);\n }\n }\n return next();\n },\n };\n}\n"],"mappings":"o+BA6EA,MAAM,EAAa,EAAuB,IAAI,CACxC,EAAoB,MAAsC,UAAU,CAapE,EAAyC,CAQ7C,UAAW,EAAQ,IACjB,CAAG,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,oBAC1C,WAAY,EAAQ,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AI,IAAe,UAAW,CAC5B,IAAM,EAAS,EACb,IAAU,IAAM,EAAI,IAAU,IAAM,EAAI,EACzC,CACD,GAAI,IAAW,IAAA,GACb,OAAO,EAAK,EAAO,CAKvB,GAAI,IAAe,YAAc,OAAO,GAAU,SAAU,CAC1D,IAAM,EAAM,mBAAmB,EAAM,CACrC,GAAI,IAAQ,IAAA,GACV,OAAO,EAAK,EAAI,CAGpB,OAAO,GAAM,EAEhB"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{I as t}from"./error-mapping-B1-IWkCQ.mjs";import{f as n,y as r}from"./validation--qS7OPmg.mjs";import{t as i}from"./transaction-BNomMtme.mjs";import{n as a}from"./transaction-operation-CVVJxQ19.mjs";import{r as o,t as s}from"./routed-operations-wytpbYKv.mjs";import{o as c}from"./value-guards-CBuxSC66.mjs";import{i as l,n as u,r as d}from"./execution-context-BXpcbyPe.mjs";import{t as f}from"./adapter-result-parser-3WP82Cm-.mjs";import{n as p}from"./bind-parameter-capacity-BMD-bxMO.mjs";import{m}from"./validator-CZLW7aR3.mjs";import{n as h,t as g}from"./query-inspection-BoG-yAln.mjs";function compileBindBudgetChunks(e,t,n){if(e===0)return[];let r=n(0,e);if(t===void 0||r.values.length<=t||e===1)return[{start:0,end:e,statement:r}];let i=[],a=0;for(;a<e;){let r=a+1,o=Math.min(e,a+1),s;for(;;){let i=n(a,o);if(i.values.length>t||(s={start:a,end:o,statement:i},o===e))break;r=o+1,o=Math.min(e,a+(o-a)*2)}if(s?.end!==e)for(--o;r<=o;){let e=r+Math.floor((o-r)/2),i=n(a,e);i.values.length<=t?(s={start:a,end:e,statement:i},r=e+1):o=e-1}let c=s??{start:a,end:a+1,statement:n(a,a+1)};i.push(c),a=c.end}return i}const _=Symbol(`run alone`),v={string:e=>typeof e==`string`,int:e=>typeof e==`number`&&Number.isSafeInteger(e),bigint:e=>typeof e==`bigint`};let y;const b=new WeakSet;function enableFindUniqueBatching(e){b.add(e)}const x=(()=>{let e=globalThis.process,t=e?.nextTick;return typeof t==`function`?n=>t.call(e,n):queueMicrotask})();function batchFindUnique(e){if(!engineBatches(e.engine)||e.engine.driver.holdsConnectionScope())return;let t;try{t=e.routed.args}catch{return}let n=keyOf(e.model,t.where);if(n===void 0)return;let{where:r,...i}=e.args,a=signatureOf(i);if(a===void 0)return;let o,s=new Promise(e=>{o=e}),c,l=new Promise(e=>{c=e}),u={values:n.values,signature:signatureOf(n.values),orThrow:e.requested!==`findUnique`,decide:o};return(enqueue(e,`${n.selector}\u0000${a}`,n,u,c)?l.then(e=>(runBatch(e),s)):s).then(t=>t===_?e.run():t.value)}function engineBatches(e){let{driver:t}=e;return b.has(e.route)&&t===e.route.driver&&e.extensionChain?.rewrites===void 0&&t.result?.parseResult===void 0&&t.adapter.result.parseResult===f}function keyOf(e,t){if(!c(t))return;let n=Object.keys(t);if(n.length!==1)return;let r=n[0],i=m(e,r);if(i===void 0)return;let a=t[r],o;if(i.name===void 0)o=[a];else{if(!c(a)||Object.keys(a).length!==i.fields.length)return;o=i.fields.map(e=>a[e])}let{scalars:s,omit:l}=e[`~`].state,u=!1;for(let[e,t]of i.fields.entries()){let n=s[t]?.[`~`].state;if(!(n&&!n.array&&v[n.type])?.(o[e])||l?.[t]===!0)return;n.type===`string`&&(u=!0)}return{selector:r,fields:i.fields,values:o,textKey:u}}function enqueue(e,t,n,r,i){y===void 0&&(y=new Map,x(flush));let a=y.get(e.engine);a===void 0&&y.set(e.engine,a=new Map);let o=`${e.model[`~`].names.ts}\u0000${t}`,s=a.get(o);s===void 0&&a.set(o,s=[]);let c=s.find(t=>sameControls(t.leader.values,e.values)),l=!1;if(c===void 0){let t={leader:e,start:()=>i(t),fields:n.fields,textKey:n.textKey,members:[]};c=t,s.push(c),l=!0}return c.members.push(r),l}function sameControls(e,t){if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&e[n]===t[n])}function flush(){let e=y;y=void 0;for(let t of e.values())for(let e of t.values())for(let t of e)t.start()}function runBatch(e){let{members:n}=e,runAlone=e=>{for(let t of e)t.decide(_)};if(n.length===1){runAlone(n);return}try{let r=new Map;for(let e of n){let t=r.get(e.signature);t?t.push(e):r.set(e.signature,[e])}let i=planBatch(e,[...r.values()]),{engine:a}=e.leader,o=t(e.leader.context);for(let t of i.chunks){let n=t.signatures.flatMap(e=>r.get(e));t.read.run({committedWriteSegment:void 0,context:o,driverOverride:void 0,engineDriver:a.driver,isWrite:!1,writeMayBeVisible:void 0}).then(a=>{try{dispatch(e,t,r,i.injected,a)}catch{runAlone(n)}},()=>runAlone(n))}}catch{runAlone(n)}}function planBatch(e,t){let{leader:n,fields:r}=e,i=projectionWithKey(n,r),a=n.rows(),o=new Map,read=(e,s)=>{let c=`${e}:${s}`,l=o.get(c);if(l===void 0){let u=t.slice(e,s).map(e=>e[0].values);l=n.engine.route.prepare(n.model[`~`].names.ts,`findMany`,{...i.args,where:mergedWhere(r,u)},a),o.set(c,l)}return l},s=t.map(e=>e[0].signature),c=p(n.engine.driver.maxBindParametersPerStatement);return{chunks:(c===void 0?[{start:0,end:t.length}]:compileBindBudgetChunks(t.length,c,(e,t)=>read(e,t).read.statement)).map(({start:e,end:t})=>({signatures:s.slice(e,t),read:read(e,t)})),injected:i.injected}}function mergedWhere(e,t){return e.length===1?{[e[0]]:{in:t.map(e=>e[0])}}:{OR:t.map(t=>Object.fromEntries(e.map((e,n)=>[e,t[n]])))}}function projectionWithKey(e,t){let{where:n,...r}=e.args,i=e.routed.args.select,a=[];if(!c(i))return{args:r,injected:a};for(let e of t)i[e]!==!0&&(c(r.select)&&(r.select={...r.select,[e]:!0}),c(r.omit)&&(r.omit={...r.omit,[e]:!1}),a.push(e));return{args:r,injected:a}}function dispatch(e,t,n,r,i){let a=new Map;for(let t of i){let n=signatureOf(e.fields.map(e=>t[e]));for(let e of r)delete t[e];a.has(n)||a.set(n,t)}for(let r of t.signatures){let t=a.get(r);for(let[i,a]of n.get(r).entries())t===void 0?a.orThrow||e.textKey?a.decide(_):a.decide({value:null}):a.decide({value:i===0?t:copyResult(t)})}}function signatureOf(e){switch(typeof e){case`undefined`:return`u`;case`boolean`:case`number`:return String(e);case`string`:return JSON.stringify(e);case`bigint`:return`${e}n`;case`object`:break;default:return}if(e===null)return`null`;if(Array.isArray(e)){let t=[];for(let n of e){let e=signatureOf(n);if(e===void 0)return;t.push(e)}return`[${t.join(`,`)}]`}if(e instanceof Date)return`D${e.getTime()}`;let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return;let n=[];for(let[t,r]of Object.entries(e)){let e=signatureOf(r);if(e===void 0)return;n.push(`${JSON.stringify(t)}:${e}`)}return`{${n.join(`,`)}}`}function copyResult(e,t=new Map){if(typeof e!=`object`||!e)return e;let n=t.get(e);if(n!==void 0)return n;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Uint8Array)return Uint8Array.prototype.slice.call(e);if(Array.isArray(e)){let n=[];t.set(e,n);for(let r of e)n.push(copyResult(r,t));return n}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return e;let i=Object.create(r);t.set(e,i);for(let[n,r]of Object.entries(e))Object.defineProperty(i,n,{value:copyResult(r,t),enumerable:!0,writable:!0,configurable:!0});return i}const S=Symbol.for(`viborm.pendingOperation`);function combineWriteNotifications(e,t){return e===void 0?t:t===void 0||t===e?e:async()=>{let n=!1,i;try{await e()}catch(e){n=!0,i=e}try{await t()}catch(e){throw n?r(i,e,`Write publication callbacks both failed.`):e}if(n)throw i}}const C=Object.freeze({});let createPendingOperationFriend,w;var T=class PendingOperation{[Symbol.toStringTag]=`Promise`;[S]=!0;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d=!1;#f;#p;#m;#h;#g=!1;static{createPendingOperationFriend=(e,t,n,r,i,a,o)=>new PendingOperation(C,e,t,n,r,i,a===void 0?void 0:{prepare:a,status:`pending`},o),w=Object.freeze({clientId:e=>e.#e.clientId,scopeId:e=>e.#e.scopeId,model:e=>e.#i,operation:e=>e.#a,context:e=>e.#e.attribution,prepareAdmission:(e,t=`input`)=>{e.#S(),t===`plan`&&e.#x()},around:e=>{let t=String(e.#o.originalOperation),n=e.#t.extensionChain?.around?.handlers(e.#i,t);return{context:n?.length?e.#C(`array`,e.#S()):void 0,handlers:n,write:!o(t),registration:e.#v()}},executeCore:(e,t,n)=>e.#s.executeReserved(()=>e.#j(t,n?.committed,n?.mayHaveCommitted)),unit:e=>e.#E(),reserveWith:(e,t)=>{e.#s.reserveWith(t)},executeWith:(e,t)=>{let n=e.#t.extensionChain?.observation;return n===void 0?e.#s.executeWith(t,()=>e.#j(t)):e.#s.executeWith(t,()=>n.run(e.#E(!0),()=>e.#j(t)))},finishResult:(e,t)=>e.#o.finishResult?e.#o.finishResult(t):t,prepare:e=>e.#x()?.queries[0],prepareBatch:e=>e.#y().prepareBatch(e.#e.attribution),parseResult:(e,t)=>{let r=e.#x();if(!r)throw new n(`Operation '${e.#a}' on model '${e.#i}' publishes no single driver result to parse.`);return r.parseResult([t])},observeBatchPhase:(e,t,n)=>d(e.#e.attribution,t,n)}),a(PendingOperation.prototype,e=>#e in e,w),Object.freeze(PendingOperation.prototype)}constructor(e,t,n,r,a,o,s,c){if(e!==C)throw new i;this.#t=t,this.#n=n,this.#r=a,this.#c=s,this.#l=c,this.#p=t.route;let l=r.endsWith(`OrThrow`);this.#a=l?r.slice(0,-7):r,this.#i=n[`~`].names.ts??`unknown`,this.#s=new h(this.#i,this.#a),this.#o=Object.freeze({...o,throwIfNotFound:l||o?.throwIfNotFound,originalOperation:o?.originalOperation??r}),this.#e=u(this.#i,this.#a,t.clientId,t.scopeId,t.extensionChain),s&&(s.of={engine:t,context:this.#e.attribution,prepared:()=>this.#y()}),Object.freeze(this)}#_(){let e=this.#c;if(e===void 0)return this.#r;if(e.status===`success`&&e.args)return e.args;if(e.status===`failure`)throw e.error;try{let t=this.#t.extensionChain?.args?.admit(this.#i,String(this.#o.originalOperation),this.#a,this.#r,this.#t.bound),n=e.prepare(t?.args??this.#r,t?.values,e);return e.args=n,e.values=t?.values,e.status=`success`,n}catch(t){throw e.error=t,e.status=`failure`,t}}#v(){return this.#d?this.#u:(this.#u=this.#l?.(this.#e.attribution,this.#c?.values,this.#c),this.#d=!0,this.#u)}#y(){if(this.#m)return this.#m;if(!s.has(this.#a))throw new n(`Unknown operation '${this.#a}' on model '${this.#i}'. Known operations: ${[...s].sort().join(`, `)}.`);let e=this.#_();this.#v();let t=this.#p.prepare(this.#i,this.#o.originalOperation,e,this.#b());return this.#m=t,t}#b(){return(this.#t.extensionChain?.callRows)?.call(this.#i,this.#c?.values)}#x(){if(this.#g)return this.#h;let e=this.#y().prepareSingle(this.#e.attribution);return this.#h=e?.queries.length===1?e:void 0,this.#g=!0,this.#h}#S(){return this.#y().args}#C(e,t){let n=this.#c?.values,r;return Object.freeze({mode:e,kind:`model`,model:this.#i,operation:String(this.#o.originalOperation),get input(){return r??=g(t),r},...n===void 0?{}:{values:n},call:this.#c})}#w(){return this.#s.executeDefault(()=>{let e=this.#t.extensionChain?.observation;return e===void 0?this.#T(this.#D()):e.run(this.#E(!0),()=>this.#T(this.#D()))})}#T(e){let t=this.#o.finishResult;return t?e.then(e=>t(e)):e}#E(e){return{kind:`operation`,operation:String(this.#o.originalOperation),model:this.#i,context:this.#e.attribution,driver:this.#t.driver,table:this.#n[`~`].names.sql??this.#i,...e?{certainty:()=>this.#f}:{}}}#D(e,t,n){return l(this.#e.attribution,()=>this.#O(e,t,n))}#O(e,t,n){let r=this.#A(`committed`),i=this.#A(`may-have-committed`),a=String(this.#o.originalOperation),o=this.#t.extensionChain?.around?.handlers(this.#i,a);return(o===void 0||o.length===0)&&this.#l===void 0?this.#j(e,combineWriteNotifications(t,r),combineWriteNotifications(n,i)):this.#k(o,a,r,i,e,t,n)}#k(e,t,n,r,i,a,s){let c;try{c=this.#S()}catch(e){return Promise.reject(e)}let l=this.#v(),u=this.#t.extensionChain?.coordination;if(u===void 0||(e===void 0||e.length===0)&&l===void 0)return this.#j(i,combineWriteNotifications(a,n),combineWriteNotifications(s,r));let d=e===void 0||e.length===0?void 0:this.#C(this.#t.transaction?`transaction`:`direct`,c);return u.executePreparedQuery(d,e,(e,t)=>this.#j(t??i,combineWriteNotifications(a,combineWriteNotifications(e?.committed,n)),combineWriteNotifications(s,combineWriteNotifications(e?.mayHaveCommitted,r))),!o(t),this.#t.transaction,void 0,l)}#A(e){if(!(this.#t.transaction!==void 0||this.#t.extensionChain?.observation===void 0))return async()=>{(e===`committed`||this.#f===void 0)&&(this.#f=e)}}#j(e,t,n){return this.#M(e,t,n)}#M(e,t,n){let r;try{r=this.#y()}catch(e){return Promise.reject(e)}let run=()=>r.run({committedWriteSegment:t,context:this.#e.attribution,driverOverride:e,engineDriver:this.#t.driver,isWrite:!o(String(this.#o.originalOperation)),writeMayBeVisible:n});if(this.#a===`findUnique`&&e===void 0&&r.seen===void 0){let e=batchFindUnique({engine:this.#t,model:this.#n,requested:String(this.#o.originalOperation),args:this.#_(),values:this.#c?.values,rows:()=>this.#b(),routed:r,context:this.#e.attribution,run});if(e!==void 0)return e}return run()}getArgs(){return this.#r}buildStatement(){return this.#y().read?.statement}then(e,t){return this.#w().then(e,t)}catch(e){return this.#w().catch(e)}finally(e){return this.#w().finally(e)}};function createPendingOperation(e,t,n,r,i,a,o){return createPendingOperationFriend(e,t,n,r,i,a,o)}function isPendingOperation(e){return typeof e==`object`&&!!e&&S in e&&e[S]===!0}export{compileBindBudgetChunks as a,enableFindUniqueBatching as i,createPendingOperation as n,isPendingOperation as r,T as t};
|
|
2
|
-
//# sourceMappingURL=pending-operation-C_eOFOBE.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"pending-operation-C_eOFOBE.mjs","names":["copy","#context","#engine","#model","#args","#modelName","#operation","#options","#execution","#inputPreparation","#prepareWriteOutcomeRegistration","#route","#preparedInput","#resolveSinglePackage","#queryContext","#resolveWriteOutcomeRegistration","#runCoreExecution","#unit","#resolveRouted","#writeOutcomeRegistrationResolved","#writeOutcomeRegistration","#routedInstance","#resolveArgs","#callRows","#singlePackageResolved","#singlePackage","#finished","#runExecution","#observationCommitCertainty","#runAttributedExecution","#observationNotification","#runExtendedExecution","#run","#getPromise"],"sources":["../src/query-engine/bind-budget.ts","../src/query-engine/find-unique-batch.ts","../src/query-engine/pending-operation.ts"],"sourcesContent":["import type { Sql } from \"@sql\";\n\nexport { normalizedBindParameterLimit } from \"@drivers/bind-parameter-capacity\";\n\nexport interface CompiledBindBudgetChunk {\n /** Inclusive semantic-item offset. */\n readonly start: number;\n /** Exclusive semantic-item offset. */\n readonly end: number;\n readonly statement: Sql;\n}\n\n/**\n * Compile the largest contiguous semantic-item ranges that fit a verified bind\n * budget. The compiled SQL is the meter; callers do not estimate binds from\n * item count or shape. `compile` must be monotonic for a growing prefix, as\n * INSERT value tuples and exact-key predicate lists are.\n *\n * Unknown capacity preserves the original one-statement shape. One item that\n * exceeds a known budget stays indivisible so the executor's final capacity\n * check can refuse it before I/O.\n */\nexport function compileBindBudgetChunks(\n itemCount: number,\n maxBindParametersPerStatement: number | undefined,\n compile: (start: number, end: number) => Sql\n): CompiledBindBudgetChunk[] {\n if (itemCount === 0) return [];\n const whole = compile(0, itemCount);\n if (\n maxBindParametersPerStatement === undefined ||\n whole.values.length <= maxBindParametersPerStatement ||\n itemCount === 1\n ) {\n return [{ start: 0, end: itemCount, statement: whole }];\n }\n\n const chunks: CompiledBindBudgetChunk[] = [];\n let start = 0;\n while (start < itemCount) {\n let lower = start + 1;\n let upper = Math.min(itemCount, start + 1);\n let largest: CompiledBindBudgetChunk | undefined;\n // Probe geometrically from this window, never from the entire remaining\n // suffix. Oversized compilation stays proportional to a window's size.\n while (true) {\n const statement = compile(start, upper);\n if (statement.values.length > maxBindParametersPerStatement) break;\n largest = { start, end: upper, statement };\n if (upper === itemCount) break;\n lower = upper + 1;\n upper = Math.min(itemCount, start + (upper - start) * 2);\n }\n if (largest?.end !== itemCount) {\n upper -= 1;\n while (lower <= upper) {\n const end = lower + Math.floor((upper - lower) / 2);\n const statement = compile(start, end);\n if (statement.values.length <= maxBindParametersPerStatement) {\n largest = { start, end, statement };\n lower = end + 1;\n } else upper = end - 1;\n }\n }\n const chunk = largest ?? {\n start,\n end: start + 1,\n statement: compile(start, start + 1),\n };\n chunks.push(chunk);\n start = chunk.end;\n }\n return chunks;\n}\n","/**\n * `findUnique` batching: Prisma's dataloader, at the operation dispatch layer.\n *\n * Opt-in (`createClient({ findUniqueBatching: true })`, 1.4.1): calls issued\n * in the same tick that would each cost one round trip are answered by ONE\n * `findMany` over the keys they name, and each caller gets its own row back.\n * The shared read runs in its leader's own async context (the first call of\n * its batch), which may not be every member's: a driver that picks a database\n * by `AsyncLocalStorage`, or a trace per request, sees the leader's. That is\n * why it is opt-in. The merge happens below every per-call lifecycle step — request\n * transforms, arguments, default omit, admission, query interceptors, the\n * official cache and observers all still see each call as its own operation —\n * and above the route, which runs the merged read like any other read.\n *\n * Two calls share a batch only when nothing that decides their rows differs:\n * the same engine (so the same client view, extension chain and bound\n * arguments), outside every transaction, the same model, the same unique key\n * spelled the same way, the same projection (`select`/`include`/`omit`, nested\n * arguments included, compared structurally) and the same admitted arguments.\n * The `where` must be the key alone: a value per member, nothing else.\n *\n * A row reaches a caller only when its decoded key is EXACTLY the caller's\n * admitted key. Whatever cannot be decided that way runs as the caller's own\n * unbatched operation, so a batch can cost a statement but never change an\n * answer:\n * - a string key without an exact match (a case-insensitive or padding\n * collation can make the database find a row JavaScript does not match);\n * - a missing row for `findUniqueOrThrow` (its own error comes from its owner);\n * - a merged read that fails, for every caller of that read.\n * Only string, integer and bigint key members are batched. An integer or\n * bigint member's decoded value is its bound value, so a row JavaScript does\n * not match is a row the database did not return either: a missing integer\n * key answers `null` from the batch.\n */\n\nimport { passThroughParseResult } from \"@adapters/adapter-result-parser\";\nimport { normalizedBindParameterLimit } from \"@drivers/bind-parameter-capacity\";\nimport { deriveRecoverableExecutionContext } from \"@drivers/execution-context\";\nimport type { QueryExecutionContext } from \"@drivers/exports\";\nimport type { AdmittedArgs } from \"@extensions/arguments\";\nimport type { AnyModel } from \"@schema/model\";\nimport { findAddressableKey } from \"@schema/model/keys\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { compileBindBudgetChunks } from \"./bind-budget\";\nimport type { QueryEngine } from \"./query-engine\";\nimport type { PreparedOperation } from \"./raptor3/commands\";\nimport type { CallRows } from \"./raptor3/shared/row-scope\";\n\n/** One `findUnique` call, as its pending operation knows it at dispatch. */\nexport interface FindUniqueCall {\n readonly engine: QueryEngine;\n readonly model: AnyModel;\n /** `findUnique` or `findUniqueOrThrow`. */\n readonly requested: string;\n /** The client-prepared input: arguments removed, request transforms applied. */\n readonly args: Record<string, unknown>;\n readonly values: AdmittedArgs | undefined;\n /** The call's own row domain, resolved for the batch that runs it. */\n readonly rows: () => CallRows | undefined;\n readonly routed: PreparedOperation;\n readonly context: QueryExecutionContext;\n /** The call's own, unbatched execution. */\n readonly run: () => Promise<unknown>;\n}\n\n/** What a batch decided for one caller. */\ntype Decision = { readonly value: unknown } | typeof RUN_ALONE;\nconst RUN_ALONE = Symbol(\"run alone\");\n\ninterface Member {\n readonly values: readonly unknown[];\n readonly signature: string;\n readonly orThrow: boolean;\n readonly decide: (decision: Decision) => void;\n}\n\ninterface Batch {\n readonly leader: FindUniqueCall;\n /** Starts the batch in its leader's own continuation (its async context). */\n readonly start: () => void;\n readonly fields: readonly string[];\n readonly textKey: boolean;\n readonly members: Member[];\n}\n\n/** Key members whose decoded value is the bound value, by scalar type. */\nconst EXACT_KEY_VALUES: Readonly<Record<string, (value: unknown) => boolean>> =\n {\n string: (value) => typeof value === \"string\",\n int: (value) => typeof value === \"number\" && Number.isSafeInteger(value),\n bigint: (value) => typeof value === \"bigint\",\n };\n\nlet pending: Map<QueryEngine, Map<string, Batch[]>> | undefined;\n\n/** The operation routes of the clients created with `findUniqueBatching`. */\nconst batchingRoutes = new WeakSet<object>();\n\n/** Turn batching on for every engine of the client that owns `route`. */\nexport function enableFindUniqueBatching(route: object): void {\n batchingRoutes.add(route);\n}\n\n/**\n * After the current synchronous run AND the microtasks it queued, so resolvers\n * that each await once before calling still share a batch. Where there is no\n * `process.nextTick`, the end of the current synchronous run.\n */\nconst defer: (callback: () => void) => void = (() => {\n const host = (\n globalThis as {\n process?: { nextTick?: (callback: () => void) => void };\n }\n ).process;\n const nextTick = host?.nextTick;\n return typeof nextTick === \"function\"\n ? (callback) => nextTick.call(host, callback)\n : queueMicrotask;\n})();\n\n/**\n * Join a batch, or answer `undefined` when this call does not batch and must\n * run as it always has.\n */\nexport function batchFindUnique(\n call: FindUniqueCall\n): Promise<unknown> | undefined {\n // A call on the originating client inside its own callback transaction\n // runs alone, and is refused there as it always was: in a batch, the shared\n // read would queue behind the transaction that waits for this call.\n if (!engineBatches(call.engine) || call.engine.driver.holdsConnectionScope())\n return undefined;\n let admitted: Record<string, unknown>;\n try {\n admitted = call.routed.args;\n } catch {\n // The call's own execution admits again and rejects with the same error.\n return undefined;\n }\n const key = keyOf(call.model, admitted.where);\n if (key === undefined) return undefined;\n const { where: _where, ...projection } = call.args;\n const shape = signatureOf(projection);\n if (shape === undefined) return undefined;\n\n let decide!: (decision: Decision) => void;\n const decision = new Promise<Decision>((resolve) => {\n decide = resolve;\n });\n let lead!: (batch: Batch) => void;\n const leading = new Promise<Batch>((resolve) => {\n lead = resolve;\n });\n const member: Member = {\n values: key.values,\n signature: signatureOf(key.values)!,\n orThrow: call.requested !== \"findUnique\",\n decide,\n };\n const leads = enqueue(\n call,\n `${key.selector}\\u0000${shape}`,\n key,\n member,\n lead\n );\n // Continuations run in the async context of the call that registered them:\n // the leader runs its batch in its own, and a call that runs alone runs in\n // its own. The tick's flush runs in whichever context queued first, and\n // only starts batches.\n const settled = leads\n ? leading.then((batch) => {\n runBatch(batch);\n return decision;\n })\n : decision;\n return settled.then((outcome) =>\n outcome === RUN_ALONE ? call.run() : outcome.value\n );\n}\n\n/**\n * The engine runs outside every transaction scope, and nothing below the\n * operation is keyed on the statement or the operation name: a statement\n * transform sees `findUnique`, and a result middleware is handed the operation\n * name, so either would observe the merged `findMany`.\n */\nfunction engineBatches(engine: QueryEngine): boolean {\n const { driver } = engine;\n return (\n batchingRoutes.has(engine.route) &&\n driver === engine.route.driver &&\n engine.extensionChain?.rewrites === undefined &&\n driver.result?.parseResult === undefined &&\n driver.adapter.result.parseResult === passThroughParseResult\n );\n}\n\ninterface BatchKey {\n readonly selector: string;\n readonly fields: readonly string[];\n readonly values: readonly unknown[];\n readonly textKey: boolean;\n}\n\n/** The admitted `where` as one addressable key and nothing else, or nothing. */\nfunction keyOf(model: AnyModel, where: unknown): BatchKey | undefined {\n if (!isRecord(where)) return undefined;\n const selectors = Object.keys(where);\n if (selectors.length !== 1) return undefined;\n const selector = selectors[0]!;\n const key = findAddressableKey(model, selector);\n if (key === undefined) return undefined;\n const value = where[selector];\n let values: unknown[];\n if (key.name === undefined) values = [value];\n else {\n if (!isRecord(value) || Object.keys(value).length !== key.fields.length)\n return undefined;\n values = key.fields.map((field) => value[field]);\n }\n // A member the model hides from every result cannot be read back to\n // dispatch a row, and no call may select it.\n const { scalars, omit } = model[\"~\"].state;\n let textKey = false;\n for (const [index, field] of key.fields.entries()) {\n const state = scalars[field]?.[\"~\"].state;\n const exact = state && !state.array && EXACT_KEY_VALUES[state.type];\n if (!exact?.(values[index]) || omit?.[field] === true) return undefined;\n if (state.type === \"string\") textKey = true;\n }\n return { selector, fields: key.fields, values, textKey };\n}\n\n/** Join or open a batch; `true` when this call opened it and leads it. */\nfunction enqueue(\n call: FindUniqueCall,\n shape: string,\n key: BatchKey,\n member: Member,\n lead: (batch: Batch) => void\n): boolean {\n if (pending === undefined) {\n pending = new Map();\n defer(flush);\n }\n let byShape = pending.get(call.engine);\n if (byShape === undefined) pending.set(call.engine, (byShape = new Map()));\n const signature = `${call.model[\"~\"].names.ts}\\u0000${shape}`;\n let batches = byShape.get(signature);\n if (batches === undefined) byShape.set(signature, (batches = []));\n let batch = batches.find((candidate) =>\n sameControls(candidate.leader.values, call.values)\n );\n let leads = false;\n if (batch === undefined) {\n const opened: Batch = {\n leader: call,\n start: () => lead(opened),\n fields: key.fields,\n textKey: key.textKey,\n members: [],\n };\n batch = opened;\n batches.push(batch);\n leads = true;\n }\n batch.members.push(member);\n return leads;\n}\n\n/** Admitted arguments decide the row domain: the same values, the same rows. */\nfunction sameControls(\n first: AdmittedArgs | undefined,\n second: AdmittedArgs | undefined\n): boolean {\n if (first === second) return true;\n if (first === undefined || second === undefined) return false;\n const names = Object.keys(first);\n return (\n names.length === Object.keys(second).length &&\n names.every(\n (name) => Object.hasOwn(second, name) && first[name] === second[name]\n )\n );\n}\n\nfunction flush(): void {\n const batches = pending;\n pending = undefined;\n for (const byShape of batches!.values())\n for (const list of byShape.values())\n for (const batch of list) batch.start();\n}\n\ninterface Chunk {\n readonly signatures: readonly string[];\n readonly read: PreparedOperation;\n}\n\n/**\n * Run one batch. Whatever goes wrong before a caller's row is decided sends\n * that caller back to its own execution; a caller is decided once, so a later\n * decision never replaces an earlier one.\n */\nfunction runBatch(batch: Batch): void {\n const { members } = batch;\n const runAlone = (callers: readonly Member[]) => {\n for (const member of callers) member.decide(RUN_ALONE);\n };\n if (members.length === 1) {\n runAlone(members);\n return;\n }\n try {\n const bySignature = new Map<string, Member[]>();\n for (const member of members) {\n const same = bySignature.get(member.signature);\n if (same) same.push(member);\n else bySignature.set(member.signature, [member]);\n }\n const plan = planBatch(batch, [...bySignature.values()]);\n const { engine } = batch.leader;\n // Its callers recover a failure by running alone, so the shared read's\n // own failure is not logged or traced as an error.\n const context = deriveRecoverableExecutionContext(batch.leader.context);\n for (const chunk of plan.chunks) {\n const callers = chunk.signatures.flatMap((key) => bySignature.get(key)!);\n (\n chunk.read.run({\n committedWriteSegment: undefined,\n context,\n driverOverride: undefined,\n engineDriver: engine.driver,\n isWrite: false,\n writeMayBeVisible: undefined,\n }) as Promise<Record<string, unknown>[]>\n ).then(\n (rows) => {\n try {\n dispatch(batch, chunk, bySignature, plan.injected, rows);\n } catch {\n runAlone(callers);\n }\n },\n () => runAlone(callers)\n );\n }\n } catch {\n runAlone(members);\n }\n}\n\n/**\n * The merged reads, split where the driver's bind budget requires, through the\n * one chunking owner: the compiled statement is the meter.\n */\nfunction planBatch(\n batch: Batch,\n keys: readonly (readonly Member[])[]\n): { chunks: Chunk[]; injected: readonly string[] } {\n const { leader, fields } = batch;\n const projected = projectionWithKey(leader, fields);\n const rows = leader.rows();\n const reads = new Map<string, PreparedOperation>();\n const read = (start: number, end: number): PreparedOperation => {\n const id = `${start}:${end}`;\n let operation = reads.get(id);\n if (operation === undefined) {\n const values = keys.slice(start, end).map((same) => same[0]!.values);\n operation = leader.engine.route.prepare(\n leader.model[\"~\"].names.ts!,\n \"findMany\",\n { ...projected.args, where: mergedWhere(fields, values) },\n rows\n );\n reads.set(id, operation);\n }\n return operation;\n };\n const signatures = keys.map((same) => same[0]!.signature);\n const limit = normalizedBindParameterLimit(\n leader.engine.driver.maxBindParametersPerStatement\n );\n const ranges =\n limit === undefined\n ? [{ start: 0, end: keys.length }]\n : compileBindBudgetChunks(\n keys.length,\n limit,\n (start, end) => read(start, end).read!.statement\n );\n return {\n chunks: ranges.map(({ start, end }) => ({\n signatures: signatures.slice(start, end),\n read: read(start, end),\n })),\n injected: projected.injected,\n };\n}\n\n/** One key member: `IN`; a compound key: one equality group per key. */\nfunction mergedWhere(\n fields: readonly string[],\n values: readonly (readonly unknown[])[]\n): Record<string, unknown> {\n if (fields.length === 1)\n return { [fields[0]!]: { in: values.map((value) => value[0]) } };\n return {\n OR: values.map((value) =>\n Object.fromEntries(fields.map((field, index) => [field, value[index]]))\n ),\n };\n}\n\n/**\n * The leader's projection with every key member read, so each row can be\n * dispatched; a member the caller does not read is removed again before the\n * row is handed over. A member can be missing because it is not selected or\n * because it is omitted (an omit wins over a select), so both are lifted.\n */\nfunction projectionWithKey(\n leader: FindUniqueCall,\n fields: readonly string[]\n): { args: Record<string, unknown>; injected: string[] } {\n const { where: _where, ...args } = leader.args;\n const selected = leader.routed.args.select;\n const injected: string[] = [];\n if (!isRecord(selected)) return { args, injected };\n for (const field of fields) {\n if (selected[field] === true) continue;\n if (isRecord(args.select)) args.select = { ...args.select, [field]: true };\n if (isRecord(args.omit)) args.omit = { ...args.omit, [field]: false };\n injected.push(field);\n }\n return { args, injected };\n}\n\nfunction dispatch(\n batch: Batch,\n chunk: Chunk,\n bySignature: ReadonlyMap<string, readonly Member[]>,\n injected: readonly string[],\n rows: readonly Record<string, unknown>[]\n): void {\n const found = new Map<string | undefined, Record<string, unknown>>();\n for (const row of rows) {\n const signature = signatureOf(batch.fields.map((field) => row[field]));\n for (const field of injected) delete row[field];\n if (!found.has(signature)) found.set(signature, row);\n }\n for (const signature of chunk.signatures) {\n const row = found.get(signature);\n for (const [index, member] of bySignature.get(signature)!.entries()) {\n if (row !== undefined)\n member.decide({ value: index === 0 ? row : copyResult(row) });\n else if (member.orThrow || batch.textKey) member.decide(RUN_ALONE);\n else member.decide({ value: null });\n }\n }\n}\n\n/**\n * A structural signature of plain argument data: equal signatures, equal\n * arguments. Anything else (a function, a fragment, a class instance) has\n * none, and the call does not batch.\n */\nfunction signatureOf(value: unknown): string | undefined {\n switch (typeof value) {\n case \"undefined\":\n return \"u\";\n case \"boolean\":\n case \"number\":\n return String(value);\n case \"string\":\n return JSON.stringify(value);\n case \"bigint\":\n return `${value}n`;\n case \"object\":\n break;\n default:\n return undefined;\n }\n if (value === null) return \"null\";\n if (Array.isArray(value)) {\n const items: string[] = [];\n for (const item of value) {\n const signature = signatureOf(item);\n if (signature === undefined) return undefined;\n items.push(signature);\n }\n return `[${items.join(\",\")}]`;\n }\n if (value instanceof Date) return `D${value.getTime()}`;\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return undefined;\n const entries: string[] = [];\n for (const [name, entry] of Object.entries(value)) {\n const signature = signatureOf(entry);\n if (signature === undefined) return undefined;\n entries.push(`${JSON.stringify(name)}:${signature}`);\n }\n return `{${entries.join(\",\")}}`;\n}\n\n/**\n * A second caller of the same key gets its own result, as it would have\n * unbatched: plain objects, arrays, dates and byte arrays are copied, keeping\n * the shape of what is shared inside the result (a node reached twice is one\n * copy); an immutable value (a Decimal) is shared. Members are defined, never\n * assigned, so a JSON key named `__proto__` stays an own member.\n */\nfunction copyResult(\n value: unknown,\n copies = new Map<object, unknown>()\n): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n const known = copies.get(value);\n if (known !== undefined) return known;\n if (value instanceof Date) return new Date(value.getTime());\n if (value instanceof Uint8Array)\n return Uint8Array.prototype.slice.call(value);\n if (Array.isArray(value)) {\n const copy: unknown[] = [];\n copies.set(value, copy);\n for (const item of value) copy.push(copyResult(item, copies));\n return copy;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return value;\n const copy = Object.create(prototype) as object;\n copies.set(value, copy);\n for (const [name, entry] of Object.entries(value))\n Object.defineProperty(copy, name, {\n value: copyResult(entry, copies),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n return copy;\n}\n","/**\n * Deferred operation lifecycle owned by the query engine.\n * Validation, SQL construction, and execution remain lazy until a lifecycle\n * method is called. Every operation is served by the single (V2) engine.\n */\n\nimport type { AnyDriver, QueryExecutionContext } from \"@drivers/exports\";\nimport {\n InvalidTransactionInputError,\n retainWriteOutcomeFailure,\n} from \"@errors\";\nimport type { AdmittedArgs } from \"@extensions/arguments\";\nimport type { CallOrigin } from \"@extensions/origin\";\nimport type {\n AroundHandlers,\n CallMode,\n PreparedModelQueryContext,\n WriteOutcomeRegistration,\n} from \"@extensions/query\";\nimport type { UnitSource } from \"@extensions/unit-source\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { Sql } from \"@sql\";\nimport {\n createPendingOperationContext,\n type OperationExecutionContext,\n observeTransactionBatchPhase,\n withOperationErrorContext,\n} from \"./execution-context\";\nimport { batchFindUnique } from \"./find-unique-batch\";\nimport { PendingExecution } from \"./pending-execution\";\nimport type { QueryEngine } from \"./query-engine\";\nimport { snapshotQueryInput } from \"./query-inspection\";\nimport type { CommandEngine, PreparedOperation } from \"./raptor3/commands\";\nimport { isReadOperation, ROUTED_OPERATIONS } from \"./routed-operations\";\nimport {\n registerTransactionOperationOwner,\n type TransactionOperation,\n type TransactionOperationOwner,\n} from \"./transaction-operation\";\nimport {\n type Operation,\n type PreparedBatchOperation,\n type PrepareOptions,\n QueryEngineError,\n} from \"./types\";\n\nexport const PENDING_OPERATION_SYMBOL = Symbol.for(\"viborm.pendingOperation\");\n\n/** Publish a durably committed write segment to the cache and observers. */\nexport type CommittedWriteSegmentNotification = () => Promise<void>;\n/** Conservatively invalidate after dispatch when provider acknowledgement is ambiguous. */\nexport type WriteMayBeVisibleNotification = () => Promise<void>;\n\nfunction combineWriteNotifications(\n first: (() => Promise<void>) | undefined,\n second: (() => Promise<void>) | undefined\n): (() => Promise<void>) | undefined {\n if (first === undefined) return second;\n if (second === undefined || second === first) return first;\n return async () => {\n let firstFailed = false;\n let firstFailure: unknown;\n try {\n await first();\n } catch (error) {\n firstFailed = true;\n firstFailure = error;\n }\n try {\n await second();\n } catch (error) {\n if (firstFailed) {\n throw retainWriteOutcomeFailure(\n firstFailure,\n error,\n \"Write publication callbacks both failed.\"\n );\n }\n throw error;\n }\n if (firstFailed) throw firstFailure;\n };\n}\n\n/**\n * Client-owned work that must finish before operation construction starts. It\n * receives the call's arguments without the ones extensions declare (`args`),\n * and the values admitted from those.\n */\nexport type PrepareOperationInput = (\n args: Record<string, unknown>,\n values: AdmittedArgs | undefined,\n /** One object per call: what an extension's two moments of it share. */\n call: object\n) => Record<string, unknown>;\n\n/** Package-owned write listener prepared only after the operation input is trusted. */\nexport type PrepareWriteOutcomeRegistration = (\n context: QueryExecutionContext,\n values: AdmittedArgs | undefined,\n call: object | undefined\n) => WriteOutcomeRegistration | undefined;\n\ninterface OperationInputPreparation extends CallOrigin {\n readonly prepare: PrepareOperationInput;\n status: \"pending\" | \"success\" | \"failure\";\n args?: Record<string, unknown>;\n /** The operation's one admission record, settled with its arguments. */\n values?: AdmittedArgs;\n error?: unknown;\n}\n\ntype ResolvedPrepareOptions = Readonly<\n PrepareOptions & { readonly originalOperation: string }\n>;\n\nconst OR_THROW_SUFFIX = \"OrThrow\";\nconst pendingOperationConstruction = Object.freeze({});\n\ntype CreatePendingOperation = <T>(\n engine: QueryEngine,\n model: AnyModel,\n operation: Operation | `${Operation}OrThrow`,\n args: Record<string, unknown>,\n options?: PrepareOptions,\n prepareInput?: PrepareOperationInput,\n prepareWriteOutcomeRegistration?: PrepareWriteOutcomeRegistration\n) => PendingOperation<T>;\n\nlet createPendingOperationFriend: CreatePendingOperation;\n\nlet pendingOperationTransactionOwner: TransactionOperationOwner<\n PendingOperation<unknown>\n>;\n\n/** One user operation, from lazy creation through execution and parsing. */\nexport class PendingOperation<T>\n implements Promise<T>, TransactionOperation<T>\n{\n readonly [Symbol.toStringTag] = \"Promise\";\n readonly [PENDING_OPERATION_SYMBOL] = true;\n readonly #context: OperationExecutionContext;\n readonly #engine: QueryEngine;\n readonly #model: AnyModel;\n readonly #args: Record<string, unknown>;\n readonly #modelName: string;\n readonly #operation: Operation;\n readonly #options: ResolvedPrepareOptions;\n\n readonly #execution: PendingExecution<T>;\n readonly #inputPreparation: OperationInputPreparation | undefined;\n readonly #prepareWriteOutcomeRegistration:\n | PrepareWriteOutcomeRegistration\n | undefined;\n #writeOutcomeRegistration: WriteOutcomeRegistration | undefined;\n #writeOutcomeRegistrationResolved = false;\n #observationCommitCertainty: \"committed\" | \"may-have-committed\" | undefined;\n\n // The ONE operation owner (C-01). Every client lineage builds it in\n // `VibORM`'s constructor and `bind()` forwards it, so an operation that was\n // created from a client has one.\n readonly #route: CommandEngine;\n #routedInstance: PreparedOperation | undefined;\n #singlePackage: PreparedBatchOperation<unknown> | undefined;\n #singlePackageResolved = false;\n\n static {\n createPendingOperationFriend = <T>(\n engine: QueryEngine,\n model: AnyModel,\n operation: Operation | `${Operation}OrThrow`,\n args: Record<string, unknown>,\n options?: PrepareOptions,\n prepareInput?: PrepareOperationInput,\n prepareWriteOutcomeRegistration?: PrepareWriteOutcomeRegistration\n ) =>\n new PendingOperation<T>(\n pendingOperationConstruction,\n engine,\n model,\n operation,\n args,\n options,\n prepareInput === undefined\n ? undefined\n : { prepare: prepareInput, status: \"pending\" },\n prepareWriteOutcomeRegistration\n );\n pendingOperationTransactionOwner = Object.freeze({\n clientId: (operation) => operation.#context.clientId,\n scopeId: (operation) => operation.#context.scopeId,\n model: (operation) => operation.#modelName,\n operation: (operation) => operation.#operation,\n context: (operation) => operation.#context.attribution,\n prepareAdmission: (operation, phase = \"input\") => {\n operation.#preparedInput();\n if (phase === \"plan\") operation.#resolveSinglePackage();\n },\n around: (operation) => {\n const requestedOperation = String(operation.#options.originalOperation);\n const handlers = operation.#engine.extensionChain?.around?.handlers(\n operation.#modelName,\n requestedOperation\n );\n return {\n context: handlers?.length\n ? operation.#queryContext(\"array\", operation.#preparedInput())\n : undefined,\n handlers,\n write: !isReadOperation(requestedOperation),\n registration: operation.#resolveWriteOutcomeRegistration(),\n };\n },\n executeCore: (operation, driver, notifications) =>\n operation.#execution.executeReserved(() =>\n operation.#runCoreExecution(\n driver,\n notifications?.committed,\n notifications?.mayHaveCommitted\n )\n ),\n unit: (operation) => operation.#unit(),\n reserveWith: (operation, driver) => {\n operation.#execution.reserveWith(driver);\n },\n executeWith: (operation, driver) => {\n const observation = operation.#engine.extensionChain?.observation;\n if (observation === undefined) {\n return operation.#execution.executeWith(driver, () =>\n operation.#runCoreExecution(driver)\n );\n }\n return operation.#execution.executeWith(driver, () =>\n observation.run(operation.#unit(true), () =>\n operation.#runCoreExecution(driver)\n )\n );\n },\n // One preparation answers both arms: the package this operation prepares\n // to synchronously publishes the one query and the parser for its one\n // result. A verb that needs the asynchronous fold publishes no single\n // query, and the array owner asks it for the package instead.\n finishResult: (operation, value) =>\n operation.#options.finishResult\n ? operation.#options.finishResult(value)\n : value,\n prepare: (operation) => operation.#resolveSinglePackage()?.queries[0],\n prepareBatch: (operation) =>\n operation.#resolveRouted().prepareBatch(operation.#context.attribution),\n parseResult: (operation, raw) => {\n const single = operation.#resolveSinglePackage();\n if (!single) {\n throw new QueryEngineError(\n `Operation '${operation.#operation}' on model '${operation.#modelName}' publishes no single driver result to parse.`\n );\n }\n return single.parseResult([raw]);\n },\n observeBatchPhase: (operation, driver, execute) =>\n observeTransactionBatchPhase(\n operation.#context.attribution,\n driver,\n execute\n ),\n } satisfies TransactionOperationOwner<PendingOperation<unknown>>);\n registerTransactionOperationOwner(\n PendingOperation.prototype,\n (value): value is PendingOperation<unknown> => #context in value,\n pendingOperationTransactionOwner\n );\n Object.freeze(PendingOperation.prototype);\n }\n\n private constructor(\n construction: typeof pendingOperationConstruction,\n engine: QueryEngine,\n model: AnyModel,\n requestedOperation: Operation | `${Operation}OrThrow`,\n args: Record<string, unknown>,\n options?: PrepareOptions,\n inputPreparation?: OperationInputPreparation,\n prepareWriteOutcomeRegistration?: PrepareWriteOutcomeRegistration\n ) {\n if (construction !== pendingOperationConstruction) {\n throw new InvalidTransactionInputError();\n }\n this.#engine = engine;\n this.#model = model;\n this.#args = args;\n this.#inputPreparation = inputPreparation;\n this.#prepareWriteOutcomeRegistration = prepareWriteOutcomeRegistration;\n // Every client lineage installs the route in `VibORM`'s constructor and\n // `bind()` forwards it (C-01); an engine built outside that lineage owns no\n // operation path at all.\n this.#route = engine.route;\n const isOrThrow = requestedOperation.endsWith(OR_THROW_SUFFIX);\n this.#operation = isOrThrow\n ? (requestedOperation.slice(0, -OR_THROW_SUFFIX.length) as Operation)\n : (requestedOperation as Operation);\n this.#modelName = model[\"~\"].names.ts ?? \"unknown\";\n this.#execution = new PendingExecution<T>(this.#modelName, this.#operation);\n this.#options = Object.freeze({\n ...options,\n throwIfNotFound: isOrThrow || options?.throwIfNotFound,\n originalOperation: options?.originalOperation ?? requestedOperation,\n });\n this.#context = createPendingOperationContext(\n this.#modelName,\n this.#operation,\n engine.clientId,\n engine.scopeId,\n engine.extensionChain\n );\n // The call object an extension's moments share is where the words on the\n // call (`key`, `codec`, `database`) find the operation it became.\n if (inputPreparation)\n inputPreparation.of = {\n engine,\n context: this.#context.attribution,\n prepared: () => this.#resolveRouted(),\n };\n Object.freeze(this);\n }\n\n /**\n * Resolve client request preparation once, caching both values and throws.\n * The arguments extensions declare leave the call's own and are admitted\n * first, so the record is settled with the call's own arguments and no\n * first moment sees a declared one among them.\n */\n #resolveArgs(): Record<string, unknown> {\n const preparation = this.#inputPreparation;\n if (preparation === undefined) return this.#args;\n if (preparation.status === \"success\" && preparation.args) {\n return preparation.args;\n }\n if (preparation.status === \"failure\") throw preparation.error;\n\n try {\n const admission = this.#engine.extensionChain?.args?.admit(\n this.#modelName,\n String(this.#options.originalOperation),\n this.#operation,\n this.#args,\n this.#engine.bound\n );\n const args = preparation.prepare(\n admission?.args ?? this.#args,\n admission?.values,\n preparation\n );\n preparation.args = args;\n preparation.values = admission?.values;\n preparation.status = \"success\";\n return args;\n } catch (error) {\n preparation.error = error;\n preparation.status = \"failure\";\n throw error;\n }\n }\n\n /** Resolve one exact package-owned listener for every lifecycle entry point. */\n #resolveWriteOutcomeRegistration(): WriteOutcomeRegistration | undefined {\n if (this.#writeOutcomeRegistrationResolved) {\n return this.#writeOutcomeRegistration;\n }\n this.#writeOutcomeRegistration = this.#prepareWriteOutcomeRegistration?.(\n this.#context.attribution,\n this.#inputPreparation?.values,\n this.#inputPreparation\n );\n this.#writeOutcomeRegistrationResolved = true;\n return this.#writeOutcomeRegistration;\n }\n\n /** Construct (once) the route's view of this operation. */\n #resolveRouted(): PreparedOperation {\n if (this.#routedInstance) return this.#routedInstance;\n // The model proxy answers every property with a callable child, so a\n // misspelled or REMOVED operation name (`createManyAndReturn`,\n // `updateManyAndReturn` — see the implicit-returning surface) reaches here\n // instead of failing as \"undefined is not a function\". Name it as what it\n // is, from the one vocabulary owner, before the route is asked for a verb\n // it has no construction path for.\n if (!ROUTED_OPERATIONS.has(this.#operation)) {\n throw new QueryEngineError(\n `Unknown operation '${this.#operation}' on model '${this.#modelName}'. Known operations: ${[...ROUTED_OPERATIONS].sort().join(\", \")}.`\n );\n }\n const args = this.#resolveArgs();\n // A package-owned listener may tell the engine what to report while it\n // plans (a write hook's upsert arm): it exists before any planning.\n this.#resolveWriteOutcomeRegistration();\n const routed = this.#route.prepare(\n this.#modelName,\n // Refused above where it is no operation the engine knows.\n this.#options.originalOperation as never,\n args,\n this.#callRows()\n );\n this.#routedInstance = routed;\n return routed;\n }\n\n /** The row facts this call's admitted arguments resolve to, if any. */\n #callRows() {\n const binding = this.#engine.extensionChain?.callRows;\n return binding?.call(this.#modelName, this.#inputPreparation?.values);\n }\n\n /**\n * The ONE prepared package this operation compiles to when it compiles to\n * exactly one driver query — every read. The route prepares it once and both\n * array-owner arms read it: the query `prepare()` publishes and the parser\n * `parseResult()` applies come from that single preparation, so a member's\n * statement and its decoder cannot describe different queries.\n */\n #resolveSinglePackage(): PreparedBatchOperation<unknown> | undefined {\n if (this.#singlePackageResolved) return this.#singlePackage;\n const prepared = this.#resolveRouted().prepareSingle(\n this.#context.attribution\n );\n this.#singlePackage = prepared?.queries.length === 1 ? prepared : undefined;\n this.#singlePackageResolved = true;\n return this.#singlePackage;\n }\n\n /**\n * The payload this operation runs: the prepared operation's ONE admission.\n * Resolving it settles request preparation and admits the operation.\n */\n #preparedInput(): Record<string, unknown> {\n return this.#resolveRouted().args;\n }\n\n /**\n * The prepared facts one query handler chain inspects. Its `input` is\n * snapshotted at the first read, once for the whole chain: the prepared\n * payload is the admission's own and nothing writes it after admission, so\n * a later snapshot says what an eager one would, and a chain that never\n * reads it never copies it.\n */\n #queryContext(\n mode: CallMode,\n preparedInput: Record<string, unknown>\n ): PreparedModelQueryContext<Record<string, unknown>> {\n const values = this.#inputPreparation?.values;\n let input: Readonly<Record<string, unknown>> | undefined;\n return Object.freeze({\n mode,\n kind: \"model\" as const,\n model: this.#modelName,\n operation: String(this.#options.originalOperation),\n get input() {\n input ??= snapshotQueryInput(preparedInput);\n return input;\n },\n ...(values === undefined ? {} : { values }),\n call: this.#inputPreparation,\n });\n }\n\n #getPromise(): Promise<T> {\n return this.#execution.executeDefault(() => {\n const observation = this.#engine.extensionChain?.observation;\n if (observation === undefined) {\n return this.#finished(this.#runExecution());\n }\n return observation.run(this.#unit(true), () =>\n this.#finished(this.#runExecution())\n );\n });\n }\n\n /** The value its caller receives: the client's last step applied, if any. */\n #finished(value: Promise<T>): Promise<T> {\n const finish = this.#options.finishResult;\n return finish ? value.then((result) => finish(result) as T) : value;\n }\n\n /**\n * This operation's `operation` unit. Its certainty is the operation's own,\n * except for an array member, whose array reports it.\n */\n #unit(certain?: true): UnitSource {\n return {\n kind: \"operation\",\n operation: String(this.#options.originalOperation),\n model: this.#modelName,\n context: this.#context.attribution,\n driver: this.#engine.driver,\n table: this.#model[\"~\"].names.sql ?? this.#modelName,\n ...(certain ? { certainty: () => this.#observationCommitCertainty } : {}),\n };\n }\n\n #runExecution(\n driverOverride?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n ): Promise<T> {\n return withOperationErrorContext(this.#context.attribution, () =>\n this.#runAttributedExecution(\n driverOverride,\n committedWriteSegment,\n writeMayBeVisible\n )\n );\n }\n\n #runAttributedExecution(\n driverOverride?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n ): Promise<T> {\n const observerCommitted = this.#observationNotification(\"committed\");\n const observerMayHaveCommitted =\n this.#observationNotification(\"may-have-committed\");\n const requestedOperation = String(this.#options.originalOperation);\n const handlers = this.#engine.extensionChain?.around?.handlers(\n this.#modelName,\n requestedOperation\n );\n if (\n (handlers === undefined || handlers.length === 0) &&\n this.#prepareWriteOutcomeRegistration === undefined\n ) {\n return this.#runCoreExecution(\n driverOverride,\n combineWriteNotifications(committedWriteSegment, observerCommitted),\n combineWriteNotifications(writeMayBeVisible, observerMayHaveCommitted)\n );\n }\n return this.#runExtendedExecution(\n handlers,\n requestedOperation,\n observerCommitted,\n observerMayHaveCommitted,\n driverOverride,\n committedWriteSegment,\n writeMayBeVisible\n );\n }\n\n /** Query extensions and write-outcome registration, out of line. */\n #runExtendedExecution(\n handlers: AroundHandlers | undefined,\n requestedOperation: string,\n observerCommitted: (() => Promise<void>) | undefined,\n observerMayHaveCommitted: (() => Promise<void>) | undefined,\n driverOverride?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n ): Promise<T> {\n let preparedInput: Record<string, unknown>;\n try {\n preparedInput = this.#preparedInput();\n } catch (error) {\n return Promise.reject(error);\n }\n const writeOutcomeRegistration = this.#resolveWriteOutcomeRegistration();\n const coordination = this.#engine.extensionChain?.coordination;\n if (\n coordination === undefined ||\n ((handlers === undefined || handlers.length === 0) &&\n writeOutcomeRegistration === undefined)\n ) {\n return this.#runCoreExecution(\n driverOverride,\n combineWriteNotifications(committedWriteSegment, observerCommitted),\n combineWriteNotifications(writeMayBeVisible, observerMayHaveCommitted)\n );\n }\n const context =\n handlers === undefined || handlers.length === 0\n ? undefined\n : this.#queryContext(\n this.#engine.transaction ? \"transaction\" : \"direct\",\n preparedInput\n );\n // Handlers come with `around` and a registration with the part that\n // watches writes: each coordinates with what runs them.\n return coordination.executePreparedQuery!<T, Record<string, unknown>>(\n context,\n handlers,\n (notifications, driver) =>\n this.#runCoreExecution(\n driver ?? driverOverride,\n combineWriteNotifications(\n committedWriteSegment,\n combineWriteNotifications(\n notifications?.committed,\n observerCommitted\n )\n ),\n combineWriteNotifications(\n writeMayBeVisible,\n combineWriteNotifications(\n notifications?.mayHaveCommitted,\n observerMayHaveCommitted\n )\n )\n ),\n !isReadOperation(requestedOperation),\n this.#engine.transaction,\n undefined,\n writeOutcomeRegistration\n );\n }\n\n #observationNotification(\n certainty: \"committed\" | \"may-have-committed\"\n ): (() => Promise<void>) | undefined {\n if (\n this.#engine.transaction !== undefined ||\n this.#engine.extensionChain?.observation === undefined\n ) {\n return undefined;\n }\n return async () => {\n if (\n certainty === \"committed\" ||\n this.#observationCommitCertainty === undefined\n ) {\n this.#observationCommitCertainty = certainty;\n }\n };\n }\n\n #runCoreExecution(\n driverOverride?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n ): Promise<T> {\n return this.#run(driverOverride, committedWriteSegment, writeMayBeVisible);\n }\n\n /**\n * Run this operation through the route. The driver an existing transaction or\n * array owner supplied stays exactly the driver it supplied; this owner opens\n * and closes no scope of its own, and retries nothing here. The engine's four\n * bounded recoveries live inside the route (`raptor3/AGENTS.md`, \"Which\n * recovery REPLAYS and which RE-PLANS\"); one of them reads `meta.raceable`\n * off the failure to decide whether a premise may be answered by a second\n * attempt.\n */\n #run(\n driverOverride?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n ): Promise<T> {\n let routed: PreparedOperation;\n try {\n routed = this.#resolveRouted();\n } catch (error) {\n return Promise.reject(error);\n }\n const run = () =>\n routed.run({\n committedWriteSegment,\n context: this.#context.attribution,\n driverOverride,\n engineDriver: this.#engine.driver,\n isWrite: !isReadOperation(String(this.#options.originalOperation)),\n writeMayBeVisible,\n }) as Promise<T>;\n // Below every per-call lifecycle step, outside any borrowed scope: a\n // `findUnique` may share one read with the calls of the same tick.\n // A read whose rows are kept (`codec`) is sent alone: a shared read's\n // rows are not its own.\n if (\n this.#operation === \"findUnique\" &&\n driverOverride === undefined &&\n routed.seen === undefined\n ) {\n const batched = batchFindUnique({\n engine: this.#engine,\n model: this.#model,\n requested: String(this.#options.originalOperation),\n args: this.#resolveArgs(),\n values: this.#inputPreparation?.values,\n rows: () => this.#callRows(),\n routed,\n context: this.#context.attribution,\n run,\n });\n if (batched !== undefined) return batched as Promise<T>;\n }\n return run();\n }\n\n getArgs(): Record<string, unknown> {\n return this.#args;\n }\n\n /**\n * The one SQL statement this operation compiles to, or `undefined` when it\n * does not compile to exactly one (backs {@link QueryEngine.build}).\n *\n * Every read compiles to one statement and publishes it, from the prepared\n * read the execution itself runs — there is no second lowering here. A write\n * answers `undefined`: the engine's only write fold is the asynchronous\n * `prepareBatch()`, which publishes driver-prepared queries rather than an\n * `Sql`, and this accessor is synchronous.\n */\n buildStatement(): Sql | undefined {\n return this.#resolveRouted().read?.statement;\n }\n\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): Promise<TResult1 | TResult2> {\n return this.#getPromise().then(onfulfilled, onrejected);\n }\n\n catch<TResult = never>(\n onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null\n ): Promise<T | TResult> {\n return this.#getPromise().catch(onrejected);\n }\n\n finally(onfinally?: (() => void) | null): Promise<T> {\n return this.#getPromise().finally(onfinally);\n }\n}\n\n/** Create one genuine operation without exposing its construction identity. */\nexport function createPendingOperation<T>(\n engine: QueryEngine,\n model: AnyModel,\n operation: Operation | `${Operation}OrThrow`,\n args: Record<string, unknown>,\n options?: PrepareOptions,\n prepareInput?: PrepareOperationInput,\n prepareWriteOutcomeRegistration?: PrepareWriteOutcomeRegistration\n): PendingOperation<T> {\n return createPendingOperationFriend(\n engine,\n model,\n operation,\n args,\n options,\n prepareInput,\n prepareWriteOutcomeRegistration\n );\n}\n\nexport function isPendingOperation<T = unknown>(\n value: unknown\n): value is PendingOperation<T> {\n return (\n value !== null &&\n typeof value === \"object\" &&\n PENDING_OPERATION_SYMBOL in value &&\n (value as Record<symbol, unknown>)[PENDING_OPERATION_SYMBOL] === true\n );\n}\n\nexport type UnwrapPendingOperation<T> =\n T extends PendingOperation<infer U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AAc,kBAAkB,CAAC,CAClE,oBACD,CAAC,CAKJ,GACE,MAAA,IAAoB,cACpB,IAAmB,IAAA,IACnB,EAAO,OAAS,IAAA,GAChB,CACA,IAAM,EAAU,gBAAgB,CAC9B,OAAQ,MAAA,EACR,MAAO,MAAA,EACP,UAAW,OAAO,MAAA,EAAc,kBAAkB,CAClD,KAAM,MAAA,GAAmB,CACzB,OAAQ,MAAA,GAAwB,OAChC,SAAY,MAAA,GAAgB,CAC5B,SACA,QAAS,MAAA,EAAc,YACvB,IACD,CAAC,CACF,GAAI,IAAY,IAAA,GAAW,OAAO,EAEpC,OAAO,KAAK,CAGd,SAAmC,CACjC,OAAO,MAAA,EAaT,gBAAkC,CAChC,OAAO,MAAA,GAAqB,CAAC,MAAM,UAGrC,KACE,EACA,EAC8B,CAC9B,OAAO,MAAA,GAAkB,CAAC,KAAK,EAAa,EAAW,CAGzD,MACE,EACsB,CACtB,OAAO,MAAA,GAAkB,CAAC,MAAM,EAAW,CAG7C,QAAQ,EAA6C,CACnD,OAAO,MAAA,GAAkB,CAAC,QAAQ,EAAU,GAKhD,SAAgB,uBACd,EACA,EACA,EACA,EACA,EACA,EACA,EACqB,CACrB,OAAO,6BACL,EACA,EACA,EACA,EACA,EACA,EACA,EACD,CAGH,SAAgB,mBACd,EAC8B,CAC9B,OAEE,OAAO,GAAU,YADjB,GAEA,KAA4B,GAC3B,EAAkC,KAA8B"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-z-cH5ZBI.mjs";import{m as n,p as r}from"./validation--qS7OPmg.mjs";import{o as i,t as a}from"./sql-3o4DOKm9.mjs";import{t as o}from"./adapter-result-parser-3WP82Cm-.mjs";import{N as s,T as c,o as l}from"./native-types-DgjMUikz.mjs";import{a as ee}from"./adapter-internals-DOqI8IlQ.mjs";import{a as u}from"./physical-CeE2nYmI.mjs";import{t as d}from"./geo-area-codec-mHrM3b9A.mjs";import{a as f}from"./datetime-physical-codec-Dj-APo9f.mjs";import{t as p}from"./identifiers-s00pGES8.mjs";import{C as te,D as m,E as h,O as g,S as _,T as v,a as y,b,c as x,d as S,f as C,g as w,h as T,i as E,j as D,l as O,m as k,n as A,o as j,p as M,r as N,s as P,v as ne,w as F,x as I,y as L}from"./standard-sql-qLcQyCtK.mjs";import{t as R}from"./json-parameter-oQ8nGaKr.mjs";import{t as z}from"./array-literal-DHinAnVs.mjs";import{r as B}from"./batch-refs-C-gx7A4-.mjs";import{t as V}from"./adapter-namespace-DaRiTIIf.mjs";import{a as H,c as U,i as W,l as G,m as K,n as q,p as J,r as Y,s as X,t as Z}from"./select-assembly-DVI7d3tf.mjs";const Q=p(`"`);function postgresLikePattern(e,t){let n=e===`startsWith`?``:`%`,r=e===`endsWith`?``:`%`,[a,o]=t.values;return t.strings.join(``)===``&&typeof a==`string`&&o===void 0?i`${n+D(a)+r}`:i`(${i.raw(n&&`'%' || `)}REPLACE(REPLACE(REPLACE(CAST(${t} AS TEXT), CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')${i.raw(r&&` || '%'`)})`}function postgresJsonObject(e){if(e.length===0)return i.raw`'{}'::json`;let t=[],n=i.raw(e.length>50?`jsonb_build_object`:`json_build_object`);for(let r=0;r<e.length;r+=50){let a=e.slice(r,r+50).flatMap(([e,t])=>[i`${e}::text`,t]);t.push(i`${n}(${i.join(a,`, `)})`)}return t.length===1?t[0]:i`(${i.join(t,` || `)})::json`}const re=K(e=>`${e}_pkey`);var CastParameter=class extends a{type;constructor(e,t){super([`CAST(`,` AS ${t})`],[e]),this.type=t}},ArrayParameter=class extends a{};const ie=m().list;function arrayParameter(e){let t=e[0];if(t===void 0)return;let n=t instanceof CastParameter?t.type:void 0,r=[];for(let t of e){let e=t instanceof CastParameter?t:void 0,[i,a,o]=t.strings;if(e?.type!==n||!e&&(i!==``||a!==``||o!==void 0))return;let s=t.values[0];if(s instanceof Uint8Array)r.push(`\\x${Array.from(s,e=>e.toString(16).padStart(2,`0`)).join(``)}`);else if(typeof s==`string`||typeof s==`number`||typeof s==`bigint`||typeof s==`boolean`)r.push(String(s));else return}let i=z(r);return n===void 0?new ArrayParameter([``,``],[i]):new ArrayParameter([`CAST(`,` AS ${n}[])`],[i])}const $={quotient:(e,t)=>i`div(${e}, ${t})`,remainder:(e,t)=>i`mod(${e}, ${t})`},ae=/^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\(|$)/i;var PostgresAdapter=class{geoPoint;constructor(e=`public`,t=!1){V(this,e,`postgresql`),this.identifiers=C(Q,this.namespace,!0),J(this,t?this.#r():void 0),ee(this,{batchRefs:this.#n,constraints:re,pinnedTable:this.identifiers.table,select:this.#e.select})}raw=te();identifiers;literals={...m(),dateTime:e=>i`${f(e)}`,true:()=>i.raw`TRUE`,false:()=>i.raw`FALSE`,json:e=>i`${R.from(e)}`,decimal:(e,t)=>new CastParameter(s(e,t,`text`),c(`pg`,t)),id:(e,t)=>t===`uuid`?new CastParameter(e,`UUID`):i`${e}`,list:e=>arrayParameter(e)??ie(e)};operators={...y(),containsText:(e,t)=>i`${e} LIKE ${postgresLikePattern(`contains`,t)} ESCAPE '\\'`,startsWithText:(e,t)=>i`${e} LIKE ${postgresLikePattern(`startsWith`,t)} ESCAPE '\\'`,endsWithText:(e,t)=>i`${e} LIKE ${postgresLikePattern(`endsWith`,t)} ESCAPE '\\'`,insensitiveText:(e,t,n,r)=>i`${this.expressions.caseSensitiveText(t,r,!0)} ILIKE ${postgresLikePattern(e,n)} ESCAPE '\\'`,startsWithPrefix:(e,t,n)=>i`${this.expressions.caseSensitiveText(e,n,!0)} LIKE ${`${D(t)}%`} ESCAPE '\\'`,exactTextEq:(e,t,n)=>i`${this.expressions.caseSensitiveText(e,n,!1)} = ${t}`,exactTextIn:(e,t,n)=>this.operators.in(this.expressions.caseSensitiveText(e,n,!1),t),in:(e,t)=>t instanceof ArrayParameter?i`${e} = ANY(${t})`:i`${e} IN ${t}`,notIn:(e,t)=>t instanceof ArrayParameter?i`${e} <> ALL(${t})`:i`${e} NOT IN ${t}`,...L(),..._(),...w(this.literals.true,this.literals.false),...S()};expressions={...E(),caseSensitiveText:(e,t,r=!1)=>{let a=l(t,`pg`)?.type;if(!r&&a?.toLowerCase()===`xml`)throw new n(`PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.`,{meta:{dialect:`pg`,scalarType:`string`}});return r&&a&&ae.test(a)?i`CAST(${e} AS TEXT)`:e},caseFold:(e,t)=>i`LOWER(${this.expressions.caseSensitiveText(e,t,!0)})`,concat:(...e)=>e.length===0?i.raw`''`:e.length===1?e[0]:i`(${i.join(e,` || `)})`,greatest:(...e)=>i`GREATEST(${i.join(e,`, `)})`,least:(...e)=>i`LEAST(${i.join(e,`, `)})`,integerDivide:(e,t)=>i`(${e} / ${t})`,decimalCast:(e,t)=>i`CAST(${e} AS ${i.raw(c(`pg`,t))})`,idCast:(e,t)=>t===`bytes`?i`decode(${e}, 'hex')`:i`CAST(${e} AS ${i.raw(t===`uuid`?`UUID`:`TEXT`)})`,cast:N({text:`TEXT`,integer:`INTEGER`,bigint:`BIGINT`,boolean:`BOOLEAN`,numeric:`NUMERIC`}),blobToHex:e=>i`encode(${e}, 'hex')`};aggregates={...A(`'Infinity'::float8`),min:(e,t=!1)=>t?i`BOOL_AND(${e})`:i`MIN(${e})`,max:(e,t=!1)=>t?i`BOOL_OR(${e})`:i`MAX(${e})`,decimalAvg:(e,t)=>X($,e,t),decimalSumOperandPrecision:x(1e3)};json={equals:(e,t)=>i`(${e})::jsonb = (${t})::jsonb`,boolean:e=>e,document:e=>e,number:e=>e,object:postgresJsonObject,array:e=>e.length===0?i.raw`'[]'::json`:i`json_build_array(${i.join(e,`, `)})`,emptyArray:()=>i.raw`'[]'::json`,agg:e=>i`COALESCE(json_agg(${e}), '[]'::json)`,objectFromColumns:postgresJsonObject,extract:(e,t)=>i`(${e})::jsonb#>${t}::text[]`,extractText:(e,t)=>i`(${e})::jsonb#>>${t}::text[]`,numberAtPath:(e,t)=>i`(CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'number' THEN ((${e})::jsonb#>>${t}::text[])::double precision END)`,stringAtPath:(e,t)=>i`(${this.json.foldableStringAtPath(e,t)} COLLATE "C")`,foldableStringAtPath:(e,t)=>i`(CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'string' THEN (${e})::jsonb#>>${t}::text[] END)`,contains:(e,t)=>i`(${e})::jsonb @> ${t}`,lastElement:e=>i`(${e})::jsonb -> -1`,value:e=>i`${R.from(e)}`};arrays={literal:e=>e.length===0?i.raw`'{}'`:i`ARRAY[${i.join(e,`, `)}]`,value:(e,t)=>i`${t?e.map(e=>typeof e==`string`?f(e):e):e}`,enumValue:e=>i`${z(e)}`,ofRows:e=>i`ARRAY(${e})`,has:(e,t)=>i`${t} = ANY(${e})`,hasEvery:(e,t)=>i`${e} @> ${t}`,hasSome:(e,t)=>i`${e} && ${t}`,isEmpty:e=>i`(cardinality(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>i`CAST(${e} AS TEXT[])`,length:e=>i`cardinality(${e})`,get:(e,t)=>i`${e}[${t}]`,push:(e,t)=>i`array_append(${e}, ${t})`,set:(e,t,n)=>i`${e}[:${t}-1] || ARRAY[${n}] || ${e}[${t}+1:]`};orderBy={...O(),nullsFirst:(e,t)=>t===`desc`?i`${e} DESC NULLS FIRST`:i`${e} ASC NULLS FIRST`,nullsLast:(e,t)=>t===`desc`?i`${e} DESC NULLS LAST`:i`${e} ASC NULLS LAST`};clauses=h();set={...b(),multiply:(e,t,n)=>n?.decimal?G($,e,t,n.decimal):i`${e} = ${e} * ${t}`,divide:(e,t,n)=>n?.decimal?U($,e,t,n.decimal):i`${e} = ${e} / ${t}`,push:(e,t)=>i`${e} = array_cat(COALESCE(${e}, '{}'), ${t})`,unshift:(e,t)=>i`${e} = array_cat(${t}, COALESCE(${e}, '{}'))`};filters=F();subqueries=g(Q);#e={select:e=>e.distinct&&e.orderBy?Z(e,e.distinct,this.identifiers.escape):q(e.distinct?i`SELECT DISTINCT ON (${e.distinct}) ${e.columns}`:i`SELECT ${e.columns}`,e,{forUpdate:`append`})};cte=P(Q,{inlining:i.raw(`NOT MATERIALIZED`)});mutations={skipDuplicatesStrategy:`sql`,insert:k(Q),insertAbsent:M(Q),insertDefault:e=>i`INSERT INTO ${e} DEFAULT VALUES`,...ne(),returning:e=>i`RETURNING ${e}`,upserted:i.raw(`(xmax = 0)`),...I()};assertions={exists:e=>i`SELECT 1 / CASE WHEN EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`,notExists:e=>i`SELECT 1 / CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`};joins={...j(),full:(e,t)=>i`FULL OUTER JOIN ${e} ON ${t}`,...T(Q)};setOperations=v();capabilities={supportsReturning:!0,supportsCteWithMutations:!0,supportsFullOuterJoin:!0,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!0,joinsJunctionFilters:`unbounded`,readsNodesByKey:!0};lastInsertId=()=>i.raw`lastval()`;#t=B({table:i.raw`"__viborm_batch_refs"`,batchIdColumn:i.raw`"batch_id"`,keyColumn:i.raw`"ref_key"`,valueColumn:i.raw`"ref_value"`,createTable:i.raw`CREATE TEMP TABLE IF NOT EXISTS "__viborm_batch_refs" ("batch_id" TEXT NOT NULL, "ref_key" TEXT NOT NULL, "ref_value" TEXT, PRIMARY KEY ("batch_id", "ref_key"))`,castValue:e=>i`CAST((${e}) AS TEXT)`,storeReturning:(e,t,n,r)=>i`WITH "__viborm_inserted" AS (${n} RETURNING ${r}) INSERT INTO "__viborm_batch_refs" ("batch_id", "ref_key", "ref_value") SELECT ${e}, ${t}, CAST(${r} AS TEXT) FROM "__viborm_inserted"`});#n=(()=>{let e=this.#t,t=this.capabilities;return{setup:e.setup,cleanup:e.cleanup,store:e.store,read:e.read,get storeReturning(){return t.supportsCteWithMutations?e.storeReturning:void 0},get storeInsertedKey(){return t.supportsCteWithMutations?e.storeInsertedKey:void 0}}})();vector={literal:e=>{if(e.some(e=>!Number.isFinite(Math.fround(e))))throw new r(`PostgreSQL vector components must fit a finite float32 value.`,{code:t.INVALID_INPUT});return i`${`[${e.join(`,`)}]`}::vector`},l2:(e,t,n)=>n===`exact`?i`(${e} <-> ${t}) + 0`:i`${e} <-> ${t}`,cosine:(e,t,n)=>n===`servable`?i`${e} <=> ${t}`:i`NULLIF(${e} <=> ${t}, 'NaN'::double precision)`};#r(){let longitude=e=>i`ST_X(${e}::geometry)`,latitude=e=>i`ST_Y(${e}::geometry)`;return{value:(e,t)=>i`ST_SetSRID(ST_MakePoint(${e}, ${t}), 4326)::geography`,longitude,latitude,...Y(longitude,latitude,this.operators,(e,t)=>{let n=W(t);if(n.length!==0)return this.operators.or(...n.map(t=>i`${e} && ST_SetSRID(ST_GeomFromGeoJSON(${t}), 4326)::geography`))}),withinPolygon:(e,t)=>i`ST_Intersects(${i`ST_SetSRID(ST_GeomFromGeoJSON(${H(t)}), 4326)::geography`}, ${e})`,distance:(e,t)=>{let n=i`RADIANS(ST_X(${e}::geometry))`,r=i`RADIANS(ST_Y(${e}::geometry))`,a=i`RADIANS(ST_X(${t}::geometry))`,o=i`RADIANS(ST_Y(${t}::geometry))`;return i`CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE CAST(${d} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${i`POWER(SIN((${o} - ${r}) / 2), 2) + COS(${r}) * COS(${o}) * POWER(SIN((${a} - ${n}) / 2), 2)`})))) END`}}}result={nativeScalarPassthrough:!0,enumListRepresentation:`arrayText`,idRepresentation:(e,t)=>u(e,t,`pg`)?.representation??`text`,parseResult:o,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()}};export{PostgresAdapter as t};
|
|
2
|
-
//# sourceMappingURL=postgres-adapter-Dlr3ZWd7.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-adapter-Dlr3ZWd7.mjs","names":["sql","#createGeoPointSql","#batchRefs","#assemble","#cteBatchRefs"],"sources":["../src/adapters/databases/postgres/postgres-adapter.ts"],"sourcesContent":["import {\n QueryError,\n UnsupportedOperationError,\n VibORMErrorCode,\n} from \"@errors\";\nimport {\n type NativeTypeDeclaration,\n nativeTypeFor,\n} from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { Sql, sql } from \"@sql\";\nimport { encodePostgresTemporal } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport { JsonParameter } from \"../../../sql/json-parameter\";\nimport type {\n ArithmeticTarget,\n BatchReferenceSqlAdapter,\n} from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport { passThroughParseResult } from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n type TextMatch,\n type VectorOrderKey,\n} from \"../../database-adapter\";\nimport { createOnConflictBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n logicalDecimalAverage,\n logicalDecimalDivide,\n logicalDecimalMultiply,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertAbsent,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createOnConflictBuilders,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n} from \"../../shared/standard-sql\";\nimport { arrayLiteralText } from \"./array-literal\";\n\nconst quoteIdent = createIdentifierQuoter('\"');\n/**\n * The `LIKE` pattern matching `value` literally where `kind` says. A plain\n * string (a bare bound parameter) is escaped here and bound as the finished\n * pattern; any other operand (a column, a JSON path) is escaped by the server.\n */\nfunction postgresLikePattern(kind: TextMatch, value: Sql): Sql {\n const head = kind === \"startsWith\" ? \"\" : \"%\";\n const tail = kind === \"endsWith\" ? \"\" : \"%\";\n const [literal, other] = value.values;\n if (\n value.strings.join(\"\") === \"\" &&\n typeof literal === \"string\" &&\n other === undefined\n )\n return sql`${head + escapeLikeLiteral(literal) + tail}`;\n return sql`(${sql.raw(head && \"'%' || \")}REPLACE(REPLACE(REPLACE(CAST(${value} AS TEXT), CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')${sql.raw(tail && \" || '%'\")})`;\n}\nfunction postgresJsonObject(pairs: [string, Sql][]): Sql {\n if (pairs.length === 0) return sql.raw`'{}'::json`;\n const chunks: Sql[] = [];\n const buildObject = sql.raw(\n pairs.length > 50 ? \"jsonb_build_object\" : \"json_build_object\"\n );\n // PostgreSQL limits a function call to 100 arguments. Chunking preserves\n // the surrounding aggregate scope, unlike moving values into a subquery.\n for (let start = 0; start < pairs.length; start += 50) {\n const args = pairs\n .slice(start, start + 50)\n .flatMap(([key, value]) => [sql`${key}::text`, value]);\n chunks.push(sql`${buildObject}(${sql.join(args, \", \")})`);\n }\n return chunks.length === 1\n ? chunks[0]!\n : sql`(${sql.join(chunks, \" || \")})::json`;\n}\nconst POSTGRES_CONSTRAINTS = createNamedConstraintIdentities(\n (tableName) => `${tableName}_pkey`\n);\n\n/** An operand cast to the type its column holds: `uuid`, `NUMERIC(p,s)`. */\nclass CastParameter extends Sql {\n readonly type: string;\n constructor(value: unknown, type: string) {\n super([\"CAST(\", ` AS ${type})`], [value]);\n this.type = type;\n }\n}\n\n/** A value list bound as ONE array parameter: `= ANY(…)`, `<> ALL(…)`. */\nclass ArrayParameter extends Sql {}\nconst PARENTHESIZED_LIST = createStandardLiterals().list;\n\n/**\n * engine-09: a list whose members are each one parameter — bare, or all cast\n * to one type — as one array parameter: PostgreSQL's own array text, typed by\n * the members' cast or, bare, by the compared column, as a list column's\n * parameter is. Any other list keeps a parameter per member.\n */\nfunction arrayParameter(members: readonly Sql[]): ArrayParameter | undefined {\n const first = members[0];\n if (first === undefined) return;\n const type = first instanceof CastParameter ? first.type : undefined;\n const elements: string[] = [];\n for (const member of members) {\n const cast = member instanceof CastParameter ? member : undefined;\n const [head, tail, extra] = member.strings;\n if (\n cast?.type !== type ||\n (!cast && (head !== \"\" || tail !== \"\" || extra !== undefined))\n )\n return;\n const value = member.values[0];\n if (value instanceof Uint8Array)\n elements.push(\n `\\\\x${Array.from(value, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`\n );\n else if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n )\n elements.push(String(value));\n else return;\n }\n const text = arrayLiteralText(elements);\n return type === undefined\n ? new ArrayParameter([\"\", \"\"], [text])\n : new ArrayParameter([\"CAST(\", ` AS ${type}[])`], [text]);\n}\n\n/**\n * `div`/`mod` rather than `/` and a hand-rolled remainder: both are exact on\n * `numeric` for any operand, including a fractional divisor, and `div`\n * truncates toward zero — which is what the half-even rule's quotient means.\n * `/` on numerics picks its own result scale and would round the last digit.\n */\nconst POSTGRES_INTEGERS: ExactIntegerArithmetic = {\n quotient: (n: Sql, d: Sql): Sql => sql`div(${n}, ${d})`,\n remainder: (n: Sql, d: Sql): Sql => sql`mod(${n}, ${d})`,\n};\n\n/** The two characters PostgreSQL reads structurally inside a quoted member. */\n\n/**\n * PostgreSQL's own text spelling of one list, for a column whose element type\n * the driver cannot serialize.\n *\n * Every member is quoted, so a member that is empty, spells `NULL`, or holds a\n * brace, comma, quote or backslash is still exactly one member: those are the\n * only characters the server reads structurally, and quoting makes the reading\n * unambiguous without a per-member decision.\n */\n\nconst NON_TEXT_STRING_TYPE =\n /^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\\(|$)/i;\n\nexport class PostgresAdapter implements DatabaseAdapter {\n /**\n * The bound schema. PostgreSQL always qualifies, so this adapter has no\n * unbound mode: an omitted or explicitly `undefined` argument means the\n * `public` schema, whatever a connection's `search_path` says.\n */\n declare readonly namespace: string;\n readonly geoPoint: GeoPointSql | undefined;\n\n constructor(namespace = \"public\", postgis = false) {\n installAdapterNamespace(this, namespace, \"postgresql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(quoteIdent, this.namespace, true);\n installGeoPointSql(this, postgis ? this.#createGeoPointSql() : undefined);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: POSTGRES_CONSTRAINTS,\n // Always qualified by its schema.\n pinnedTable: this.identifiers.table,\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n dateTime: (iso: string): Sql => sql`${encodePostgresTemporal(iso)}`,\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // Serialized JSON text — PG casts the param to json/jsonb from the column\n // context. Stringifying (not raw binding) keeps primitives valid: a bare\n // 'hello' is not valid JSON input, '\"hello\"' is. The carrier is what tells\n // a transport that this text is already a document; see json-parameter.ts.\n json: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n\n // Cast into the operand's own `NUMERIC(p,s)` domain, the same type the DDL\n // emits for the field. PostgreSQL would usually infer `numeric` from the\n // column context anyway; saying it makes the comparison independent of what\n // the surrounding expression does to the operand's inferred type, and\n // naming the precision keeps the operand and the column one domain rather\n // than two that happen to agree.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n new CastParameter(\n encodePhysicalDecimal(canonical, descriptor, \"text\"),\n decimalColumnType(\"pg\", descriptor)\n ),\n\n // A `uuid` column takes canonical text and is TYPED: PostgreSQL has no\n // `uuid = text` operator, so an untyped operand raises 42883 rather than\n // comparing. `bytea` takes the payload's bytes as an ordinary binary\n // parameter — the same parameter every blob scalar already binds — and a\n // text-stored domain takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n representation: IdRepresentation\n ): Sql =>\n representation === \"uuid\"\n ? new CastParameter(physical, \"UUID\")\n : sql`${physical}`,\n\n list: (values: Sql[]): Sql =>\n arrayParameter(values) ?? PARENTHESIZED_LIST(values),\n };\n\n operators = {\n ...createComparisonOperators(),\n\n containsText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ${postgresLikePattern(\"contains\", value)} ESCAPE '\\\\'`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ${postgresLikePattern(\"startsWith\", value)} ESCAPE '\\\\'`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ${postgresLikePattern(\"endsWith\", value)} ESCAPE '\\\\'`,\n // `ILIKE` folds case as the column's collation does: every letter on a\n // libc or ICU locale, ASCII only on a `C` one. On the bare column, so a\n // trigram index on it serves the filter.\n insensitiveText: (\n kind: TextMatch,\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, true)} ILIKE ${postgresLikePattern(kind, value)} ESCAPE '\\\\'`,\n // PostgreSQL is the one dialect where the escaped LIKE spelling is both\n // exact and index-usable, so it stands alone here: `LIKE` is case- and\n // accent-sensitive natively, which is the contract `startsWithText` holds,\n // and `match_pattern_prefix` extracts `name >= 'x' AND name < 'y'` from the\n // constant-folded pattern even though it arrives as a bound parameter.\n //\n // THE INDEX RANGE HAS A COLLATION PRECONDITION, and the common case does\n // not meet it. Measured, 20k rows, plain btree index:\n // - C-collated database (PGlite, `datcollate = 'C'`): Bitmap Index Scan\n // over 111 rows, where `LEFT(col, LENGTH($1)) = $1` is a Seq Scan over\n // all 20000.\n // - `en_US.utf8` (postgres:16 — the project's own test container, and\n // what a default `initdb` produces): BOTH spellings Seq Scan. Only a\n // `(col text_pattern_ops)` index ranges, and `generateCreateIndex`\n // (src/migrations/drivers/postgres/index.ts) emits no opclass, so\n // viborm cannot create one.\n // What survives on a default-locale cluster — and the reason this spelling\n // still stands there — is the row estimate: `LIKE` tracks the data\n // (202/1010/11111/19998 against truths 111/1111/11111/20000) while\n // `LEFT(...)` is an opaque function estimated at a flat 100 for every\n // prefix width, a 111x error at `name1%` that propagates into the row\n // estimate of any join above it. It is never worse than the spelling it\n // replaced on any measured leg. Full record: Decision 7.3 in\n // docs/architecture/query-performance-plan.md.\n startsWithPrefix: (\n column: Sql,\n value: string,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, true)} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\'`,\n\n // Preserve native equality and indexes; the shared text boundary refuses\n // native types such as XML that cannot express an exact comparison.\n exactTextEq: (\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, false)} = ${value}`,\n exactTextIn: (\n column: Sql,\n values: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n this.operators.in(\n this.expressions.caseSensitiveText(column, nativeType, false),\n values\n ),\n\n // Set membership: a bound list (`literals.list`) is an array, read by\n // ANY/ALL; a parenthesized list or a subquery is read by IN.\n in: (column: Sql, values: Sql): Sql =>\n values instanceof ArrayParameter\n ? sql`${column} = ANY(${values})`\n : sql`${column} IN ${values}`,\n notIn: (column: Sql, values: Sql): Sql =>\n values instanceof ArrayParameter\n ? sql`${column} <> ALL(${values})`\n : sql`${column} NOT IN ${values}`,\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n caseSensitiveText: (\n expr: Sql,\n nativeType?: NativeTypeDeclaration,\n textOperation = false\n ): Sql => {\n const type = nativeTypeFor(nativeType, \"pg\")?.type;\n if (!textOperation && type?.toLowerCase() === \"xml\")\n throw new UnsupportedOperationError(\n \"PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.\",\n { meta: { dialect: \"pg\", scalarType: \"string\" } }\n );\n return textOperation && type && NON_TEXT_STRING_TYPE.test(type)\n ? sql`CAST(${expr} AS TEXT)`\n : expr;\n },\n caseFold: (expr: Sql, nativeType?: NativeTypeDeclaration): Sql =>\n sql`LOWER(${this.expressions.caseSensitiveText(expr, nativeType, true)})`,\n\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`(${sql.join(parts, \" || \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // PostgreSQL integer division already truncates toward zero, which is why\n // `set.divide` ignores `target.integer` here as well. Casting either side\n // would narrow a `bigint` operand to `int4`.\n integerDivide: (left: Sql, right: Sql): Sql => sql`(${left} / ${right})`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${expr} AS ${sql.raw(decimalColumnType(\"pg\", descriptor))})`,\n\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`decode(${expr}, 'hex')`\n : sql`CAST(${expr} AS ${sql.raw(\n representation === \"uuid\" ? \"UUID\" : \"TEXT\"\n )})`,\n\n cast: createCastExpression({\n text: \"TEXT\",\n integer: \"INTEGER\",\n bigint: \"BIGINT\",\n boolean: \"BOOLEAN\",\n numeric: \"NUMERIC\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`encode(${expr}, 'hex')`,\n };\n\n aggregates = {\n ...createAggregateFunctions(\"'Infinity'::float8\"),\n\n min: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOL_AND(${column})` : sql`MIN(${column})`,\n max: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOL_OR(${column})` : sql`MAX(${column})`,\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n logicalDecimalAverage(POSTGRES_INTEGERS, column, descriptor),\n\n // `sum(numeric)` is itself unbounded on PostgreSQL; 1000 is the widest\n // `NUMERIC(p,s)` an operand can be CAST into to meet it, which is the\n // domain a comparison against that sum is actually limited by.\n decimalSumOperandPrecision: createDecimalSumOperandPrecision(1000),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql =>\n sql`(${left})::jsonb = (${right})::jsonb`,\n boolean: (condition: Sql): Sql => condition,\n document: (expression: Sql): Sql => expression,\n number: (expression: Sql): Sql => expression,\n\n object: postgresJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`'[]'::json`;\n return sql`json_build_array(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw`'[]'::json`,\n\n agg: (expr: Sql): Sql => sql`COALESCE(json_agg(${expr}), '[]'::json)`,\n\n objectFromColumns: postgresJsonObject,\n\n // #>/#>> with a text[] param handles every path shape uniformly:\n // '{}' returns the document root, and integer segments address array\n // elements (a single-segment `-> '0'` would only match an object key)\n extract: (column: Sql, path: string[]): Sql =>\n sql`(${column})::jsonb#>${path}::text[]`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`(${column})::jsonb#>>${path}::text[]`,\n\n // jsonb_typeof gates the cast: a non-number (or an absent path, where\n // jsonb_typeof is NULL) short-circuits to NULL instead of raising\n // \"invalid input syntax for type double precision\"\n numberAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN jsonb_typeof((${column})::jsonb#>${path}::text[]) = 'number' THEN ((${column})::jsonb#>>${path}::text[])::double precision END)`,\n\n // COLLATE \"C\" pins byte (= code point) ordering; the database's default\n // collation (en_US.UTF-8 and friends) orders 'a' before 'B', which would\n // make < / > disagree with MySQL and SQLite\n stringAtPath: (column: Sql, path: string[]): Sql =>\n sql`(${this.json.foldableStringAtPath(column, path)} COLLATE \"C\")`,\n foldableStringAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN jsonb_typeof((${column})::jsonb#>${path}::text[]) = 'string' THEN (${column})::jsonb#>>${path}::text[] END)`,\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`(${target})::jsonb @> ${value}`,\n\n lastElement: (target: Sql): Sql => sql`(${target})::jsonb -> -1`,\n\n // Serialized JSON text, same format literals.json writes — PG casts the\n // param to jsonb from the comparison context\n value: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n };\n\n arrays = {\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`'{}'`;\n return sql`ARRAY[${sql.join(items, \", \")}]`;\n },\n\n // Native array parameter; drivers serialize JS arrays to PG array format\n value: (values: unknown[], temporal?: \"date\" | \"datetime\"): Sql =>\n sql`${temporal ? values.map((value) => (typeof value === \"string\" ? encodePostgresTemporal(value) : value)) : values}`,\n\n // One untyped parameter holding PostgreSQL's own array literal. A managed\n // enum's array OID is created by the estate, so no driver has a serializer\n // for it and the native parameter above arrives malformed; an unknown\n // parameter instead takes its type from the column or operand it meets,\n // which is how the enum type is reached without naming it here.\n enumValue: (values: unknown[]): Sql => sql`${arrayLiteralText(values)}`,\n\n ofRows: (query: Sql): Sql => sql`ARRAY(${query})`,\n\n has: (column: Sql, value: Sql): Sql => sql`${value} = ANY(${column})`,\n\n hasEvery: (column: Sql, values: Sql): Sql => sql`${column} @> ${values}`,\n\n hasSome: (column: Sql, values: Sql): Sql => sql`${column} && ${values}`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(cardinality(${column}) = 0 OR ${column} IS NULL)`,\n\n // `numeric[]::text[]` casts every ELEMENT. `numeric[]::text` would produce\n // one string holding PostgreSQL's array literal, and `to_json(numeric[])`\n // JSON numbers — the two spellings a decimal list cannot survive.\n exactNumericProjection: (column: Sql): Sql =>\n sql`CAST(${column} AS TEXT[])`,\n\n length: (column: Sql): Sql => sql`cardinality(${column})`,\n\n get: (column: Sql, index: Sql): Sql => sql`${column}[${index}]`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`array_append(${column}, ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`${column}[:${index}-1] || ARRAY[${value}] || ${column}[${index}+1:]`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS FIRST`\n : sql`${column} ASC NULLS FIRST`,\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS LAST`\n : sql`${column} ASC NULLS LAST`,\n };\n\n clauses = createStandardClauses();\n\n set = {\n ...createNumericSetOperations(),\n\n // A decimal target rounds the product/quotient back to the field's scale\n // half-to-even; every other numeric column keeps PostgreSQL's own\n // arithmetic, whose integer division already truncates toward zero.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalMultiply(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalDivide(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} / ${by}`,\n\n // `values` is already the destination field's one complete list crossing:\n // a native array parameter for ordinary lists or an untyped PostgreSQL\n // array literal for managed enums. `array_cat` lets the column resolve that\n // one parameter's exact array type and keeps bind/SQL size constant.\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(COALESCE(${column}, '{}'), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(${values}, COALESCE(${column}, '{}'))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n readonly #assemble = {\n select: (parts: QueryParts): Sql => {\n // DISTINCT ON requires ORDER BY to lead with the distinct columns, which\n // would override the user's ordering — emulate via ROW_NUMBER() instead\n if (parts.distinct && parts.orderBy) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape\n );\n }\n\n // PostgreSQL supports DISTINCT ON (columns)\n const selectClause = parts.distinct\n ? sql`SELECT DISTINCT ON (${parts.distinct}) ${parts.columns}`\n : sql`SELECT ${parts.columns}`;\n\n return assembleSelectQuery(selectClause, parts, { forUpdate: \"append\" });\n },\n };\n\n cte = createCteBuilders(quoteIdent, {\n inlining: sql.raw(\"NOT MATERIALIZED\"),\n });\n\n mutations = {\n skipDuplicatesStrategy: \"sql\" as const,\n insert: createInsertStatement(quoteIdent),\n insertAbsent: createInsertAbsent(quoteIdent),\n insertDefault: (table: Sql): Sql =>\n sql`INSERT INTO ${table} DEFAULT VALUES`,\n\n ...createMutationCommands(),\n\n returning: (columns: Sql): Sql => sql`RETURNING ${columns}`,\n // An inserted row version has no deleting transaction yet; the row an\n // ON CONFLICT update rewrote carries the updating one.\n upserted: sql.raw(\"(xmax = 0)\"),\n\n ...createOnConflictBuilders(),\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n notExists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n };\n\n joins = {\n ...createCoreJoins(),\n\n full: (table: Sql, condition: Sql): Sql =>\n sql`FULL OUTER JOIN ${table} ON ${condition}`,\n\n ...createLateralJoins(quoteIdent),\n };\n\n setOperations = createSetOperations();\n\n capabilities: DatabaseAdapter[\"capabilities\"] = {\n supportsReturning: true,\n supportsCteWithMutations: true,\n supportsFullOuterJoin: true,\n supportsLateralJoins: true,\n supportsVector: false,\n supportsUpsertWhere: true, // PostgreSQL supports WHERE in ON CONFLICT\n supportsTargetedUpsert: true, // ON CONFLICT (cols) arbitrates on those cols\n supportsMutationTargetInSubquery: true,\n supportsMutationRowLimit: false, // PostgreSQL has no UPDATE/DELETE ... LIMIT\n supportsRowLocks: true,\n joinsJunctionFilters: \"unbounded\",\n readsNodesByKey: true,\n };\n\n lastInsertId = (): Sql => sql.raw`lastval()`;\n\n readonly #cteBatchRefs = createOnConflictBatchRefs({\n table: sql.raw`\"__viborm_batch_refs\"`,\n batchIdColumn: sql.raw`\"batch_id\"`,\n keyColumn: sql.raw`\"ref_key\"`,\n valueColumn: sql.raw`\"ref_value\"`,\n // The table is not ON COMMIT DROP, so it survives the native batch that\n // created it (D-50); the scratch itself belongs to the dispatched batch —\n // each batch stores its own reference rows, reads back what it stored at\n // its own end and deletes them there (D-58), so a later batch never names\n // a reference an earlier one stored. The table lingers on the session like\n // the SQLite and MySQL scratch tables do.\n createTable: sql.raw`CREATE TEMP TABLE IF NOT EXISTS \"__viborm_batch_refs\" (\"batch_id\" TEXT NOT NULL, \"ref_key\" TEXT NOT NULL, \"ref_value\" TEXT, PRIMARY KEY (\"batch_id\", \"ref_key\"))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS TEXT)`,\n // The exact identity of an INSERT, carried by the statement that runs it:\n // the INSERT is the data-modifying CTE, its RETURNING feeds the reference\n // row, and nothing session-global (lastval) is read.\n storeReturning: (batchId, key, insert, column) =>\n sql`WITH \"__viborm_inserted\" AS (${insert} RETURNING ${column}) INSERT INTO \"__viborm_batch_refs\" (\"batch_id\", \"ref_key\", \"ref_value\") SELECT ${batchId}, ${key}, CAST(${column} AS TEXT) FROM \"__viborm_inserted\"`,\n });\n\n // Whether this provider can mutate inside a CTE is the capability's fact,\n // read live: the CTE store and the key store it derives are offered only\n // while `capabilities.supportsCteWithMutations` holds, and a PostgreSQL\n // without it offers no exact key store at all (lastval() is not exact).\n readonly #batchRefs: BatchReferenceSqlAdapter = (() => {\n const withCte = this.#cteBatchRefs;\n const capabilities = this.capabilities;\n return {\n setup: withCte.setup,\n cleanup: withCte.cleanup,\n store: withCte.store,\n read: withCte.read,\n get storeReturning() {\n return capabilities.supportsCteWithMutations\n ? withCte.storeReturning\n : undefined;\n },\n get storeInsertedKey() {\n return capabilities.supportsCteWithMutations\n ? withCte.storeInsertedKey\n : undefined;\n },\n };\n })();\n\n vector = {\n literal: (values: number[]): Sql => {\n if (values.some((value) => !Number.isFinite(Math.fround(value))))\n throw new QueryError(\n \"PostgreSQL vector components must fit a finite float32 value.\",\n { code: VibORMErrorCode.INVALID_INPUT }\n );\n return sql`${`[${values.join(\",\")}]`}::vector`;\n },\n\n // pgvector's index serves `column <-> vector` as an ORDER BY key, and\n // nothing else: an exact order adds a zero it cannot see through.\n l2: (column: Sql, vector: Sql, order?: VectorOrderKey): Sql =>\n order === \"exact\"\n ? sql`(${column} <-> ${vector}) + 0`\n : sql`${column} <-> ${vector}`,\n\n // A zero vector's cosine distance is NaN; the value reads it as NULL, and\n // so does an exact order, which that NULLIF already keeps from an index.\n cosine: (column: Sql, vector: Sql, order?: VectorOrderKey): Sql =>\n order === \"servable\"\n ? sql`${column} <=> ${vector}`\n : sql`NULLIF(${column} <=> ${vector}, 'NaN'::double precision)`,\n };\n\n #createGeoPointSql(): GeoPointSql {\n const longitude = (point: Sql): Sql => sql`ST_X(${point}::geometry)`;\n const latitude = (point: Sql): Sql => sql`ST_Y(${point}::geometry)`;\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`ST_SetSRID(ST_MakePoint(${pointLongitude}, ${pointLatitude}), 4326)::geography`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators,\n (point, bounds) => {\n const polygons = geoBoundsIndexPolygons(bounds);\n if (polygons.length === 0) return;\n return this.operators.or(\n ...polygons.map(\n (polygon) =>\n sql`${point} && ST_SetSRID(ST_GeomFromGeoJSON(${polygon}), 4326)::geography`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_SetSRID(ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}), 4326)::geography`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) => {\n const leftLongitude = sql`RADIANS(ST_X(${left}::geometry))`;\n const leftLatitude = sql`RADIANS(ST_Y(${left}::geometry))`;\n const rightLongitude = sql`RADIANS(ST_X(${right}::geometry))`;\n const rightLatitude = sql`RADIANS(ST_Y(${right}::geometry))`;\n const haversine = sql`POWER(SIN((${rightLatitude} - ${leftLatitude}) / 2), 2) + COS(${leftLatitude}) * COS(${rightLatitude}) * POWER(SIN((${rightLongitude} - ${leftLongitude}) / 2), 2)`;\n // PostgreSQL's LEAST/GREATEST ignore NULL operands. The explicit arm is\n // what keeps a nullable source point's distance NULL rather than zero.\n return sql`CASE WHEN ${left} IS NULL OR ${right} IS NULL THEN NULL ELSE CAST(${GEO_POINT_EARTH_RADIUS_METERS} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${haversine})))) END`;\n },\n };\n }\n\n result: DatabaseAdapter[\"result\"] = {\n // PostgreSQL returns native JS scalars and parseField below is a pure\n // passthrough, so the result parser may take the identity fast path for\n // plain string/int/number/boolean columns (byte-identical, guarded).\n nativeScalarPassthrough: true,\n\n // A managed enum's array OID is in no driver's result-type table, so an\n // enum LIST comes back as the array's own text rather than a JS array.\n enumListRepresentation: \"arrayText\",\n\n // The one physical promise an identifier column makes, derived from the\n // ONE storage owner so the column the migration creates, the parameter the\n // write binds and the value this reads back cannot be three decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"pg\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing. This leg used to offer\n // `convertBigIntToNumber(raw)`, but `Queries.decodeResult` hands it the\n // operation's ROW ARRAY, which is never a bigint, and an integer's width\n // is a VALUE's fact that the engine's `int` codec owns - it turns a bigint\n // or an integer text into a number and refuses one outside the safe range\n // (`raptor3/shared/query.ts`). Measured on live PostgreSQL over seven\n // operations and both routes, on `pg` and on `postgres.js`: 40 asks, 40\n // `undefined` (Arnaud's D-40, `g4/rulings/o2/receipts/leg-probe-pg.log`\n // and `leg-probe-postgresjs-2.log`), with `COUNT(*)` arriving as the text\n // `\"2\"` on both transports.\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => {\n // PostgreSQL returns native JSON objects - passthrough\n return next();\n },\n\n parseField: (\n _value: unknown,\n _scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // PostgreSQL has native types - passthrough\n return next();\n },\n };\n}\n"],"mappings":"6jCAmFA,MAAM,EAAa,EAAuB,IAAI,CAM9C,SAAS,oBAAoB,EAAiB,EAAiB,CAC7D,IAAM,EAAO,IAAS,aAAe,GAAK,IACpC,EAAO,IAAS,WAAa,GAAK,IAClC,CAAC,EAAS,GAAS,EAAM,OAO/B,OALE,EAAM,QAAQ,KAAK,GAAG,GAAK,IAC3B,OAAO,GAAY,UACnB,IAAU,IAAA,GAEH,CAAG,GAAG,EAAO,EAAkB,EAAQ,CAAG,IAC5C,CAAG,IAAIA,EAAI,IAAI,GAAQ,UAAU,CAAC,+BAA+B,EAAM,qFAAqFA,EAAI,IAAI,GAAQ,UAAU,CAAC,GAEhM,SAAS,mBAAmB,EAA6B,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EAAM,+BAA+B,EAA8B,6DAH3F,CAAG,cAAc,EAAc,KAAK,EAAa,mBAAmB,EAAa,UAAU,EAAc,iBAAiB,EAAe,KAAK,EAAc,YAGM,WAEvL,CAGH,OAAoC,CAIlC,wBAAyB,GAIzB,uBAAwB,YAKxB,kBAAmB,EAAQ,IACzB,EAAY,EAAQ,EAAY,KAAK,EAAE,gBAAkB,OAY3D,YAAa,EAEb,eACE,EACA,IAGO,GAAM,CAGf,YACE,EACA,EACA,IAGO,GAAM,CAEhB"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{p as t}from"./validation--qS7OPmg.mjs";import{o as n,r}from"./normalized-result-B8pifWS0.mjs";const i=/\s+/,a=/^[A-Za-z]+$/,o=new Set([`COPY`,`DELETE`,`FETCH`,`INSERT`,`MERGE`,`MOVE`,`SELECT`,`UPDATE`]),s=new Set(`ALTER.ANALYZE.BEGIN.CALL.CHECKPOINT.CLOSE.CLUSTER.COMMENT.COMMIT.CREATE.DEALLOCATE.DECLARE.DISCARD.DO.DROP.END.EXPLAIN.GRANT.IMPORT.LISTEN.LOAD.LOCK.NOTIFY.PREPARE.REASSIGN.REFRESH.REINDEX.RELEASE.RESET.REVOKE.ROLLBACK.SAVEPOINT.SECURITY.SET.SHOW.START.TRUNCATE.UNLISTEN.VACUUM`.split(`.`));function malformedPostgresResult(e,n){return new t(`Driver "${e.provider}" returned malformed PostgreSQL result metadata for operation "${e.operation}": ${n}.`,{meta:r(e)})}function normalizePostgresRowCount(e,t,r,c){if(!Array.isArray(r))throw malformedPostgresResult(c,`the rows payload is not an array`);if(typeof t!=`string`||t.trim()===``)throw malformedPostgresResult(c,`the command tag is invalid`);let[l]=t.trim().split(i,1);if(!(l&&a.test(l)))throw malformedPostgresResult(c,`the command tag is invalid`);let u=l.toUpperCase(),d=o.has(u),f=s.has(u);if(!(d||f))throw malformedPostgresResult(c,`the command tag is unknown`);if(e!==null)return n(e,c);if(d)throw malformedPostgresResult(c,`command ${u} requires a numeric row count`);return r.length}export{normalizePostgresRowCount as t};
|
|
2
|
-
//# sourceMappingURL=postgres-result-DF6DmW3r.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-result-DF6DmW3r.mjs","names":[],"sources":["../src/drivers/shared/postgres-result.ts"],"sourcesContent":["import { QueryError } from \"@errors\";\nimport {\n createNormalizedResultMeta,\n type NormalizedResultContext,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\n\nconst COMMAND_SEPARATOR_REGEX = /\\s+/;\nconst COMMAND_TOKEN_REGEX = /^[A-Za-z]+$/;\n\nconst COUNTED_COMMANDS = new Set([\n \"COPY\",\n \"DELETE\",\n \"FETCH\",\n \"INSERT\",\n \"MERGE\",\n \"MOVE\",\n \"SELECT\",\n \"UPDATE\",\n]);\n\nconst NULLABLE_COUNT_COMMANDS = new Set([\n \"ALTER\",\n \"ANALYZE\",\n \"BEGIN\",\n \"CALL\",\n \"CHECKPOINT\",\n \"CLOSE\",\n \"CLUSTER\",\n \"COMMENT\",\n \"COMMIT\",\n \"CREATE\",\n \"DEALLOCATE\",\n \"DECLARE\",\n \"DISCARD\",\n \"DO\",\n \"DROP\",\n \"END\",\n \"EXPLAIN\",\n \"GRANT\",\n \"IMPORT\",\n \"LISTEN\",\n \"LOAD\",\n \"LOCK\",\n \"NOTIFY\",\n \"PREPARE\",\n \"REASSIGN\",\n \"REFRESH\",\n \"REINDEX\",\n \"RELEASE\",\n \"RESET\",\n \"REVOKE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"SECURITY\",\n \"SET\",\n \"SHOW\",\n \"START\",\n \"TRUNCATE\",\n \"UNLISTEN\",\n \"VACUUM\",\n]);\n\nfunction malformedPostgresResult(\n context: NormalizedResultContext,\n reason: string\n): QueryError {\n return new QueryError(\n `Driver \"${context.provider}\" returned malformed PostgreSQL result metadata for operation \"${context.operation}\": ${reason}.`,\n { meta: createNormalizedResultMeta(context) }\n );\n}\n\n/**\n * PostgreSQL command tags carry a numeric count only for a defined set of\n * commands. Other known tags legitimately expose null, while missing metadata\n * and null counts for counted commands are malformed provider successes.\n */\nexport function normalizePostgresRowCount(\n value: unknown,\n command: unknown,\n rows: unknown,\n context: NormalizedResultContext\n): number {\n if (!Array.isArray(rows)) {\n throw malformedPostgresResult(context, \"the rows payload is not an array\");\n }\n if (typeof command !== \"string\" || command.trim() === \"\") {\n throw malformedPostgresResult(context, \"the command tag is invalid\");\n }\n const [commandToken] = command.trim().split(COMMAND_SEPARATOR_REGEX, 1);\n if (!(commandToken && COMMAND_TOKEN_REGEX.test(commandToken))) {\n throw malformedPostgresResult(context, \"the command tag is invalid\");\n }\n const normalizedCommand = commandToken.toUpperCase();\n const isCountedCommand = COUNTED_COMMANDS.has(normalizedCommand);\n const isNullableCountCommand = NULLABLE_COUNT_COMMANDS.has(normalizedCommand);\n if (!(isCountedCommand || isNullableCountCommand)) {\n throw malformedPostgresResult(context, \"the command tag is unknown\");\n }\n if (value !== null) {\n return normalizeProviderRowCount(value, context);\n }\n if (isCountedCommand) {\n throw malformedPostgresResult(\n context,\n `command ${normalizedCommand} requires a numeric row count`\n );\n }\n return rows.length;\n}\n"],"mappings":"8IAOA,MAAM,EAA0B,MAC1B,EAAsB,cAEtB,EAAmB,IAAI,IAAI,CAC/B,OACA,SACA,QACA,SACA,QACA,OACA,SACA,SACD,CAAC,CAEI,EAA0B,IAAI,IAAI,kSAwCvC,CAAC,CAEF,SAAS,wBACP,EACA,EACY,CACZ,OAAO,IAAI,EACT,WAAW,EAAQ,SAAS,iEAAiE,EAAQ,UAAU,KAAK,EAAO,GAC3H,CAAE,KAAM,EAA2B,EAAQ,CAAE,CAC9C,CAQH,SAAgB,0BACd,EACA,EACA,EACA,EACQ,CACR,GAAI,CAAC,MAAM,QAAQ,EAAK,CACtB,MAAM,wBAAwB,EAAS,mCAAmC,CAE5E,GAAI,OAAO,GAAY,UAAY,EAAQ,MAAM,GAAK,GACpD,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,GAAM,CAAC,GAAgB,EAAQ,MAAM,CAAC,MAAM,EAAyB,EAAE,CACvE,GAAI,EAAE,GAAgB,EAAoB,KAAK,EAAa,EAC1D,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,IAAM,EAAoB,EAAa,aAAa,CAC9C,EAAmB,EAAiB,IAAI,EAAkB,CAC1D,EAAyB,EAAwB,IAAI,EAAkB,CAC7E,GAAI,EAAE,GAAoB,GACxB,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,GAAI,IAAU,KACZ,OAAO,EAA0B,EAAO,EAAQ,CAElD,GAAI,EACF,MAAM,wBACJ,EACA,WAAW,EAAkB,+BAC9B,CAEH,OAAO,EAAK"}
|