viborm 1.13.0 → 1.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -4
- package/dist/{adapter-internals-DZO1WI67.mjs → adapter-internals-DOqI8IlQ.mjs} +2 -2
- package/dist/adapter-internals-DOqI8IlQ.mjs.map +1 -0
- package/dist/adapter-namespace-DaRiTIIf.mjs +2 -0
- package/dist/{adapter-namespace-C9RM19_J.mjs.map → adapter-namespace-DaRiTIIf.mjs.map} +1 -1
- package/dist/{adapter-result-parser-Bz3WtMBa.mjs → adapter-result-parser-3WP82Cm-.mjs} +1 -1
- package/dist/{adapter-result-parser-Bz3WtMBa.mjs.map → adapter-result-parser-3WP82Cm-.mjs.map} +1 -1
- package/dist/adapters.d.mts +755 -1
- package/dist/adapters.mjs +1 -1
- package/dist/args-764KdWMr.mjs +2 -0
- package/dist/args-764KdWMr.mjs.map +1 -0
- package/dist/{array-literal-DfgmVxKI.mjs → array-literal-DHinAnVs.mjs} +1 -1
- package/dist/{array-literal-DfgmVxKI.mjs.map → array-literal-DHinAnVs.mjs.map} +1 -1
- package/dist/async-dispose-d96wFNu6.mjs +2 -0
- package/dist/async-dispose-d96wFNu6.mjs.map +1 -0
- package/dist/base-z-cH5ZBI.mjs +2 -0
- package/dist/base-z-cH5ZBI.mjs.map +1 -0
- package/dist/{batch-refs-DShoaHb7.mjs → batch-refs-C-gx7A4-.mjs} +2 -2
- package/dist/{batch-refs-DShoaHb7.mjs.map → batch-refs-C-gx7A4-.mjs.map} +1 -1
- package/dist/bind-parameter-capacity-BMD-bxMO.mjs +2 -0
- package/dist/bind-parameter-capacity-BMD-bxMO.mjs.map +1 -0
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/bun-sqlite.mjs.map +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/cloudflare-kv.mjs.map +1 -1
- package/dist/cache/memory.d.mts +2 -2
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache/memory.mjs.map +1 -1
- package/dist/cache.d.mts +58 -4
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/call-Cz8XUmrl.mjs +2 -0
- package/dist/call-Cz8XUmrl.mjs.map +1 -0
- package/dist/{canonical-json-B6J5VbLv.mjs → canonical-json-Bl-fKFF_.mjs} +2 -2
- package/dist/{canonical-json-B6J5VbLv.mjs.map → canonical-json-Bl-fKFF_.mjs.map} +1 -1
- package/dist/cli.mjs +7 -5
- package/dist/cli.mjs.map +1 -1
- package/dist/{client-Dx-6NncH.d.mts → client-D1shn5AL.d.mts} +22 -3
- package/dist/client-DRpX3-vw.mjs +2 -0
- package/dist/client-DRpX3-vw.mjs.map +1 -0
- package/dist/client-DzXpmSNi.mjs +9 -0
- package/dist/client-DzXpmSNi.mjs.map +1 -0
- package/dist/client.d.mts +3 -2
- package/dist/client.mjs +2 -1
- package/dist/client.mjs.map +1 -0
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/confine-DqFBTUw6.mjs +2 -0
- package/dist/confine-DqFBTUw6.mjs.map +1 -0
- package/dist/coordination-6qZHx_kl.mjs +2 -0
- package/dist/coordination-6qZHx_kl.mjs.map +1 -0
- package/dist/{current-nScH-oH5.mjs → current-DBTlPsQg.mjs} +1 -1
- package/dist/{current-nScH-oH5.mjs.map → current-DBTlPsQg.mjs.map} +1 -1
- package/dist/d1.d.mts +3 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{index-B8MMx5Al.d.mts → database-adapter-BD_htd5h.d.mts} +9039 -9523
- package/dist/datetime-physical-codec-Dj-APo9f.mjs +2 -0
- package/dist/{datetime-physical-codec-kE6fh5zZ.mjs.map → datetime-physical-codec-Dj-APo9f.mjs.map} +1 -1
- package/dist/defaults-DwOHWI_M.mjs +2 -0
- package/dist/defaults-DwOHWI_M.mjs.map +1 -0
- package/dist/document-rMfLKZP5.d.mts +288 -0
- package/dist/driver-BGVcgnIX.mjs +2 -0
- package/dist/driver-BGVcgnIX.mjs.map +1 -0
- package/dist/driver-BIXhOH2_.mjs +2 -0
- package/dist/driver-BIXhOH2_.mjs.map +1 -0
- package/dist/driver-CH9qAuft.d.mts +235 -0
- package/dist/driver-diagnostics-DW9NdckJ.mjs +2 -0
- package/dist/driver-diagnostics-DW9NdckJ.mjs.map +1 -0
- package/dist/driver.d.mts +2 -2
- package/dist/driver.mjs +1 -1
- package/dist/durable-object.d.mts +58 -0
- package/dist/durable-object.mjs +3 -0
- package/dist/durable-object.mjs.map +1 -0
- package/dist/error-mapping-B1-IWkCQ.mjs +2 -0
- package/dist/error-mapping-B1-IWkCQ.mjs.map +1 -0
- package/dist/every-KV5yuSVT.mjs +2 -0
- package/dist/every-KV5yuSVT.mjs.map +1 -0
- package/dist/execution-context-BXpcbyPe.mjs +2 -0
- package/dist/execution-context-BXpcbyPe.mjs.map +1 -0
- package/dist/exports-nYDS0SZ7.d.mts +47 -0
- package/dist/extension-CGepsF-p.mjs +2 -0
- package/dist/extension-CGepsF-p.mjs.map +1 -0
- package/dist/{fs-estate-Bfy9RFvT.mjs → fs-estate-D1Nsg9G1.mjs} +2 -2
- package/dist/{fs-estate-Bfy9RFvT.mjs.map → fs-estate-D1Nsg9G1.mjs.map} +1 -1
- package/dist/geo-area-codec-mHrM3b9A.mjs +2 -0
- package/dist/{geo-area-codec-B3QtKij8.mjs.map → geo-area-codec-mHrM3b9A.mjs.map} +1 -1
- package/dist/hydration-A3zffFWP.mjs +2 -0
- package/dist/{hydration-Dd2H4EyY.mjs.map → hydration-A3zffFWP.mjs.map} +1 -1
- package/dist/identifier-conversion-DHYPTgzr.mjs +2 -0
- package/dist/{identifier-conversion-771tvRzd.mjs.map → identifier-conversion-DHYPTgzr.mjs.map} +1 -1
- package/dist/{identifiers-DLcLFNim.mjs → identifiers-s00pGES8.mjs} +1 -1
- package/dist/{identifiers-DLcLFNim.mjs.map → identifiers-s00pGES8.mjs.map} +1 -1
- package/dist/identity-CtW15WlB.mjs +2 -0
- package/dist/identity-CtW15WlB.mjs.map +1 -0
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +50 -18
- package/dist/instrumentation.mjs +1 -1
- package/dist/instrumentation.mjs.map +1 -1
- package/dist/introspect-DD_5FEl0.mjs +2 -0
- package/dist/introspect-DD_5FEl0.mjs.map +1 -0
- package/dist/json-DgMc8-GU.mjs +2 -0
- package/dist/json-DgMc8-GU.mjs.map +1 -0
- package/dist/{json-number-ChtP7ZeY.mjs → json-number-AI-SdUUn.mjs} +1 -1
- package/dist/{json-number-ChtP7ZeY.mjs.map → json-number-AI-SdUUn.mjs.map} +1 -1
- package/dist/json-parameter-oQ8nGaKr.mjs +2 -0
- package/dist/json-parameter-oQ8nGaKr.mjs.map +1 -0
- package/dist/judge-words-CzUyXtJ6.mjs +2 -0
- package/dist/judge-words-CzUyXtJ6.mjs.map +1 -0
- package/dist/key-hxFFCKed.mjs +2 -0
- package/dist/key-hxFFCKed.mjs.map +1 -0
- package/dist/keys-BQxM4c_a.mjs +2 -0
- package/dist/keys-BQxM4c_a.mjs.map +1 -0
- package/dist/libsql-DuGR904j.mjs +3 -0
- package/dist/libsql-DuGR904j.mjs.map +1 -0
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/light-BkJe3-yW.mjs +2 -0
- package/dist/light-BkJe3-yW.mjs.map +1 -0
- package/dist/memory-G4cSuc6A.mjs +2 -0
- package/dist/{memory-CsRVfZdT.mjs.map → memory-G4cSuc6A.mjs.map} +1 -1
- package/dist/methods-part-ZY0f2AV_.mjs +2 -0
- package/dist/methods-part-ZY0f2AV_.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +5 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/mysql.mjs.map +1 -1
- package/dist/migrations/postgres.d.mts +5 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/postgres.mjs.map +1 -1
- package/dist/migrations/snowflake.d.mts +6 -0
- package/dist/migrations/snowflake.mjs +2 -0
- package/dist/migrations/snowflake.mjs.map +1 -0
- package/dist/migrations/sqlite.d.mts +5 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/sqlite.mjs.map +1 -1
- package/dist/migrations/storage/durable-object.d.mts +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.d.mts +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/surrealdb.d.mts +5 -5
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/surrealdb.mjs.map +1 -1
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations/tenant.mjs.map +1 -1
- package/dist/migrations-BMiRjR-N.mjs +2 -0
- package/dist/{migrations-OE5D32qo.mjs.map → migrations-BMiRjR-N.mjs.map} +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/migrations.mjs.map +1 -1
- package/dist/mysql-BNXWfTOo.mjs +100 -0
- package/dist/mysql-BNXWfTOo.mjs.map +1 -0
- package/dist/mysql-adapter-C69j1sKh.mjs +2 -0
- package/dist/mysql-adapter-C69j1sKh.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/native-types-DgjMUikz.mjs +2 -0
- package/dist/native-types-DgjMUikz.mjs.map +1 -0
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/normalized-result-B8pifWS0.mjs +2 -0
- package/dist/normalized-result-B8pifWS0.mjs.map +1 -0
- package/dist/{object-store-DlGfGCb4.d.mts → object-store-0zc3XYcO.d.mts} +4 -4
- package/dist/{object-store-DdKoB-lN.mjs → object-store-DS0F0yZX.mjs} +2 -2
- package/dist/{object-store-DdKoB-lN.mjs.map → object-store-DS0F0yZX.mjs.map} +1 -1
- package/dist/on-ylYaKuRu.mjs +2 -0
- package/dist/on-ylYaKuRu.mjs.map +1 -0
- package/dist/on.d.mts +12 -19
- package/dist/on.mjs +1 -1
- package/dist/on.mjs.map +1 -1
- package/dist/ordering/keys.d.mts +37 -0
- package/dist/ordering/keys.mjs +1 -0
- package/dist/ordering.d.mts +85 -85
- package/dist/ordering.mjs +4 -4
- package/dist/ordering.mjs.map +1 -1
- package/dist/pending-operation-C_eOFOBE.mjs +2 -0
- package/dist/pending-operation-C_eOFOBE.mjs.map +1 -0
- package/dist/permissions.d.mts +88 -147
- package/dist/permissions.mjs +1 -1
- package/dist/permissions.mjs.map +1 -1
- package/dist/pg.d.mts +1 -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/pglite.mjs.map +1 -1
- package/dist/physical-CeE2nYmI.mjs +2 -0
- package/dist/{physical-CjG29tya.mjs.map → physical-CeE2nYmI.mjs.map} +1 -1
- package/dist/pinned-session-DCoAZDOz.mjs +2 -0
- package/dist/{pinned-session-De2rDjdO.mjs.map → pinned-session-DCoAZDOz.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-DUjM5jQk.d.mts → planner-uYQS0hif.d.mts} +12 -1
- package/dist/{postgres-V7noUFbG.mjs → postgres-CDdh5dSP.mjs} +33 -23
- package/dist/postgres-CDdh5dSP.mjs.map +1 -0
- package/dist/postgres-adapter-Dlr3ZWd7.mjs +2 -0
- package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +1 -0
- package/dist/postgres-adapter-axapXX8d.mjs +2 -0
- package/dist/{postgres-adapter-CvLB764t.mjs.map → postgres-adapter-axapXX8d.mjs.map} +1 -1
- package/dist/{postgres-result-CJ8C5cck.mjs → postgres-result-DF6DmW3r.mjs} +2 -2
- package/dist/{postgres-result-CJ8C5cck.mjs.map → postgres-result-DF6DmW3r.mjs.map} +1 -1
- package/dist/postgres.d.mts +1 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/provider-limits-Ccsb8PTb.mjs +2 -0
- package/dist/provider-limits-Ccsb8PTb.mjs.map +1 -0
- package/dist/provider-parameter-snapshot-BikrgKqI.mjs +2 -0
- package/dist/provider-parameter-snapshot-BikrgKqI.mjs.map +1 -0
- package/dist/query-BZVHfA0s.mjs +2 -0
- package/dist/query-BZVHfA0s.mjs.map +1 -0
- package/dist/query-inspection-BoG-yAln.mjs +2 -0
- package/dist/query-inspection-BoG-yAln.mjs.map +1 -0
- package/dist/raw-Dyq6Y6UX.mjs +2 -0
- package/dist/raw-Dyq6Y6UX.mjs.map +1 -0
- package/dist/{relation-bound-C02WchLT.mjs → relation-bound-ku_cMdye.mjs} +1 -1
- package/dist/{relation-bound-C02WchLT.mjs.map → relation-bound-ku_cMdye.mjs.map} +1 -1
- package/dist/{result-parsing-Bj0gVF-R.mjs → result-parsing-B0Y4KGDT.mjs} +1 -1
- package/dist/{result-parsing-Bj0gVF-R.mjs.map → result-parsing-B0Y4KGDT.mjs.map} +1 -1
- package/dist/routed-operations-wytpbYKv.mjs +2 -0
- package/dist/routed-operations-wytpbYKv.mjs.map +1 -0
- package/dist/rule-words-ZIGm7cDm.mjs +2 -0
- package/dist/rule-words-ZIGm7cDm.mjs.map +1 -0
- package/dist/scalar-BHCh7aUz.mjs +4 -0
- package/dist/scalar-BHCh7aUz.mjs.map +1 -0
- package/dist/schema/introspect.d.mts +97 -0
- package/dist/schema/introspect.mjs +1 -0
- package/dist/schema/json.d.mts +3 -278
- package/dist/schema/json.mjs +1 -2
- package/dist/schema-BYA-_bpk.mjs +2 -0
- package/dist/schema-BYA-_bpk.mjs.map +1 -0
- package/dist/schema-CFIaebgi.mjs +2 -0
- package/dist/{schema-DKL7GSu7.mjs.map → schema-CFIaebgi.mjs.map} +1 -1
- package/dist/schema-introspection-D0f8cti4.mjs +6 -0
- package/dist/{schema-introspection-BogU9kCO.mjs.map → schema-introspection-D0f8cti4.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-BL9BG6oR.mjs → select-assembly-DVI7d3tf.mjs} +2 -2
- package/dist/{select-assembly-BL9BG6oR.mjs.map → select-assembly-DVI7d3tf.mjs.map} +1 -1
- package/dist/serializer-rBq3v1xr.mjs +51 -0
- package/dist/serializer-rBq3v1xr.mjs.map +1 -0
- package/dist/settle-1cy5x_52.mjs +2 -0
- package/dist/settle-1cy5x_52.mjs.map +1 -0
- package/dist/settled-BjyuA76m.mjs +2 -0
- package/dist/settled-BjyuA76m.mjs.map +1 -0
- package/dist/snowflake-UOCC820W.mjs +2 -0
- package/dist/snowflake-UOCC820W.mjs.map +1 -0
- package/dist/snowflake.d.mts +473 -0
- package/dist/snowflake.mjs +3 -0
- package/dist/snowflake.mjs.map +1 -0
- package/dist/soft-delete.d.mts +27 -169
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/spans-XDUFeTzC.mjs +2 -0
- package/dist/spans-XDUFeTzC.mjs.map +1 -0
- package/dist/{sql-BsBoKwaf.mjs → sql-3o4DOKm9.mjs} +1 -1
- package/dist/{sql-BsBoKwaf.mjs.map → sql-3o4DOKm9.mjs.map} +1 -1
- package/dist/sql-Dl6nykFV.mjs +2 -0
- package/dist/sql-Dl6nykFV.mjs.map +1 -0
- package/dist/{sql-statement-tokens-ugBPr6SM.mjs → sql-statement-tokens-DbeMwHra.mjs} +1 -1
- package/dist/{sql-statement-tokens-ugBPr6SM.mjs.map → sql-statement-tokens-DbeMwHra.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-Ad0d-m2t.mjs +2 -0
- package/dist/sqlite-adapter-Ad0d-m2t.mjs.map +1 -0
- package/dist/sqlite-statement-classifier-BAHl-WXS.mjs +2 -0
- package/dist/sqlite-statement-classifier-BAHl-WXS.mjs.map +1 -0
- package/dist/sqlite-utils-BRvbmlQ1.mjs +2 -0
- package/dist/{sqlite-utils-B-Y47_Uz.mjs.map → sqlite-utils-BRvbmlQ1.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/standard-sql-qLcQyCtK.mjs +6 -0
- package/dist/standard-sql-qLcQyCtK.mjs.map +1 -0
- package/dist/{suppressed-failure-DO0ej03b.mjs → suppressed-failure-CQkQsMVS.mjs} +1 -1
- package/dist/{suppressed-failure-DO0ej03b.mjs.map → suppressed-failure-CQkQsMVS.mjs.map} +1 -1
- package/dist/surrealdb.d.mts +36 -6
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/surrealql-DpipDgMB.mjs +2 -0
- package/dist/surrealql-DpipDgMB.mjs.map +1 -0
- package/dist/to-many-BybuKQM1.mjs +2 -0
- package/dist/to-many-BybuKQM1.mjs.map +1 -0
- package/dist/transaction-BNomMtme.mjs +2 -0
- package/dist/transaction-BNomMtme.mjs.map +1 -0
- package/dist/{transaction-operation-Km-Gr-a3.mjs → transaction-operation-CVVJxQ19.mjs} +2 -2
- package/dist/transaction-operation-CVVJxQ19.mjs.map +1 -0
- package/dist/{types-C4v6iAmY.mjs → types-DtDnXhwa.mjs} +1 -1
- package/dist/{types-C4v6iAmY.mjs.map → types-DtDnXhwa.mjs.map} +1 -1
- package/dist/unit-BhHbZyuJ.mjs +2 -0
- package/dist/unit-BhHbZyuJ.mjs.map +1 -0
- package/dist/unit-words-CT0yeqfZ.mjs +2 -0
- package/dist/unit-words-CT0yeqfZ.mjs.map +1 -0
- package/dist/utils-CpAojrCj.mjs +26 -0
- package/dist/{utils-CuQHO2NF.mjs.map → utils-CpAojrCj.mjs.map} +1 -1
- package/dist/validation--qS7OPmg.mjs +2 -0
- package/dist/validation--qS7OPmg.mjs.map +1 -0
- package/dist/validation-CYaJ8ndO.mjs +2 -0
- package/dist/validation-CYaJ8ndO.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-CZLW7aR3.mjs +2 -0
- package/dist/validator-CZLW7aR3.mjs.map +1 -0
- package/dist/{value-guards-CK9guf2Z.mjs → value-guards-CBuxSC66.mjs} +1 -1
- package/dist/{value-guards-CK9guf2Z.mjs.map → value-guards-CBuxSC66.mjs.map} +1 -1
- package/dist/values-B4aj1i1f.mjs +2 -0
- package/dist/values-B4aj1i1f.mjs.map +1 -0
- package/dist/version-DRfmNoR1.mjs +2 -0
- package/dist/{version-Ce4zn8qc.mjs.map → version-DRfmNoR1.mjs.map} +1 -1
- package/dist/write-sinks-3IKCDF-S.mjs +2 -0
- package/dist/write-sinks-3IKCDF-S.mjs.map +1 -0
- package/package.json +92 -36
- package/dist/adapter-internals-DZO1WI67.mjs.map +0 -1
- package/dist/adapter-namespace-C9RM19_J.mjs +0 -2
- package/dist/base-wlv81COV.mjs +0 -2
- package/dist/base-wlv81COV.mjs.map +0 -1
- package/dist/bind-parameter-capacity-Bjgx1lMC.mjs +0 -2
- package/dist/bind-parameter-capacity-Bjgx1lMC.mjs.map +0 -1
- package/dist/builder-yLL4r6JS.mjs +0 -2
- package/dist/builder-yLL4r6JS.mjs.map +0 -1
- package/dist/chain-3bgO2RX3.mjs +0 -2
- package/dist/chain-3bgO2RX3.mjs.map +0 -1
- package/dist/client-Bbke7iRo.mjs +0 -50
- package/dist/client-Bbke7iRo.mjs.map +0 -1
- package/dist/client-nkU6M5bV.mjs +0 -2
- package/dist/client-nkU6M5bV.mjs.map +0 -1
- package/dist/clock-DXbsDHLj.mjs +0 -2
- package/dist/clock-DXbsDHLj.mjs.map +0 -1
- package/dist/datetime-physical-codec-kE6fh5zZ.mjs +0 -2
- package/dist/driver-BRYL6K0W.mjs +0 -2
- package/dist/driver-BRYL6K0W.mjs.map +0 -1
- package/dist/driver-CcEhJcsE.mjs +0 -2
- package/dist/driver-CcEhJcsE.mjs.map +0 -1
- package/dist/error-mapping-DW7TYOyA.mjs +0 -2
- package/dist/error-mapping-DW7TYOyA.mjs.map +0 -1
- package/dist/every-hDecAr5k.mjs +0 -2
- package/dist/every-hDecAr5k.mjs.map +0 -1
- package/dist/execution-context-_oajgBi4.mjs +0 -2
- package/dist/execution-context-_oajgBi4.mjs.map +0 -1
- package/dist/geo-area-codec-B3QtKij8.mjs +0 -2
- package/dist/geo-point-codec-Ggv29hSH.mjs +0 -2
- package/dist/geo-point-codec-Ggv29hSH.mjs.map +0 -1
- package/dist/hydration-Dd2H4EyY.mjs +0 -2
- package/dist/identifier-conversion-771tvRzd.mjs +0 -2
- package/dist/identity-b2N94bh1.mjs +0 -2
- package/dist/identity-b2N94bh1.mjs.map +0 -1
- package/dist/invariant-CKZrz_S2.mjs +0 -2
- package/dist/invariant-CKZrz_S2.mjs.map +0 -1
- package/dist/key-B4B1etH3.mjs +0 -2
- package/dist/key-B4B1etH3.mjs.map +0 -1
- package/dist/keys-BcQgRjMB.mjs +0 -2
- package/dist/keys-BcQgRjMB.mjs.map +0 -1
- package/dist/keys-M0pWraMM.mjs +0 -2
- package/dist/keys-M0pWraMM.mjs.map +0 -1
- package/dist/libsql-lOqKLyZA.mjs +0 -11
- package/dist/libsql-lOqKLyZA.mjs.map +0 -1
- package/dist/memory-CsRVfZdT.mjs +0 -2
- package/dist/migrations-OE5D32qo.mjs +0 -2
- package/dist/model-DK9BhhNF.mjs +0 -2
- package/dist/model-DK9BhhNF.mjs.map +0 -1
- package/dist/mysql-CIdv4h7j.mjs +0 -100
- package/dist/mysql-CIdv4h7j.mjs.map +0 -1
- package/dist/mysql-adapter-C3d-TdaO.mjs +0 -2
- package/dist/mysql-adapter-C3d-TdaO.mjs.map +0 -1
- package/dist/native-types-CQH05hcr.mjs +0 -2
- package/dist/native-types-CQH05hcr.mjs.map +0 -1
- package/dist/normalized-result-ByvlIQqa.mjs +0 -2
- package/dist/normalized-result-ByvlIQqa.mjs.map +0 -1
- package/dist/observation-BcT8Cs3d.mjs +0 -2
- package/dist/observation-BcT8Cs3d.mjs.map +0 -1
- package/dist/physical-CjG29tya.mjs +0 -2
- package/dist/pinned-session-De2rDjdO.mjs +0 -2
- package/dist/postgres-V7noUFbG.mjs.map +0 -1
- package/dist/postgres-adapter-CvLB764t.mjs +0 -2
- package/dist/postgres-adapter-D53hxZM4.mjs +0 -2
- package/dist/postgres-adapter-D53hxZM4.mjs.map +0 -1
- package/dist/provider-limits-DolYOv3_.mjs +0 -2
- package/dist/provider-limits-DolYOv3_.mjs.map +0 -1
- package/dist/query-CTna5P9o.mjs +0 -2
- package/dist/query-CTna5P9o.mjs.map +0 -1
- package/dist/result-shape-D5gZFVps.mjs +0 -2
- package/dist/result-shape-D5gZFVps.mjs.map +0 -1
- package/dist/rows-B1SG8qg9.mjs +0 -2
- package/dist/rows-B1SG8qg9.mjs.map +0 -1
- package/dist/rows-of-qH0_KyL6.mjs +0 -2
- package/dist/rows-of-qH0_KyL6.mjs.map +0 -1
- package/dist/scalar-DNshDNz3.mjs +0 -4
- package/dist/scalar-DNshDNz3.mjs.map +0 -1
- package/dist/schema/json.mjs.map +0 -1
- package/dist/schema-DKL7GSu7.mjs +0 -2
- package/dist/schema-introspection-BogU9kCO.mjs +0 -6
- package/dist/settle-v6QhvFkm.mjs +0 -2
- package/dist/settle-v6QhvFkm.mjs.map +0 -1
- package/dist/sha256-D_fCV62w.mjs +0 -2
- package/dist/sha256-D_fCV62w.mjs.map +0 -1
- package/dist/sqlite-adapter-CVKv1u4i.mjs +0 -2
- package/dist/sqlite-adapter-CVKv1u4i.mjs.map +0 -1
- package/dist/sqlite-utils-B-Y47_Uz.mjs +0 -2
- package/dist/standard-sql-BHpLmLeM.mjs +0 -6
- package/dist/standard-sql-BHpLmLeM.mjs.map +0 -1
- package/dist/surrealql-Bnu3BzHE.mjs +0 -2
- package/dist/surrealql-Bnu3BzHE.mjs.map +0 -1
- package/dist/to-many-Dd1m0XqX.mjs +0 -2
- package/dist/to-many-Dd1m0XqX.mjs.map +0 -1
- package/dist/transaction-D5LHYn-r.mjs +0 -2
- package/dist/transaction-D5LHYn-r.mjs.map +0 -1
- package/dist/transaction-operation-Km-Gr-a3.mjs.map +0 -1
- package/dist/utils-CuQHO2NF.mjs +0 -26
- package/dist/utils-QZGdBir8.mjs +0 -2
- package/dist/utils-QZGdBir8.mjs.map +0 -1
- package/dist/v-CWY9ntMb.mjs +0 -2
- package/dist/v-CWY9ntMb.mjs.map +0 -1
- package/dist/validation-mTttU3Fk.mjs +0 -2
- package/dist/validation-mTttU3Fk.mjs.map +0 -1
- package/dist/validation-pfpKPPZ_.mjs +0 -2
- package/dist/validation-pfpKPPZ_.mjs.map +0 -1
- package/dist/validator-BjNxS3uX.mjs +0 -2
- package/dist/validator-BjNxS3uX.mjs.map +0 -1
- package/dist/version-Ce4zn8qc.mjs +0 -2
- package/dist/write-sinks-Bean5xf5.mjs +0 -2
- package/dist/write-sinks-Bean5xf5.mjs.map +0 -1
- package/dist/writes-BX5fLiw5.mjs +0 -2
- package/dist/writes-BX5fLiw5.mjs.map +0 -1
- /package/dist/{contract-BOwMGvl2.d.mts → contract-CrIB-3ZJ.d.mts} +0 -0
- /package/dist/{sql-BbLhTqDH.d.mts → sql-BVZ8QefY.d.mts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-DRpX3-vw.mjs","names":["#a","#and","#eq","#at","#named","#escaped","#cast","#inner","#true","#false","#null","#literal","#document","#object","#aside","#or","#isNull","#isNotNull","#rows","#shared","#settled","reaching","materialized","#rankedWalks","sql","#flagging","after","same","own","#keyArrays","#flagSet","member","flagged","columns","#shares","#sharingBodies","call","#boundOf","#setBound","#negative","#enclosing","#lowersLayer","#nextAlias","#attachPoint","#tableNamed","#pinned","#scalarValue","#listValue","#typedScalarValue","#geoPoint","#projectedTypedColumn","#when","#prepareUpdate","#arithmeticTarget","#frames","#lowerStated","#lowerPredicate","#within","#scalar","#capped","#apart","#opposite","#bound","#lowerRelationPredicate","#lowerExists","#boundParameters","#guarded","#masked","#gates","#preparedColumn","#aggregateExpression","#lowerTarget","#lowerJsonOperation","text","#outerAlias","#targetValue","operand","#lowerOtherOperation","list","#distanceExpression","#sumTargetValue","#rowAlias","#inside","#correlated","#quantified","#sharedWalk","#relationExists","#membershipWhere","#relatedWhere","#bounded","#junctionJoin","#attached","#placed","name","#reachingSet","#aliased","#rowKey","#all","#predecessor","#joinsPredecessor","#covers","row","#side","#related","#orderTerm","#relationOrderTerm","#operand","#gatedHere","#sortKey","#correlatedCount","#joinsOnce","#orderTerms","#totalOrder","#reverseOrder","#lowerOrder","#distinctOrder","#cursorCondition","#completeOrder","#identityEntries","#sharingQuery","#select","#page","prepared","#selectWhere","#read","#ordered","#candidates","#readAggregate","rows","#prepareAggregates","#overMasked","#aggregateLeaf","#carriedValue","#splitSumSql","#selectSeries","#lowerProjectionField","#orphanedMemberships","#lowerRelationProjection","#parentClaimsArm","#missingArm","#duplicateMembershipGuard","#lowerRecursiveRelationProjection","#lowerSpecialProjectionField","#links","#linkBound","#memberSource","#junctionTarget","#step","#recursiveIdentity","nodeFacts","edgeFacts","#grouped","#prepareHaving","#groupOrderTerms","#owner","#caller","#own","#correlation","response","#published","prepared","#package","#compute","#overWrite","#overWrites","text","sql","transport","sent","within","#q","#related","#projections","#within","sql","#answered","#among","#limited","#sets","sent","side","#name","#transport","#hear","#ran","#meta","#known","#log","#missed","#presumed","#used","#stale","#touched","#again","#made","#members","#says","#absences","#left","#learnt","#learn","#settle","#sent","#whole","sent","#deliver","#steps","#delivered","#concrete","#answers","#asserted","#outcomes","#handed","after","#said","#raw","loose","#absent","#of","#about","#waited","#linked","#holds","#changed","#rows","#spoiled","#links","#recalled","read","#presume","#intern","#attempting","#heard","#note","raw","#seen","#spoil","#follow","#key","#cascades","#writing","#end","#told","#copies","own","key","#asked","asked","same","rows","#attempted","#store","#operation","#schema","#q","#said","#nested","#leave","#within","#paired","#stated","#writes","#plain","#members","#several","#write","#made","#born","#join","#keyed","#make","#relationsOf","#spelled","#relationsIn","#referencing","relations","#holds","#slots","#moved","#cleared","row","#single","#once","#after","#relate","#computed","#moves","old","#reaching","entries","#set","#one","#answering","#many","#removes","loose","#config","#queries","#modelName","#requested","#operation","#rawArgs","#scope","#model","#missing","#admitted","#prepared","#read","#facts","#context","isPlainRecord","rewritten","#schema","#engine","#relations","#registry","relations","#prepareModelOperation","call","#extensionOmitResolvers","#createClient","#transact","#createViewProxy","#createView","#resolveClientOmit","#createRootView","prepared"],"sources":["../src/query-engine/query-engine.ts","../src/query-engine/raptor3/shared/query-backend.ts","../src/drivers/positional-result.ts","../src/sql/slot.ts","../src/query-engine/raptor3/shared/invariant.ts","../src/query-engine/raptor3/shared/sql-queries.ts","../src/query-engine/raptor3/shared/sql-operation-context.ts","../src/query-engine/raptor3/write/send.ts","../src/query-engine/raptor3/write/statements.ts","../src/query-engine/raptor3/write/store.ts","../src/query-engine/raptor3/write/verbs.ts","../src/query-engine/raptor3/write/index.ts","../src/query-engine/raptor3/commands/index.ts","../src/client/omit.ts","../src/client/unique-where-guard.ts","../src/client/client.ts"],"sourcesContent":["import type { AnyDriver } from \"@drivers/exports\";\nimport type { AdmittedArgs } from \"@extensions/arguments\";\nimport type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type { TransactionScope } from \"@extensions/query\";\nimport type { Model } from \"@schema/model\";\nimport {\n createPendingOperation,\n type PendingOperation,\n type PrepareOperationInput,\n type PrepareWriteOutcomeRegistration,\n} from \"./pending-operation\";\nimport type { CommandEngine } from \"./raptor3/commands\";\nimport type { Operation, PrepareOptions } from \"./types\";\n\n/** Client-scoped owner of query infrastructure and operation creation. */\nexport class QueryEngine {\n readonly driver: AnyDriver;\n readonly extensionChain: ResolvedExtensionChain | undefined;\n /**\n * The transaction scope this engine runs in, inside a callback\n * transaction: what its calls register there waits for its end.\n */\n readonly transaction: TransactionScope | undefined;\n /**\n * The argument values this view binds, admitted on each of its calls as if\n * passed. Every engine bound from it keeps them (transactions, `$extends`).\n */\n readonly bound: AdmittedArgs | undefined;\n\n /**\n * Identity of the originating client lineage. Transaction-bound engines\n * preserve this identifier.\n */\n readonly clientId: symbol;\n /** Identity of the current root or transaction-bound execution scope. */\n readonly scopeId: symbol;\n /**\n * The ONE operation owner of this engine (C-01). A client builds it in\n * `VibORM`'s constructor over the one resolved topology index and schema\n * registry, and `bind()` forwards it, so every engine of a lineage shares it\n * by identity and no engine has two.\n */\n readonly route: CommandEngine;\n\n constructor(\n driver: AnyDriver,\n route: CommandEngine,\n clientId = Symbol(\"viborm.client\"),\n scopeId = Symbol(\"viborm.scope\"),\n extensionChain?: ResolvedExtensionChain,\n transaction?: TransactionScope,\n bound?: AdmittedArgs\n ) {\n this.driver = driver;\n this.route = route;\n this.extensionChain = extensionChain;\n this.transaction = transaction;\n this.clientId = clientId;\n this.scopeId = scopeId;\n this.bound = bound;\n }\n\n /**\n * This engine with other bound values: the same scope, so operations of\n * both may share one array transaction.\n */\n withBound(bound: AdmittedArgs): QueryEngine {\n return new QueryEngine(\n this.driver,\n this.route,\n this.clientId,\n this.scopeId,\n this.extensionChain,\n this.transaction,\n bound\n );\n }\n\n bind(\n driver: AnyDriver,\n extensionChain: ResolvedExtensionChain | undefined = this.extensionChain,\n transaction: TransactionScope | undefined = this.transaction\n ): QueryEngine {\n return new QueryEngine(\n driver,\n this.route,\n this.clientId,\n Symbol(\"viborm.scope\"),\n extensionChain,\n transaction,\n this.bound\n );\n }\n\n /**\n * Prepare an operation and return a PendingOperation ready for execution.\n */\n prepare<T>(\n model: Model<any>,\n operation: Operation | `${Operation}OrThrow`,\n args: Record<string, unknown>,\n options?: PrepareOptions,\n prepareInput?: PrepareOperationInput,\n prepareWriteOutcomeRegistration?: PrepareWriteOutcomeRegistration\n ): PendingOperation<T> {\n return createPendingOperation<T>(\n this,\n model,\n operation,\n args,\n options,\n prepareInput,\n prepareWriteOutcomeRegistration\n );\n }\n}\n","/**\n * What a language supplies to the engine: `docs/architecture/query-backend-frontier.md`.\n * The classes own what reads and writes mean and how rows decode. Their abstract\n * members are what is written in the language, and a backend that leaves one out\n * does not compile.\n */\n\nimport type { Writer } from \"../write/statements\";\nimport type { Queries } from \"./query\";\nimport type { SqlOperationContext } from \"./sql-operation-context\";\n\ndeclare const OPAQUE: unique symbol;\n\n/**\n * A driver's backend as the published types see it: opaque, so the engine's\n * classes stay out of every entry's declarations. {@link engineBackend} is the\n * one crossing back.\n */\nexport interface QueryBackend {\n readonly [OPAQUE]: \"QueryBackend\";\n}\n\n/** What a driver states as its backend. */\nexport const queryBackend = (backend: EngineBackend): QueryBackend =>\n backend as never;\n\n/** What the engine reads of a driver's backend. */\nexport const engineBackend = (backend: QueryBackend): EngineBackend =>\n backend as never;\n\n/** What a language supplies: how its statements read, what one call is in it, and what writes the write path's statements. */\nexport interface EngineBackend {\n readonly queries: new (\n ...args: ConstructorParameters<typeof Queries>\n ) => Queries;\n readonly context: typeof SqlOperationContext;\n readonly writer: new (operation: SqlOperationContext) => Writer;\n}\n","import { QueryError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport type { AnyDriver } from \"./driver\";\nimport {\n createNormalizedResultMeta,\n type NormalizedResultContext,\n} from \"./normalized-result\";\nimport type { QueryExecutionContext, QueryResult } from \"./types\";\n\n/** Internal projection transport; the public driver result remains object rows. */\nexport interface PositionalQueryResult {\n readonly kind: \"positional\";\n readonly rows: unknown[][];\n readonly columns: readonly string[];\n}\n\nexport type ProjectionExecutionResult =\n | PositionalQueryResult\n | { readonly kind: \"borrowed\"; readonly result: QueryResult<unknown> };\n\nexport type PositionalExecute = (\n query: Sql,\n context: QueryExecutionContext\n) => Promise<ProjectionExecutionResult>;\n\ninterface PositionalResultDriver {\n readonly execute: PositionalExecute;\n readonly isEligible: (driver: AnyDriver) => boolean;\n}\n\nconst positionalDrivers = new WeakMap<AnyDriver, PositionalResultDriver>();\n\nexport function registerPositionalResultDriver(\n driver: AnyDriver,\n execute: PositionalExecute,\n isEligible: (driver: AnyDriver) => boolean\n): void {\n positionalDrivers.set(driver, { execute, isEligible });\n}\n\nexport function resolvePositionalResultDriver(\n driver: AnyDriver\n): PositionalExecute | undefined {\n const candidate = positionalDrivers.get(driver);\n return candidate?.isEligible(driver) ? candidate.execute : undefined;\n}\n\nexport function assertPositionalRows(\n rows: unknown[],\n columns: readonly string[],\n context: NormalizedResultContext\n): asserts rows is unknown[][] {\n for (let index = 0; index < rows.length; index++) {\n const row = rows[index];\n if (\n !(Object.hasOwn(rows, index) && Array.isArray(row)) ||\n row.length !== columns.length\n ) {\n throw new QueryError(\n `Driver \"${context.provider}\" returned malformed positional rows for operation \"${context.operation}\".`,\n { meta: createNormalizedResultMeta(context) }\n );\n }\n }\n}\n\n/** A changed execution/parser surface must see the usual keyed provider rows. */\nexport function borrowPositionalResult(\n response: PositionalQueryResult\n): QueryResult<unknown> {\n const rows = response.rows.map((row) =>\n Object.fromEntries(\n response.columns.map((column, index) => [column, row[index]])\n )\n );\n return { rows, rowCount: rows.length };\n}\n","import { Sql } from \"./sql\";\n\n/**\n * A fragment whose text its statement decides once the statement is whole,\n * between two forms known where it is placed: the provisional one until\n * {@link settle}, which the statement's owner calls before anything renders\n * it (rendering a fragment keeps its text, {@link Sql.peek} does not).\n */\nexport class SqlSlot extends Sql {\n constructor(provisional: Sql) {\n super([\"\", \"\"], [provisional]);\n }\n settle(content: Sql): void {\n SqlSlot.fill(this, content);\n }\n}\n","/**\n * The engine's ONE owner of internal invariants (N4, plan §4, D-52).\n *\n * A refusal is a sentence a caller can reach with an admitted payload; an\n * invariant is a state the code cannot be in when it is right, established\n * upstream by a type or by an earlier owner. The two are told apart by CLASS,\n * never by message text: a public refusal is a `VibORMError`, an invariant\n * failure is this internal class, so the refusal census counts one and not\n * the other by construction. Where a type can say the invariant (an\n * exhaustive `switch` over a closed union), {@link unreachable} makes the\n * compiler prove it; where it cannot, {@link assertInvariant} states it in\n * one place with the fact it rests on.\n */\nexport class EngineInvariantError extends Error {\n override readonly name = \"EngineInvariantError\";\n}\n\n/** A `switch` arm the type system already closed: the value has no members. */\nexport function unreachable(value: never, message: string): never {\n throw new EngineInvariantError(`${message}: ${String(value)}`);\n}\n","/**\n * What reads and writes a statement in SQL. {@link Queries} owns the descriptions,\n * which no language appears in, and how rows are decoded; aliases, joins, CTEs and\n * flags belong to this language and live here. Another language answers the same\n * abstract members. See `docs/architecture/query-backend-frontier.md`.\n */\n\nimport type { ArithmeticTarget } from \"@adapters/adapter-core-types\";\nimport {\n adapterPinnedTable,\n assembleAdapterSelect,\n} from \"@adapters/adapter-internals\";\nimport type { QueryParts } from \"@adapters/adapter-query-parts\";\nimport type {\n DatabaseAdapter,\n GeoPointSql,\n TextMatch,\n} from \"@adapters/database-adapter\";\nimport type { Dialect } from \"@drivers/types\";\nimport { FeatureNotSupportedError, QueryEngineError } from \"@errors\";\nimport {\n CURSOR_CARRIER_PREFIX,\n POLYMORPHIC_COLLECTION_ORPHANS_KEY,\n} from \"@query-engine/result-aliases\";\nimport { jsonNullKindOf } from \"@schema/json-null\";\nimport {\n type AnyModel,\n findAddressableKey,\n getModelKeyCatalog,\n} from \"@schema/model\";\nimport { slotMayBeEmpty } from \"@schema/relation/clearability\";\nimport type { ResolvedJunctionSide } from \"@schema/relation/junction-topology\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport type { ScalarState } from \"@schema/scalars/common\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport { Sql, sql } from \"@sql\";\nimport { geoBoundsForDistance } from \"@validation/primitives/geo-area-codec\";\nimport type { GeoArea, GeoPoint } from \"@validation/primitives/geo-values\";\nimport {\n validateIsoDate,\n validateIsoTime,\n validateIsoTimestamp,\n} from \"@validation/primitives/iso\";\nimport type { NormalizedRecurrence } from \"@validation/relations/recurrence\";\nimport { SqlSlot } from \"../../../sql/slot\";\nimport {\n canonicalDecimal,\n decimalMembers,\n decimalSumOperand,\n dividesByZero,\n exactDecimalDomain,\n requireDecimal,\n} from \"./decimal\";\nimport {\n aggregatedIdentifier,\n encodeIdentifier,\n type IdentifierColumn,\n isCompact,\n transportedIdentifier,\n} from \"./identifier\";\nimport type { ModelSql } from \"./insert-value\";\nimport { unreachable } from \"./invariant\";\nimport {\n AGGREGATES,\n type Aggregate,\n admittedTemporal,\n aggregateRow,\n approximateOrder,\n BOOLEAN_LEAF,\n type BoundOperand,\n type BoundOperation,\n balancedOr,\n type CarriedRow,\n type Closure,\n COUNT_LEAF,\n CURSOR_ORDER_REFUSAL,\n callerText,\n conjunction,\n distanceUpperBound,\n type Enclosing,\n type FlagChoice,\n type FlagMember,\n type FlagPlan,\n firstRow,\n isAggregate,\n isParameterOperand,\n type KnownRow,\n type Leaf,\n type LoweringFrame,\n memberRead,\n NO_GATES,\n type OperationPredicate,\n type OrderJoins,\n type OrderTerm,\n type PlacedBody,\n type PreparedDomain,\n type PreparedOperand,\n type PreparedPredicate,\n type PreparedProjection,\n type PreparedProjectionField,\n type PreparedRelationProjection,\n type PreparedScalar,\n type PreparedSelector,\n type PreparedTarget,\n type PreparedUpdate,\n type Quantified,\n Queries,\n type Query,\n RECURSIVE_CARRIER,\n type Read,\n ROOT_CANDIDATES,\n readsRelation,\n readUpdate,\n relations,\n reversedRows,\n rowIdentity,\n rowSet,\n rowValue,\n type ScalarStateOf,\n type SelectControls,\n type Shape,\n type SharedBodies,\n type SharedBody,\n type SplitSumSql,\n sharedKey,\n states,\n type TestedColumns,\n throughDerived,\n} from \"./query\";\nimport { type CallScope, Parameter, type RowPurpose } from \"./row-scope\";\nimport { RawRows, RowsOf } from \"./rows-of\";\nimport {\n type Arguments,\n entries,\n type Input,\n type ReadOperation,\n} from \"./schema\";\nimport { hopFieldsOf, linkMembers, type Membership } from \"./storage\";\nimport { engineFault, listed, nameOf, tableOf, unsupported } from \"./terms\";\n\n/** A select's controls, and a condition spelled for the alias this language gives it. */\nexport interface SqlSelectControls extends SelectControls {\n /** More of the root row's filter (a function: of its alias). */\n condition?: Sql | ((alias: string) => Sql);\n /** The first order term is a distance an index may serve: {@link approximateOrder}. */\n approximate?: boolean;\n}\n\n/** The adapter's arithmetic for each update operator that names one; a division is chosen by the column. */\nconst ARITHMETIC: Partial<Record<string, \"add\" | \"subtract\" | \"multiply\">> = {\n increment: \"add\",\n decrement: \"subtract\",\n multiply: \"multiply\",\n};\n\n/** The body each slot of a statement was settled from. */\nconst bySlot = (bodies: readonly SharedBody[]): Map<Sql, SharedBody> => {\n const of = new Map<Sql, SharedBody>();\n for (const body of bodies)\n for (const placed of body.slots) of.set(placed.slot, body);\n return of;\n};\n\nexport class SqlQueries extends Queries {\n declare readonly adapter: DatabaseAdapter;\n // What the statements say most: the adapter's own, held from the start.\n get #a(): DatabaseAdapter {\n return this.adapter;\n }\n readonly #and = this.#a.operators.and;\n readonly #eq = this.#a.operators.eq;\n readonly #at = this.#a.identifiers.column;\n readonly #named = this.#a.identifiers.aliased;\n readonly #escaped = this.#a.identifiers.escape;\n readonly #cast = this.#a.expressions.cast;\n readonly #inner = this.#a.joins.inner;\n readonly #true = this.#a.literals.true;\n readonly #false = this.#a.literals.false;\n readonly #null = this.#a.literals.null;\n readonly #literal = this.#a.literals.value;\n readonly #document = this.#a.json.document;\n readonly #object = this.#a.json.object;\n /** A query read aside, under an alias. */\n readonly #aside = this.#a.subqueries.correlate;\n readonly #or = this.#a.operators.or;\n readonly #isNull = this.#a.operators.isNull;\n readonly #isNotNull = this.#a.operators.isNotNull;\n\n /**\n * A raw `Sql` operand is PARENTHESIZED. A caller's fragment is an\n * expression, not a token: `views: { gte: ctx => ctx.sql\\`SELECT MAX(...)\\` }`\n * composed as `\"views\" >= SELECT MAX(…)` is a syntax error on every dialect,\n * and a fragment with its own operator would re-associate. The shipped\n * engine wrapped at this same seam (`where-builder.ts:472`, applied `:492`).\n */\n value(value: unknown): Sql {\n return value instanceof Sql\n ? callerText(this.settleRows(value))\n : this.#literal(value);\n }\n\n #nextAlias = 0;\n /**\n * The statement's aliases that read a stored row of a model's table as it\n * stands ({@link table}), by model: a derived row (a produced row, a masked\n * or paged window, a locked source) is never one.\n */\n readonly #rows = new Map<string, AnyModel>();\n /**\n * The produced row a judgement is lowering over ({@link holds}): the alias\n * it is read under, per field whether the value the write sets is null,\n * where the write states it, and what folds that into a predicate over it.\n */\n declare known: KnownRow | undefined;\n /**\n * The statement part lowering here reads a masked window (K5): its read-\n * gated columns are already NULL where their rows do not carry them.\n */\n #masked = false;\n /**\n * The relation filter bodies of the statement lowering here, where the\n * adapter shares them ({@link sharingBodies}).\n */\n #shared: SharedBodies | undefined;\n /**\n * The read lowering here is bounded: a unique, first or existence read, or\n * a `take` (`capabilities.joinsJunctionFilters`). Each read sets it; a\n * write's owner never reads, so its statements are never bounded.\n */\n #bounded = false;\n /**\n * `build`'s statement, where the adapter shares relation bodies\n * (`capabilities.sharesRelationBodies`): each body the statement lowers\n * more than once is stated once, in a `WITH` before it, as the key set\n * every arm repeating it tests ({@link relationExists}); a body lowered once\n * keeps its place, so a statement that repeats none is unchanged. One scope\n * per statement: a statement lowered inside another's joins it.\n *\n * A recursive filter's walk stays in place, and each key set is tested\n * where it is read, until the statement references more relations than\n * the adapter's `relationsPerStatement` ({@link relations}): then walks it\n * repeats become reaching sets ({@link sharedWalk}), those saving the most\n * relations first, until it fits, and if still over, rows join the key\n * sets they test ({@link flagging}), the largest saving first. Each costs\n * plans: a reaching set is computed for every row of its table (a check of\n * one row reads them all), and a joined flag member is read again per row\n * of a correlated subquery, where the test it replaces was hashed once\n * (PostgreSQL holds a one-column set as an array instead, computed once).\n * The bound is the driver's to state (Neki: 256); absent, nothing changes.\n */\n #sharingBodies(build: () => Sql): Sql {\n if (this.#shared !== undefined) return build();\n const shared: SharedBodies = {\n byKey: new Map(),\n order: [],\n attach: new Map(),\n };\n this.#shared = shared;\n let statement: Sql;\n try {\n statement = build();\n } finally {\n this.#shared = undefined;\n }\n const repeated: SharedBody[] = [];\n for (const body of shared.order)\n if (body.slots.length > 1) repeated.push(body);\n else body.slots[0]!.slot.settle(body.slots[0]!.inline);\n const walks = repeated.filter((body) => body.recursive === true);\n const budget = this.adapter.capabilities.relationsPerStatement;\n const settle = (\n reaching: ReadonlySet<SharedBody>,\n flagged: FlagChoice = () => [],\n materialized?: Set<SharedBody>,\n whole?: boolean\n ) =>\n this.#settled(\n statement,\n shared,\n repeated,\n reaching,\n flagged,\n materialized,\n whole\n );\n const materialized = new Set<SharedBody>();\n let query = settle(new Set(), undefined, materialized);\n // A walk its author states selective (the teams a member belongs to,\n // through their subteams), read only inside bodies computed over their\n // whole tables, walks once per row of each in place: it is computed\n // once as a set instead, from the few rows it reaches back from. Read in\n // a body kept inlined (a body reading no other, or one read at a single\n // place, which PostgreSQL inlines), it stays: lifted, it would make that\n // body read a set, so computed over its whole table, and a keyed read\n // would lose its index (SQLite and D1 materialize it), or it would find\n // its seeds over their whole table where one row's walk reads a few.\n // Lifting one changes no body's form, so it needs no bound: a statement\n // past one starts from it.\n const lifted = new Set(\n walks.filter(\n (walk) =>\n walk.selective === true &&\n walk.slots.every(\n ({ within }) =>\n within?.body !== undefined && materialized.has(within.body)\n )\n )\n );\n if (lifted.size > 0) query = settle(lifted);\n if (budget === undefined) return query;\n let count = relations(query);\n if (count <= budget) return query;\n // Walks first, those saving the most relations, until the estimate fits;\n // then key sets joined, the largest saving first, until it does.\n const reaching = new Set<SharedBody>(lifted);\n for (const { body, saves } of this.#rankedWalks(query, walks)) {\n if (count <= budget) break;\n reaching.add(body);\n count -= saves;\n }\n query = settle(reaching);\n count = relations(query);\n if (count <= budget) return query;\n const largest: FlagChoice = (plans) =>\n [...plans]\n .sort((left, right) => right.saves - left.saves)\n .filter((plan) => {\n if (count <= budget) return false;\n count -= plan.saves;\n return true;\n });\n query = settle(reaching, largest);\n if (relations(query) <= budget) return query;\n // An estimate counts each walk or member where the others are not: one\n // nested in another saves less. Short, the most compact form.\n query = settle(new Set(walks), (plans) => plans);\n // Still over: one row, computed once, holds what the whole root read\n // tests, and `$exists` answers join it too (Neki only refuses here).\n return relations(query) <= budget || !this.adapter.arrays.ofRows\n ? query\n : settle(new Set(walks), (plans) => plans, undefined, true);\n }\n /**\n * `statement` with each repeated body stated once but walks outside\n * `reaching`, which stay in place, and the flag members `flagged` picks\n * ({@link flagging}) joined; `materialized` collects the relation bodies\n * it states computed over their whole tables: each reads another stated\n * body, so is not inlined, and is read at more than one place.\n */\n #settled(\n statement: Sql,\n shared: SharedBodies,\n repeated: readonly SharedBody[],\n reaching: ReadonlySet<SharedBody>,\n flagged: FlagChoice,\n materialized?: Set<SharedBody>,\n whole?: boolean\n ): Sql {\n const stated: SharedBody[] = [];\n for (const body of repeated)\n if (body.recursive !== true || reaching.has(body)) {\n stated.push(body);\n for (const placed of body.slots) placed.slot.settle(placed.use);\n } else for (const placed of body.slots) placed.slot.settle(placed.inline);\n for (const slots of shared.attach.values())\n for (const slot of slots) slot.settle(sql.empty);\n // A relation body is inlined where it reads no other shared body: a\n // nested one, inlined into every use of every body that reads it,\n // multiplies the plan (one row domain over 40 models: 9.8 s materialized,\n // 113 s inlined, 11 s inlining the leaves only).\n // By the slots a stated body settled to, not by text: a table may be\n // named like a body. The same pass finds the aliases each body joins\n // flags after ({@link flagging}).\n const uses = bySlot(stated);\n // How many places the statement reads each stated body at.\n const readers = new Map<SharedBody, number>();\n const attached = new Map<Sql, string>();\n for (const [alias, slots] of shared.attach)\n for (const slot of slots) attached.set(slot, alias);\n const reads = new Set<SharedBody>();\n // The aliases the statement states (a body lowered more than once states\n // its first text only), by the first stated body holding each.\n const within = new Map<string, number>();\n const scan = (query: Sql, index: number, body?: SharedBody) => {\n Sql.peekRuns(query, (node) => {\n const used = uses.get(node);\n if (used !== undefined) {\n readers.set(used, (readers.get(used) ?? 0) + 1);\n if (body !== undefined) reads.add(body);\n }\n const alias = attached.get(node);\n if (alias !== undefined && !within.has(alias)) within.set(alias, index);\n return false;\n });\n };\n for (const [index, body] of stated.entries()) scan(body.query, index, body);\n scan(statement, stated.length);\n const flags = this.#flagging(\n shared,\n stated,\n within,\n flagged,\n whole ? readers : undefined\n );\n for (const body of stated)\n for (const placed of body.slots)\n placed.slot.settle(flags.atoms.get(placed) ?? placed.use);\n // Not inlined and read at two places or more: PostgreSQL materializes\n // such a member (it inlines one read once), SQLite is told to.\n if (materialized !== undefined)\n for (const body of reads)\n if (body.correlated && (readers.get(body) ?? 0) > 1)\n materialized.add(body);\n const definitions = stated.flatMap((body) => [\n ...(flags.held.has(body)\n ? []\n : body.recursive\n ? [{ name: body.name, query: body.query, recursive: true }]\n : [\n {\n name: body.name,\n query: body.query,\n inlined: body.correlated && !reads.has(body),\n },\n ]),\n ...(flags.after.get(body) ?? []),\n ]);\n return definitions.length === 0\n ? statement\n : sql`${this.adapter.cte.with(definitions)} ${statement}`;\n }\n /**\n * `walks`, placed in `query`, by how many relations stating each as a\n * reaching set saves where the others stay: the relations of each place\n * `query` reads it, less its set's and one per place. A walk `query` does\n * not read (lowered in a body stated elsewhere) saves nothing.\n */\n #rankedWalks(\n query: Sql,\n walks: readonly SharedBody[]\n ): { readonly body: SharedBody; readonly saves: number }[] {\n const of = bySlot(walks);\n const read = new Map<SharedBody, Sql[]>();\n relations(query, (fragment) => {\n const body = of.get(fragment);\n if (body === undefined) return;\n const places = read.get(body);\n if (places === undefined) read.set(body, [fragment]);\n else places.push(fragment);\n });\n return [...read]\n .map(([body, places]) => ({\n body,\n saves:\n places.reduce((sum, place) => sum + relations(place), 0) -\n relations(body.query) -\n places.length,\n }))\n .sort((left, right) => right.saves - left.saves);\n }\n /**\n * Where aliases test repeated bodies' key sets on the same columns more\n * often than joining them costs, and their `FROM` items can join them\n * ({@link attached}), each joins them ONCE: one `WITH` member holds each\n * key any set of a group holds, with one flag per set, `LEFT JOIN`ed after\n * the item on those columns, and each test reads its set's flag, `IS NOT\n * NULL` for an `EXISTS`, `IS NULL` for a `NOT EXISTS`: two-valued as they\n * are, a NULL key holding no flag. PlanetScale's Neki bounds one statement\n * to 256 relations and counts each test's `FROM` item; a member costs one\n * per set it reads (and its union one more), and each alias joining it\n * one. Aliases testing overlapping groups share one member of all their\n * sets where that costs less and every body joining it (`within`, the\n * first repeated body whose text holds the alias) follows its last set;\n * else each distinct group has its own, which always does: each set an\n * alias tests is lowered inside that alias's body. A member is stated\n * after the last set it reads. Where the dialect holds a value list\n * (`arrays.ofRows`, PostgreSQL), a group of one-column keys is instead one\n * row of arrays, one per set (each one relation, no union), `CROSS JOIN`ed,\n * each test `COALESCE(key = ANY(array), FALSE)` or its negation: a joined\n * flag member is read again for each row of a correlated subquery (a\n * nested include's 10x page read: 1.3 s in place, 5.1 s with flags, 1.4 s\n * with arrays), an array once per statement.\n */\n #flagging(\n shared: SharedBodies,\n repeated: readonly SharedBody[],\n within: ReadonlyMap<string, number>,\n flagged: FlagChoice,\n whole?: ReadonlyMap<SharedBody, number>\n ): {\n readonly atoms: Map<PlacedBody, Sql>;\n readonly after: Map<SharedBody, FlagMember[]>;\n readonly held: ReadonlySet<SharedBody>;\n } {\n const a = this.adapter;\n const atoms = new Map<PlacedBody, Sql>();\n const after = new Map<SharedBody, FlagMember[]>();\n const inRow = new Set<SharedBody>();\n const order = new Map(repeated.map((body, index) => [body, index]));\n const tested = new Map<string, TestedColumns>();\n // What `whole` joins once: each place of the root read, whatever it tests\n // of one column or none, reads the root's row.\n const { root } = shared;\n const rooted = new Set<Sql>();\n if (whole && root && within.has(root.alias))\n Sql.peekRuns(root.scope, (node) => {\n rooted.add(node);\n return false;\n });\n for (const body of repeated)\n for (const placed of body.slots) {\n const { test } = placed;\n const width = test.columns.length;\n const held = width < 2 && rooted.has(placed.slot);\n if (!(held || within.has(test.alias)) || (width === 0 && !whole))\n continue;\n const key = held ? \"\\0\" : `${test.alias}\\0${test.columns.join(\"\\0\")}`;\n let group = tested.get(key);\n if (group === undefined) {\n group = {\n test: held ? { ...test, alias: root!.alias, columns: [] } : test,\n bodies: [],\n placed: [],\n };\n tested.set(key, group);\n }\n group.placed.push([body, placed]);\n if (!group.bodies.includes(body)) group.bodies.push(body);\n }\n const byOrder = (left: SharedBody, right: SharedBody) =>\n order.get(left)! - order.get(right)!;\n // A one-column key set is held as an array where the dialect has one\n // (`arrays.ofRows`): one read per set, no union.\n const arrays = (width: number) =>\n width < 2 && a.arrays.ofRows !== undefined;\n const member = (sets: number, width: number) =>\n sets === 1 || arrays(width) ? sets : sets + 1;\n const tests = (groups: readonly TestedColumns[]) =>\n groups.reduce((sum, group) => sum + group.placed.length, 0);\n // Each distinct group's own member, where it costs less than its tests.\n const own = (groups: readonly TestedColumns[]) => {\n const combinations = new Map<string, TestedColumns[]>();\n for (const group of groups) {\n const combination = [...group.bodies]\n .sort(byOrder)\n .map((body) => body.name)\n .join(\",\");\n const same = combinations.get(combination);\n if (same === undefined) combinations.set(combination, [group]);\n else same.push(group);\n }\n return [...combinations.values()].map((same) => {\n const sets = [...same[0]!.bodies].sort(byOrder);\n return {\n sets,\n groups: same,\n saves:\n tests(same) -\n member(sets.length, same[0]!.test.columns.length) -\n same.length,\n };\n });\n };\n // Groups of one key width that share a set, joined transitively: a\n // group testing once gains nothing by a join.\n const components: TestedColumns[][] = [];\n for (const group of tested.values()) {\n if (group.placed.length < 2) continue;\n const joined = components.filter((component) =>\n component.some(\n (other) =>\n Math.max(other.test.columns.length, 1) ===\n Math.max(group.test.columns.length, 1) &&\n other.bodies.some((body) => group.bodies.includes(body))\n )\n );\n const merged = [group, ...joined.flat()];\n for (const component of joined)\n components.splice(components.indexOf(component), 1);\n components.push(merged);\n }\n const plans: FlagPlan[] = components.flatMap((component) => {\n const separate = own(component).filter((plan) => plan.saves > 0);\n const sets = [\n ...new Set(component.flatMap((group) => group.bodies)),\n ].sort(byOrder);\n const last = order.get(sets.at(-1)!)!;\n const together = {\n sets,\n groups: component,\n saves:\n tests(component) -\n member(sets.length, component[0]!.test.columns.length) -\n component.length,\n };\n const ordered = component.every(\n (group) => within.get(group.test.alias)! > last\n );\n return ordered &&\n together.saves > separate.reduce((sum, plan) => sum + plan.saves, 0)\n ? [together]\n : separate;\n });\n const joins = new Map<string, Sql[]>();\n let named = shared.order.length;\n const chosen = new Set(flagged(plans));\n for (const { sets, groups } of plans.filter((plan) => chosen.has(plan))) {\n const keys = groups[0]!.test.columns.map((_, index) => `k${index}`);\n const name = `__shared_${named++}`;\n const last = sets.at(-1)!;\n const held = arrays(keys.length);\n // A set only this row reads is written in it, with no member to read.\n const own = new Set(\n whole && held\n ? sets.filter(\n (body) =>\n !body.recursive &&\n groups\n .flatMap((group) => group.placed)\n .filter(([placedBody]) => placedBody === body).length ===\n whole.get(body)\n )\n : []\n );\n for (const body of own) inRow.add(body);\n after.set(last, [\n ...(after.get(last) ?? []),\n {\n name,\n query: held ? this.#keyArrays(sets, own) : this.#flagSet(sets, keys),\n inlined: false,\n },\n ]);\n for (const { test, placed } of groups) {\n const flag = this.alias();\n const member = this.#named(this.#escaped(name), flag);\n const joined = joins.get(test.alias) ?? [];\n joined.push(\n held\n ? a.joins.cross(member)\n : a.joins.left(\n member,\n this.#and(\n ...test.columns.map((column, index) =>\n this.#eq(\n this.#at(flag, keys[index]!),\n this.#at(test.alias, column)\n )\n )\n )\n )\n );\n joins.set(test.alias, joined);\n for (const [body, slot] of placed) {\n const index = sets.indexOf(body);\n if (held) {\n const column = this.#at(flag, `f${index}`);\n // Two-valued as the EXISTS it replaces: a NULL key, or a key an\n // array holding a NULL does not hold, is not held.\n const holds =\n slot.test.columns.length === 0\n ? column\n : a.expressions.coalesce(\n a.arrays.has(\n column,\n this.#at(slot.test.alias, slot.test.columns[0]!)\n ),\n this.#false()\n );\n atoms.set(slot, slot.test.holds ? holds : a.operators.not(holds));\n continue;\n }\n const flagged = this.#at(\n flag,\n sets.length === 1 ? keys[0]! : `f${index}`\n );\n atoms.set(\n slot,\n slot.test.holds ? this.#isNotNull(flagged) : this.#isNull(flagged)\n );\n }\n }\n }\n for (const [alias, slots] of shared.attach) {\n const joined = joins.get(alias);\n if (joined === undefined) continue;\n for (const slot of slots) slot.settle(sql` ${sql.join(joined, \" \")}`);\n }\n return { atoms, after, held: inRow };\n }\n /**\n * One row holding each of `bodies`' one-column key sets as an array, `f<n>`\n * for the n-th ({@link DatabaseAdapter.arrays.ofRows}), and an `$exists`\n * body's answer as itself: computed once per statement, each row joining it\n * tests membership without reading a set again.\n */\n #keyArrays(bodies: readonly SharedBody[], own: ReadonlySet<SharedBody>): Sql {\n const a = this.adapter;\n return a.clauses.select(\n listed(\n bodies.map((body, index) =>\n this.#named(\n body.slots[0]!.test.columns.length === 0\n ? own.has(body)\n ? a.filters.some(body.query)\n : body.slots[0]!.use\n : a.arrays.ofRows!(\n own.has(body)\n ? body.query\n : assembleAdapterSelect(a, {\n columns: this.#at(body.name, \"k0\"),\n from: memberRead(a, body.name),\n })\n ),\n `f${index}`\n )\n )\n )\n );\n }\n /**\n * The keys `bodies`' sets hold, once each: with one set, its keys; with\n * more, each key and per set `f<n>`, 1 where that set holds the key and\n * NULL where it does not.\n */\n #flagSet(bodies: readonly SharedBody[], keys: readonly string[]): Sql {\n const a = this.adapter;\n if (bodies.length === 1) {\n const columns = keys.map((key) => this.#at(bodies[0]!.name, key));\n return assembleAdapterSelect(a, {\n columns: listed(columns),\n from: memberRead(a, bodies[0]!.name),\n groupBy: listed(columns),\n });\n }\n const flags = bodies.map((_, index) => `f${index}`);\n // Typed: PostgreSQL types a bare NULL arm by arm, as text.\n const absent = this.#cast(this.#null(), \"integer\");\n const arms = bodies.map((body, member) =>\n assembleAdapterSelect(a, {\n columns: listed([\n ...keys.map((key) => this.#named(this.#at(body.name, key), key)),\n ...flags.map((flag, index) =>\n this.#named(index === member ? sql`1` : absent, flag)\n ),\n ]),\n from: memberRead(a, body.name),\n })\n );\n // A transport bounding a compound's terms (D1: 5) reads a longer union\n // through derived tables of at most that many.\n const bound = a.capabilities.compoundSelectTerms ?? arms.length;\n const union = (terms: readonly Sql[]): Sql =>\n terms.length <= bound\n ? a.setOperations.unionAll(...terms)\n : union(\n Array.from({ length: Math.ceil(terms.length / bound) }, (_, at) =>\n terms.slice(at * bound, (at + 1) * bound)\n ).map((chunk) =>\n chunk.length === 1\n ? chunk[0]!\n : throughDerived(\n a,\n a.setOperations.unionAll(...chunk),\n this.alias()\n )\n )\n );\n const held = this.alias();\n const columns = keys.map((key) => this.#at(held, key));\n return assembleAdapterSelect(a, {\n columns: listed([\n ...columns,\n ...flags.map((flag) =>\n this.#named(a.aggregates.max(this.#at(held, flag)), flag)\n ),\n ]),\n from: this.#aside(union(arms), held),\n groupBy: listed(columns),\n });\n }\n /**\n * A write's statement, sharing its bodies where the adapter does: every\n * repeated body its WHERE (and its produced row's judgement) lowers is one\n * `WITH` member ahead of the `UPDATE` or `DELETE`, as a read's is.\n */\n sharing(build: () => Sql): Sql;\n sharing(build: () => Sql | undefined): Sql | undefined;\n sharing(build: () => Sql | undefined): Sql | undefined {\n return this.#shares(\n build,\n (statement) => statement,\n (_, statement) => statement\n );\n }\n /**\n * What `build` makes, the statement `of` it sharing its bodies where the\n * adapter does and put back by `into`; as made where it holds none.\n */\n #shares<T>(\n build: () => T,\n of: (made: T) => Sql | undefined,\n into: (made: T, statement: Sql) => T\n ): T {\n if (!this.sharesBodies) return build();\n let made!: T;\n const statement = this.#sharingBodies(() => {\n made = build();\n return of(made) ?? sql.empty;\n });\n return of(made) === undefined ? made : into(made, statement);\n }\n /** `args`, ordered by {@link defaultOrder} when it states no order. */\n #ordered(model: AnyModel, args: Arguments): Arguments {\n if (args.orderBy !== undefined) return args;\n const orderBy = this.defaultOrder(model);\n return orderBy === undefined ? args : { ...args, orderBy };\n }\n /** This view's `Queries` reading under `domain`, for `call`'s values. */\n override under(domain: PreparedDomain, call?: CallScope): Queries {\n return new SqlQueries(this.schema, this.adapter, this.result, domain, call);\n }\n /**\n * The rows a set computed over `model`'s whole table may hold while a\n * layer's predicates lower here: what its own `where` of related rows\n * states ({@link PreparedDomain.bound}), at `alias`. Rows reached through\n * a relation from a row it admits need none: they are such rows already.\n */\n #setBound(model: AnyModel, alias: string): readonly Sql[] {\n const bound = this.#boundOf(model);\n const lowered = bound && this.lowerSelector(bound, alias);\n return lowered ? [lowered] : [];\n }\n /**\n * What a declared junction's link rows may hold while a layer's predicates\n * lower here, where a positive test reads them ({@link setBound}), so a walk\n * reads its bound's links rather than filtering the whole table's. Only a\n * bound over columns both of a link's keys hold: their foreign keys make them\n * the joined rows' own, so it changes no answer. Over any other column a link\n * may disagree with the rows it joins, and a bound would drop it. A generated\n * junction has no field to bound.\n */\n #linkBound(\n edge: Extract<Membership, { kind: \"junction\" }>,\n link: string\n ): readonly Sql[] {\n const model = edge.declared?.model;\n const bound = model && this.#boundOf(model);\n if (!bound) return [];\n const holds = (side: typeof edge.sourceSide, field: string) =>\n side.members.some((pair) => pair.junctionField === field);\n for (const field of bound.facts.fields)\n if (!(holds(edge.sourceSide, field) && holds(edge.targetSide, field)))\n return [];\n return this.#setBound(model, link);\n }\n /** {@link setBound}'s selector, where one applies here. */\n #boundOf(model: AnyModel): PreparedSelector | undefined {\n const excluded = this.excluded;\n return excluded === undefined ||\n excluded.length === 0 ||\n this.#negative ||\n this.unbounded > 0\n ? undefined\n : this.domain?.bound(model, excluded);\n }\n /**\n * How many read gates are lowering here: none of their sets is bounded,\n * since what masks a value tests nothing.\n */\n unbounded = 0;\n /** The relation bodies lowering here, innermost last ({@link Enclosing}). */\n readonly #enclosing: Enclosing[] = [];\n /** `lower`, read inside `enclosing`'s body ({@link Enclosing}). */\n #inside<T>(enclosing: Enclosing, lower: () => T): T {\n this.#enclosing.push(enclosing);\n try {\n return lower();\n } finally {\n this.#enclosing.pop();\n }\n }\n /**\n * Whether what lowers here stands negated (under a `NOT`, a `none`, an\n * `isNot`, an `unless`): a set bounded there would hold fewer rows, and\n * its negation more, so none is ({@link setBound}).\n */\n #negative = false;\n /** `lower` with the polarity of what it lowers turned over. */\n #opposite<T>(lower: () => T): T {\n this.#negative = !this.#negative;\n try {\n return lower();\n } finally {\n this.#negative = !this.#negative;\n }\n }\n /** Whether a layer's predicates are lowering here. */\n get #lowersLayer(): boolean {\n return (this.excluded?.length ?? 0) > 0;\n }\n alias(): string {\n return `q${this.#nextAlias++}`;\n }\n /**\n * The FIRST alias of one statement, which opens that statement's alias scope.\n *\n * An alias is a fact of the statement it names, not of this owner's history,\n * so a statement whose first alias is minted by one of the owners named\n * below starts at `q0`, and the same logical query always emits the same\n * text. Without it the engine-lifetime read owner\n * (`commands/index.ts`) minted `q0, q1, … q10000` for the SAME\n * `findUnique`, so its statement text was unique per call — measured as an\n * obstacle by the cutover protocol (`g4/cutover/protocol.md` §7.2) and a\n * guaranteed miss for any transport that keeps statements by their text\n * (PostgreSQL named statements, `mysql2`'s prepared ones, D1/PlanetScale).\n *\n * The statement owners are {@link select}, {@link aggregated},\n * {@link grouped}, {@link selectSeries} and {@link junction} — every method\n * here that assembles a complete statement —\n * and each calls this before any other alias of that statement. Nothing else\n * may: a `lower…` fragment continues the statement it is part of, because a\n * mutation statement is assembled from several of them by the physical owner\n * (`OperationContext`'s `lowerMutationLimit` + `lowerProjection` pair) and\n * two fragments of ONE statement must not both start at `q0`. For the same\n * reason no statement owner may be entered while another statement is being\n * built: a nested complete statement is a subquery of its parent and shares\n * the parent's scope, which is why the nested relation projection, the\n * correlated count and the cursor window mint plain {@link alias}es.\n */\n rootAlias(): string {\n this.#nextAlias = 0;\n this.#rows.clear();\n return this.alias();\n }\n /**\n * `model`'s table read as `alias`, followed, inside a statement sharing its\n * bodies, by the slot where `alias` joins the key sets it is tested\n * against ({@link sharingBodies}). Only where nothing after the item but\n * other joins and the clauses of its own query read `alias`.\n */\n #attached(model: AnyModel, alias: string): Sql {\n return sql`${this.table(model, alias)}${this.#attachPoint(alias)}`;\n }\n /** The slot after `alias`'s `FROM` item ({@link attached}). */\n #attachPoint(alias: string): Sql {\n const shared = this.#shared;\n if (shared === undefined) return sql.empty;\n const slot = new SqlSlot(sql.empty);\n const slots = shared.attach.get(alias);\n if (slots === undefined) shared.attach.set(alias, [slot]);\n else slots.push(slot);\n return slot;\n }\n /** A fresh alias for a stored row of `model`, known before its `FROM` is. */\n #rowAlias(model: AnyModel): string {\n const alias = this.alias();\n this.#rows.set(alias, model);\n return alias;\n }\n table(model: AnyModel, alias?: string): Sql {\n if (alias !== undefined) this.#rows.set(alias, model);\n return this.#tableNamed(tableOf(model), alias);\n }\n /** Every persistent table this lowering names: pinned under {@link rowsOf}. */\n #tableNamed(name: string, alias?: string): Sql {\n return (this.#pinned ?? this.adapter.identifiers.table)(name, alias);\n }\n #pinned: ((name: string, alias?: string) => Sql) | undefined;\n column(model: AnyModel, field: string, alias?: string): Sql {\n const name = this.columnName(model, field);\n return alias ? this.#at(alias, name) : this.#escaped(name);\n }\n spelling(model: AnyModel, dialect: Dialect): ModelSql {\n return {\n dialect,\n table: (alias) => this.table(model, alias),\n column: (field, alias) => this.column(model, field, alias),\n value: (field, value) => this.fieldValue(model, field, value),\n name: (...path) =>\n sql.join(\n path.map((part) => this.adapter.identifiers.escape(part)),\n \".\"\n ),\n visible: (alias, options) =>\n new RowsOf(\n model,\n alias,\n options?.update && { kind: \"update\", writes: options.update },\n options?.where\n ),\n };\n }\n /**\n * A caller's fragment with every {@link RowsOf} in it settled to this\n * call's root domain at its alias (under its judgement, and its `where`,\n * where it states them): a read an extension writes takes the rows the\n * call may see, or write, as every read here does.\n */\n settleRows(fragment: Sql): Sql {\n Sql.each(fragment, (node) => {\n if (!(node instanceof RowsOf)) return;\n const { model } = node;\n // Settled here, it would take this call's domain, not its own client's.\n if (node instanceof RawRows)\n unsupported(`${nameOf(model)}.$rows() is for a tagged $queryRaw only`);\n const domain = this.domainOf(model, \"root\", node.judgement);\n // A `where` the extension passes on is admitted as a `findMany`'s.\n const named =\n node.where === undefined\n ? domain\n : this.andSelectors(model, [\n ...(domain ? [domain] : []),\n this.prepareSelector(\n model,\n this.schema.admit(model, \"findMany\", { where: node.where })\n .where\n ),\n ]);\n node.settle(\n (named && this.lowerSelector(named, node.alias)) ?? sql.raw(\"1 = 1\")\n );\n });\n return fragment;\n }\n /**\n * The rows of `model` this view's call may read, as a `FROM` item named\n * `alias` (`$rows`): the domain a root `findMany` takes, in a derived\n * table, so the text around it cannot place it under an `OR` or an outer\n * join's `ON`. Inside, its own statement scope reads the row under a minted\n * alias, so no name the caller chooses meets one the lowering writes.\n */\n rowsOf(model: AnyModel, alias: string): Sql {\n const row = this.rootAlias();\n const domain = this.domainOf(model, \"root\");\n // Every table pinned: the caller's text around it may define a CTE named\n // like a table the domain reads, which would otherwise stand for it.\n this.#pinned = adapterPinnedTable(this.adapter);\n try {\n return this.adapter.subqueries.rows(\n this.table(model, row),\n row,\n domain && this.lowerSelector(domain, row),\n alias,\n !model[\"~\"].withoutRowid\n );\n } finally {\n this.#pinned = undefined;\n }\n }\n /**\n * The one destination-aware operand owner: filters, cursors, order operands,\n * assignments and reference values all bind a value through this function,\n * so a column is never written in one vocabulary and read in another.\n */\n fieldValue(model: AnyModel, field: string, value: unknown): Sql {\n return this.#scalarValue(\n this.physical(model, field).scalar,\n value,\n field,\n this.scalarShape(model, field).id\n );\n }\n /**\n * `id` is the destination column's identifier storage, which the scalar\n * alone cannot answer: a foreign key DERIVES its domain and a private\n * carrier column names the key it stands in for. Only a COLUMN operand\n * carries native storage; min/max operands additionally pass through the\n * same transport expression their aggregate reads.\n */\n #scalarValue(\n scalar: Scalar,\n value: unknown,\n field: string,\n id?: IdentifierColumn\n ): Sql {\n const a = this.adapter;\n const state = scalar[\"~\"].state;\n if (value instanceof Sql) {\n const fragment = callerText(this.settleRows(value));\n return state.type === \"decimal\" && state.array !== true\n ? a.expressions.decimalCast(fragment, state.decimal)\n : fragment;\n }\n const sentinel = jsonNullKindOf(value);\n if (sentinel)\n return sentinel === \"DbNull\" ? this.#null() : a.json.value(null);\n if (value === null || value === undefined) return this.#null();\n if (state.array === true && Array.isArray(value))\n return this.#listValue(state, value, field);\n // A COMPACT identifier binds its physical form — the payload's bytes, or\n // a PostgreSQL `uuid`'s canonical text — through the adapter's one\n // identifier literal. A text-stored domain holds the public string itself\n // and takes the ordinary arm below, byte for byte what it took before.\n if (isCompact(id))\n return a.literals.id(encodeIdentifier(id, value), id.representation);\n switch (state.type) {\n case \"bigint\":\n return this.#literal(state.array === true ? String(value) : value);\n case \"decimal\":\n case \"json\":\n case \"point\":\n case \"vector\":\n case \"datetime\":\n case \"date\":\n case \"time\":\n return this.#typedScalarValue(scalar, value, field);\n default:\n return this.#literal(value);\n }\n }\n /** The scalars whose operand spelling depends on their type, out of line. */\n #typedScalarValue(scalar: Scalar, value: unknown, field: string): Sql {\n const a = this.adapter;\n const state = scalar[\"~\"].state;\n // A single value bound against a LIST field is one MEMBER of that field's\n // container (`has` is the operator that asks for one), and a container\n // carries what it was WRITTEN with — the same fact {@link nativeType}\n // already states for the decode leaf, which refuses to hand a list's\n // native type to a literal. The two scalars whose column spelling is\n // PHYSICAL have to consume it: a decimal's exact `DECIMAL(p,s)` operand\n // cast, and a datetime's dialect rendering of the instant (MySQL's naive\n // `DATETIME`, which a JSON container has no column to hold). Every other\n // scalar crosses a container exactly as it crosses its column.\n const member = state.array === true;\n switch (state.type) {\n case \"decimal\":\n return member\n ? this.#literal(\n decimalMembers(state, [value], field, this.adapter.result)[0]!\n )\n : a.literals.decimal(\n canonicalDecimal(value, field),\n requireDecimal(state, field)\n );\n case \"json\":\n return a.literals.json(value);\n case \"point\":\n return this.#geoPoint(\"value\").value(\n this.value((value as GeoPoint).longitude),\n this.value((value as GeoPoint).latitude)\n );\n case \"vector\":\n // Providers without a native vector tier store the admitted JSON array.\n return a.capabilities.supportsVector\n ? a.vector.literal(value as number[])\n : a.literals.json(value);\n case \"datetime\": {\n const wire = admittedTemporal(value, validateIsoTimestamp);\n return typeof wire === \"string\"\n ? a.literals.dateTime(\n wire,\n member ? undefined : this.nativeType(scalar),\n member\n )\n : this.#literal(wire);\n }\n case \"time\": {\n const admitted = validateIsoTime(value);\n return this.#literal(\"value\" in admitted ? admitted.value : value);\n }\n case \"date\": {\n const wire = admittedTemporal(value, validateIsoDate);\n return typeof wire === \"string\"\n ? a.literals.dateTime(wire, undefined, member)\n : this.#literal(wire);\n }\n default:\n return this.#literal(value);\n }\n }\n /** A whole list, bound as the container the destination column stores. */\n #listValue(\n state: ScalarState,\n values: readonly unknown[],\n field: string\n ): Sql {\n if (state.type === \"decimal\")\n return this.adapter.arrays.value(\n decimalMembers(state, values, field, this.adapter.result)\n );\n return state.type === \"enum\"\n ? this.adapter.arrays.enumValue([...values])\n : this.adapter.arrays.value(\n [...values],\n state.type === \"datetime\" || state.type === \"date\"\n ? state.type\n : undefined\n );\n }\n /** The provider's settled point protocol, or its named capability refusal. */\n #geoPoint(usage: string): GeoPointSql {\n const geoPoint = this.adapter.geoPoint;\n if (!geoPoint)\n throw new FeatureNotSupportedError(\n \"point\",\n usage,\n \"GeoPoint requires a provider with its physical point tier enabled.\"\n );\n return geoPoint;\n }\n projectedColumn(model: AnyModel, field: string, alias?: string): Sql {\n const column = this.column(model, field, alias);\n const leaf = this.scalarShape(model, field);\n const state = this.physical(model, field).state;\n if (state.type === \"bigint\" && state.array !== true)\n return this.#cast(column, \"text\");\n if (\n state.array === true &&\n (state.type === \"bigint\" || state.type === \"number\")\n )\n return this.adapter.arrays.exactNumericProjection(column);\n if (\n state.type === \"decimal\" ||\n (state.type === \"point\" && state.array !== true)\n )\n return this.#projectedTypedColumn(state, column);\n return transportedIdentifier(this.adapter, leaf.id, column, leaf.nullable);\n }\n /** A decimal or point column's projection spelling, out of line. */\n #projectedTypedColumn(state: ScalarStateOf, column: Sql): Sql {\n if (state.type === \"decimal\")\n return state.array === true\n ? this.adapter.arrays.exactNumericProjection(column)\n : this.#cast(column, \"text\");\n // A scalar point: a JSON document of its two coordinates.\n const geoPoint = this.#geoPoint(\"projection\");\n const projected = this.adapter.json.objectFromColumns([\n [\n \"longitude\",\n this.#document(this.adapter.json.number(geoPoint.longitude(column))),\n ],\n [\n \"latitude\",\n this.#document(this.adapter.json.number(geoPoint.latitude(column))),\n ],\n ]);\n return state.nullable\n ? this.#when(this.#isNull(column), this.#null(), projected)\n : projected;\n }\n /**\n * A projected value carried INSIDE a JSON document. A value that is already\n * JSON stays a document; a value the container would round stays exact text.\n */\n #carriedValue(leaf: Shape | Leaf, expression: Sql): Sql {\n if (leaf.kind !== \"scalar\") return this.#document(expression);\n // A decimal crossed the projection in the spelling {@link projectedColumn}\n // states — a text cast for a scalar, the adapter's decimal array\n // projection for a list — and its codec reads an exact value only from\n // that spelling: carried as a JSON number it is rounded by the container,\n // and carried as a JSON array its members are. This is the same physical\n // fact the projection stated, consumed rather than re-derived from the leaf.\n if (\n leaf.type === \"decimal\" ||\n ((leaf.type === \"bigint\" || leaf.type === \"number\") && leaf.list)\n )\n return leaf.list\n ? this.adapter.arrays.exactNumericProjection(expression)\n : this.#cast(expression, \"text\");\n if (\n leaf.list ||\n leaf.type === \"json\" ||\n leaf.type === \"point\" ||\n leaf.type === \"vector\"\n )\n return this.#document(expression);\n if (leaf.type === \"bigint\") return this.#cast(expression, \"text\");\n if (leaf.type === \"number\") return this.adapter.json.number(expression);\n if (leaf.type === \"blob\")\n return this.#when(\n this.#isNull(expression),\n this.#null(),\n this.adapter.expressions.blobToHex(expression)\n );\n return expression;\n }\n junctionWhere(\n edge: Extract<Membership, { kind: \"junction\" }>,\n values: Input\n ): Sql {\n return this.#and(\n ...linkMembers(edge)\n .filter(({ pair }) => Object.hasOwn(values, pair.junctionField))\n .map(({ side, pair }) =>\n this.#eq(\n this.#escaped(pair.junctionField),\n this.fieldValue(\n side.model,\n pair.referencedField,\n values[pair.junctionField]\n )\n )\n )\n );\n }\n junctionSideConditions(\n side: ResolvedJunctionSide,\n junctionAlias: string | undefined,\n endpoint: string | Input | CarriedRow\n ): Sql[] {\n return side.members.map((pair) =>\n this.#eq(\n junctionAlias\n ? this.#at(junctionAlias, pair.junctionField)\n : this.#escaped(pair.junctionField),\n typeof endpoint === \"string\"\n ? this.column(side.model, pair.referencedField, endpoint)\n : typeof endpoint === \"function\"\n ? endpoint(pair.referencedField)\n : this.fieldValue(\n side.model,\n pair.referencedField,\n endpoint[pair.referencedField]\n )\n )\n );\n }\n /** The payload {@link readUpdate} reads, refused where it cannot run. */\n #prepareUpdate(\n model: AnyModel,\n field: string,\n value: unknown\n ): PreparedUpdate {\n const update = readUpdate(value);\n // An exact decimal divided by zero fails HERE, before any statement is\n // issued: the operand's value is knowable and every dialect answers it\n // differently otherwise (SQLite NULL, MySQL NULL or an error,\n // PostgreSQL raises). The shipped refusal, verbatim.\n if (\n update.kind === \"arithmetic\" &&\n update.operator === \"divide\" &&\n exactDecimalDomain(this.physical(model, field).state) &&\n dividesByZero(update.by)\n )\n engineFault(`Cannot divide decimal field '${field}' by zero.`);\n return update;\n }\n /**\n * The target domain an arithmetic assignment lands back inside: an integer\n * column divides as an integer, an exact decimal is quantized to its scale.\n * The adapter owns both spellings; this only names the destination.\n */\n #arithmeticTarget(model: AnyModel, field: string): ArithmeticTarget {\n const state = this.physical(model, field).state;\n return {\n integer: state.type === \"int\" || state.type === \"bigint\",\n decimal: exactDecimalDomain(state),\n };\n }\n /**\n * One admitted update payload as the provider's own `SET` assignment. Every\n * operator crosses through the adapter's `set` vocabulary, so the dialect owns\n * integer truncation, decimal quantization and list concatenation, and the\n * query owner spells no arithmetic of its own.\n */\n override updateAssignment(\n model: AnyModel,\n field: string,\n value: unknown\n ): Sql {\n const a = this.adapter;\n const column = this.column(model, field);\n const update = this.#prepareUpdate(model, field, value);\n if (update.kind === \"value\")\n return a.set.assign(column, this.fieldValue(model, field, update.value));\n if (update.kind === \"list\")\n return a.set[update.operator](\n column,\n this.fieldValue(model, field, update.members)\n );\n return a.set[update.operator](\n column,\n this.fieldValue(model, field, update.by),\n this.#arithmeticTarget(model, field)\n );\n }\n /**\n * The same admitted update payload named over an ALREADY-KNOWN value: the\n * key a row will carry after the mutation, which a non-returning readback and\n * a relation-key transition both have to state in SQL.\n *\n * Every operator is named through the SAME adapter vocabulary its assignment\n * uses, so the expression and the `SET` clause cannot disagree: `+`, `-` and\n * `*` are the dialect's own native arithmetic in every non-decimal domain,\n * and an integer `divide` asks `expressions.integerDivide` for the dialect's\n * truncation — the same provider fact `set.divide`'s `target.integer` flag\n * carries, in expression form.\n *\n * The one shape with no expression form is an EXACT DECIMAL under `multiply`\n * or `divide`: there the provider's assignment is a guarded coefficient\n * rewrite that rounds half-even back to the field's scale and refuses an\n * intermediate the dialect cannot represent, and restating it here would be a\n * second arithmetic owner. The refusal is registered and recorded as a\n * decision for Arnaud (note §R2.1).\n *\n * WHICH PAYLOAD REACHES IT, measured for the N4 census (the earlier reading\n * of this paragraph named the wrong shape). A decimal RELATION key does NOT\n * reach it: a relation key written beside a mutation of that relation must be\n * a literal (`Assignments.requireLiteral`, `commands/relation-body.ts:127`),\n * so no operator survives to be named, and a key transition is the only thing\n * that would ask. The reachable shape is a decimal PRIMARY key on an UPSERT's\n * FOUND arm whose update payload names NO relation: `EngineSchema.admit`\n * states `keyPortabilityRefusal` for `update` / `updateMany`, and the found\n * arm carries it only when the update payload names relations\n * (`commands/commands.ts:1743`, the shipped gate) — so\n * `upsert({ update: { decimalKey: { multiply: n } } })` arrives here through\n * `OperationContext.updatedIdentity`, which has to ADDRESS the row it just\n * wrote. It is a TRANSPORT boundary, not an invariant: the same payload\n * succeeds on a provider with RETURNING, where the post-update key is read\n * back instead of named. Executing it therefore belongs to that read-back's\n * owner (D-50's scratch at the column's declared type), not here; an ordered\n * observation cannot answer it, because what is missing is the row's address,\n * not a value a dependent consumes.\n */\n updateValue(\n model: AnyModel,\n field: string,\n value: unknown,\n before: Sql\n ): Sql {\n const a = this.adapter;\n const update = this.#prepareUpdate(model, field, value);\n if (!this.named(model, field, update))\n engineFault(\n `Cannot determine the updated value of '${nameOf(model) ?? \"unknown\"}.${field}' before '${update.operator}' executes: the database determines the stored result.`\n );\n if (update.kind === \"value\")\n return this.fieldValue(model, field, update.value);\n const state = this.physical(model, field).state;\n const base = state.type === \"int\" ? this.#cast(before, \"integer\") : before;\n const operand = this.fieldValue(model, field, update.by);\n // A division of integers is the dialect's integer division.\n return a.expressions[\n ARITHMETIC[update.operator] ??\n (state.type === \"int\" || state.type === \"bigint\"\n ? \"integerDivide\"\n : \"divide\")\n ](base, operand);\n }\n /**\n * A read's own candidates: `selector` (absent: every row) under `purpose`.\n * Reads consume only the predicate, so the conjunction carries no facts:\n * the key-preserving form, {@link candidates}, is the write lookups'.\n */\n #within(\n model: AnyModel,\n selector: Pick<PreparedSelector, \"model\" | \"predicate\"> | undefined,\n purpose: RowPurpose\n ): Pick<PreparedSelector, \"model\" | \"predicate\"> | undefined {\n const scope = this.scope(model, purpose);\n if (scope?.predicate === undefined) return selector;\n if (selector?.predicate === undefined) return scope;\n return {\n model,\n predicate: conjunction([selector.predicate, scope.predicate]),\n };\n }\n /** `undefined` where it states nothing, or the call drops all it states. */\n override lowerSelector(\n selector: Pick<PreparedSelector, \"model\" | \"predicate\">,\n alias?: string\n ): Sql | undefined {\n if (!selector.predicate) return undefined;\n const frames = this.#frames;\n this.#frames = [{ alias, escaped: false }];\n try {\n return this.#lowerStated(selector.predicate, alias);\n } finally {\n this.#frames = frames;\n }\n }\n /**\n * The aliases of the rows a predicate being lowered reads, from its root\n * to the relation body it is in, each marked once a `{ $row, up }` inside\n * it names a row above it: such a body is correlated past its parent, so\n * it is never shared. A semijoin body's `joins` are the relations joined\n * into its `FROM` ({@link lowerRelationPredicate}); `undefined` where the\n * body takes none, and while what is lowered is not one of its conjuncts.\n */\n #frames: LoweringFrame[] = [];\n /** The alias of the row `up` bodies above the current one. */\n #outerAlias(up: number | undefined, alias: string | undefined): string {\n const frames = this.#frames;\n const at = frames.length - 1 - (up ?? 0);\n const owner = up === undefined || up === 0 ? alias : frames[at]?.alias;\n if (owner === undefined)\n unsupported(\n \"An enclosing row's column ({ $row, up }) has no row to read here.\"\n );\n for (let index = at + 1; index < frames.length; index++)\n frames[index]!.escaped = true;\n return owner;\n }\n /**\n * `predicate` lowered; `undefined` where it is made of layers the call\n * drops (R6), so a statement without them is the one without the domain.\n */\n #lowerStated(predicate: PreparedPredicate, alias?: string): Sql | undefined {\n if (predicate.kind === \"layer\") {\n const resolved = predicate.resolve(this, alias);\n if (resolved === undefined) return undefined;\n // A stack, made at the first layer this `Queries` lowers: what reads\n // it reads it while it lowers (the selectors' memo keys its content).\n const excluded = (this.excluded ??= []);\n excluded.push(predicate.layer);\n try {\n return this.#lowerPredicate(resolved, alias);\n } finally {\n excluded.pop();\n }\n }\n if (predicate.kind !== \"and\") return this.#lowerPredicate(predicate, alias);\n // No closure here: this runs at every filter node of every statement.\n const { predicates } = predicate;\n if (predicates.length === 1) {\n const only = this.#lowerStated(predicates[0]!, alias);\n return only && this.#and(only);\n }\n const members: Sql[] = [];\n // biome-ignore lint/style/useForOf: no iterator at every filter node (E5.1, measured).\n for (let index = 0; index < predicates.length; index++) {\n const lowered = this.#lowerStated(predicates[index]!, alias);\n if (lowered !== undefined) members.push(lowered);\n }\n return members.length === 0 && predicates.length > 0\n ? undefined\n : this.#and(...members);\n }\n /** An aggregate read's root filter: its `where` under the root domain. */\n lowerWhere(\n model: AnyModel,\n where: Input | undefined,\n alias?: string\n ): Sql | undefined {\n const selector = this.#within(\n model,\n where === undefined\n ? undefined\n : this.prepareSelector(model, where, false, false),\n \"root\"\n );\n return selector && this.lowerSelector(selector, alias);\n }\n /**\n * The value a LOCATED row holds for one field, read where it is SPENT:\n * `(SELECT <column> FROM <target> WHERE <this arm's selector> LIMIT 1)`,\n * inside the statement that writes it.\n *\n * A parent-held `connect` folds its target's referenced value into the\n * parent's own SET. Its planning probe answers EXISTENCE and the branch; the\n * bytes that land in the column are the target's own, read at the write — so\n * no second, re-derived provenance stands between the row the selector named\n * and the key written, and a collation that makes the selector's literal\n * differ from the stored value cannot change the answer (E1 U1, and the\n * create root's `toOneFkAssign` before it).\n *\n * Never asked where the provider refuses to read the table its own\n * statement mutates (MySQL ERROR 1093): there the row is read first\n * (`Store.#presume`).\n */\n override locatedValue(\n model: AnyModel,\n field: string,\n selector: PreparedSelector\n ): Sql {\n const alias = this.alias();\n return this.#scalar({\n columns: this.column(model, field, alias),\n from: this.table(model, alias),\n where: this.lowerSelector(selector, alias),\n limit: this.value(1),\n });\n }\n lowerMutationLimit(\n model: AnyModel,\n selector: PreparedSelector,\n limit: number | undefined\n ): { readonly where?: Sql; readonly suffix?: Sql } {\n const adapter = this.adapter;\n // The UPDATE/DELETE target carries no alias, so it is addressable only by\n // its NAME. Without that qualifier a correlated `EXISTS` emits the parent\n // column bare and it rebinds to the CHILD table wherever both carry the\n // name — `some` matches nothing, `none`/`every` match everything, and a\n // `deleteMany` removes the complement of the intended set. The shipped\n // engine passed the table name for exactly this reason\n // (`operations/update.ts:79-90`, `delete.ts:85-92`).\n const mutated = tableOf(model);\n // MySQL answers an UPDATE/DELETE's subquery row by row while the statement\n // and the referential actions it fires change the rows that subquery\n // reads, which is also why it refuses to read the mutated table there\n // (ERROR 1093). A selector that reads other rows is therefore its keys,\n // read into a derived table before any write: the statement snapshot\n // PostgreSQL and SQLite answer from.\n const where =\n !adapter.capabilities.supportsMutationTargetInSubquery &&\n selector.predicate !== undefined &&\n readsRelation(selector.predicate)\n ? this.#capped(selector)\n : this.lowerSelector(selector, mutated);\n if (limit === undefined) return { where };\n // A limited write takes the first `limit` rows in key order, the order a\n // read's `take` completes with: every path picks the same rows. MySQL,\n // which refuses a `LIMIT` inside `IN`, states it on the statement itself.\n if (!adapter.capabilities.supportsMutationRowLimit)\n return {\n where: adapter.operators.and(\n ...[where, this.#capped(selector, limit)].filter(\n (condition): condition is Sql => condition !== undefined\n )\n ),\n };\n return {\n where,\n suffix: sql`${adapter.clauses.orderBy(this.ascendingKeys(model))} ${adapter.clauses.limit(this.value(limit))}`,\n };\n }\n /**\n * `<keys> IN (SELECT * FROM (SELECT <keys> FROM <model> WHERE <selector>\n * ORDER BY <keys> LIMIT <limit>) AS <alias>)`, the keys outside addressed\n * through `alias`: the first `limit` rows in key order, a mutation's limit\n * where the provider has no `UPDATE … LIMIT`, and a {@link window}; without\n * a `limit`, every row, a MySQL mutation's keyed snapshot\n * ({@link lowerMutationLimit}). Where the provider cannot read a mutation's\n * own table in a subquery (MySQL, ERROR 1093), the read sits in a derived\n * table, materialized before the write: MySQL also refuses a `LIMIT` directly\n * inside `IN (…)`, and the derived table answers both, in the premise's\n * SELECT and in the effect.\n */\n #capped(selector: PreparedSelector, limit?: number, alias?: string): Sql {\n const adapter = this.adapter;\n const model = selector.model;\n const inner = this.alias();\n const keys = this.keyOrder(model);\n const capped = assembleAdapterSelect(adapter, {\n columns: listed(keys.map((field) => this.column(model, field, inner))),\n from: this.table(model, inner),\n where: this.lowerSelector(selector, inner),\n ...(limit === undefined\n ? {}\n : {\n orderBy: this.ascendingKeys(model, inner),\n limit: this.value(limit),\n }),\n });\n return adapter.operators.in(\n rowValue(keys.map((field) => this.column(model, field, alias))),\n adapter.subqueries.scalar(\n adapter.capabilities.supportsMutationTargetInSubquery\n ? capped\n : throughDerived(adapter, capped, this.alias())\n )\n );\n }\n /** `<key> ASC, …` in {@link keyOrder}, the keys addressed through `alias`. */\n ascendingKeys(model: AnyModel, alias?: string): Sql {\n return listed(\n this.keyOrder(model).map((field) =>\n this.adapter.orderBy.asc(this.column(model, field, alias))\n )\n );\n }\n lowerIdentity(model: AnyModel, identity: Input, alias?: string): Sql {\n return this.#and(\n ...Object.entries(identity).map(([field, value]) =>\n this.#eq(\n this.column(model, field, alias),\n this.fieldValue(model, field, value)\n )\n )\n );\n }\n /**\n * `predicate` lowered under an `OR` or a `NOT`: not a conjunct of the body\n * it is in, so no relation in it joins that body.\n */\n #apart(predicate: PreparedPredicate, alias?: string): Sql {\n const frame = this.#frames.at(-1);\n const joins = frame?.joins;\n if (joins === undefined) return this.#lowerPredicate(predicate, alias);\n frame!.joins = undefined;\n try {\n return this.#lowerPredicate(predicate, alias);\n } finally {\n frame!.joins = joins;\n }\n }\n #lowerPredicate(predicate: PreparedPredicate, alias?: string): Sql {\n // biome-ignore lint/style/useDefaultSwitchClause: the prepared predicate union is exhaustive; a default would be dead code.\n switch (predicate.kind) {\n case \"and\":\n case \"layer\":\n return this.#lowerStated(predicate, alias) ?? this.#true();\n case \"or\":\n // A balanced tree, not a chain: SQLite parses `a OR b OR …` one\n // expression level deep per arm and refuses depth 1000 (platform-15).\n return balancedOr(\n predicate.predicates.map((member) => this.#apart(member, alias)),\n (arms) => this.#or(...arms)\n );\n case \"not\":\n return this.adapter.operators.not(\n this.#opposite(() => this.#apart(predicate.predicate, alias))\n );\n case \"always\":\n return predicate.value ? this.#true() : this.#false();\n case \"condition\":\n return predicate.condition.holds(this.values, this.instant)\n ? this.#true()\n : this.#false();\n case \"operation\":\n return this.lowerOperation(this.#bound(predicate), alias);\n case \"relation\":\n return this.#lowerRelationPredicate(predicate, alias);\n case \"exists\":\n return this.#lowerExists(predicate, alias ?? \"\");\n case \"window\":\n return this.#capped(predicate.selector, predicate.limit, alias);\n }\n }\n /**\n * The operation with its parameters' values read for this call, so the\n * value-dependent lowering reads them as any value. R6 has made each\n * present (a spread one a list).\n */\n #bound(predicate: OperationPredicate): BoundOperation {\n if (\n predicate.operand?.kind !== \"parameter\" &&\n !(predicate.value instanceof Parameter) &&\n !predicate.operands?.some(isParameterOperand)\n )\n return predicate as BoundOperation;\n return this.#boundParameters(predicate);\n }\n /** {@link bound}'s operation, which reads at least one parameter. */\n #boundParameters(predicate: OperationPredicate): BoundOperation {\n const { operand, operands, value, ...rest } = predicate;\n const read = (parameter: Parameter) =>\n parameter.read(this.values, this.instant);\n const bound = (member: PreparedOperand): BoundOperand[] => {\n if (member.kind !== \"parameter\") return [member];\n const given = read(member.parameter);\n return member.spread\n ? (given as unknown[]).map((item) => ({ kind: \"value\", value: item }))\n : [{ kind: \"value\", value: given }];\n };\n return {\n ...rest,\n ...(operand && { operand: bound(operand)[0]! }),\n ...(operands && { operands: operands.flatMap(bound) }),\n value: value instanceof Parameter ? read(value) : value,\n };\n }\n #preparedColumn(scalar: PreparedScalar, alias?: string): Sql {\n return this.#guarded(\n scalar.model,\n scalar.field,\n alias\n ? this.#at(alias, scalar.physical.name)\n : this.#escaped(scalar.physical.name),\n alias\n );\n }\n /**\n * `column`, `model`'s `field` at `alias`, as an operand the caller wrote\n * (K5): a read-gated field reads NULL on a row that does not carry it, in\n * every position a caller writes it. A layer's predicates read the column\n * itself: they lower inside the layer.\n */\n #guarded(model: AnyModel, field: string, column: Sql, alias?: string): Sql {\n return this.#lowersLayer || this.#masked\n ? column\n : (this.domain?.project?.guarded(this, model, field, column, alias) ??\n column);\n }\n /** `model`'s `field` at `alias` as an operand the caller wrote ({@link guarded}). */\n #operand(model: AnyModel, field: string, alias?: string): Sql {\n return this.#guarded(model, field, this.column(model, field, alias), alias);\n }\n /** `model`'s read-gated fields, where the call's domain gates some (K5). */\n #gates(model: AnyModel) {\n return this.domain?.project?.projected(model)?.gates;\n }\n /** Whether a caller's operand over `model`'s `field` may read NULL (K5). */\n #gatedHere(model: AnyModel, field: string): boolean {\n return !this.#lowersLayer && this.#gates(model)?.has(field) === true;\n }\n /** `fn` lowered over a masked window ({@link masked}). */\n #overMasked<T>(fn: () => T): T {\n this.#masked = true;\n try {\n return fn();\n } finally {\n this.#masked = false;\n }\n }\n #lowerTarget(target: PreparedTarget, alias?: string): Sql {\n return target.kind === \"column\"\n ? this.#preparedColumn(target.scalar, alias)\n : this.#aggregateExpression(target.aggregate, target.scalar, alias);\n }\n private lowerOperation(predicate: BoundOperation, alias?: string): Sql {\n const a = this.adapter;\n const { operator, target, operand } = predicate;\n const scalar = target.scalar;\n // A `_count` compares with `COUNT(col)`, a row count on every storage, and\n // admission types its operand as a number (`numericFilterOps`). It has no\n // column domain: no JSON document class, no text collation, no identifier\n // or decimal binding — every domain dispatch below reads `state`, so the\n // fact is stated once, here.\n const counted =\n target.kind === \"aggregate\" && target.aggregate === \"_count\";\n const state = counted ? undefined : scalar?.physical.state;\n const column = this.#lowerTarget(target, alias);\n if (state?.type === \"json\" && state.array !== true)\n return this.#lowerJsonOperation(predicate, column);\n const insensitive = predicate.insensitive === true;\n // A discriminator member is compared by the constraint that answers it; the\n // engine's case-sensitivity contract governs every other comparison. An\n // `insensitive` mode is a filter spelling and never reaches a discriminator,\n // so it keeps the folded pair rather than silently folding one side.\n // A COLUMN target's identifier storage: its value operands bind the\n // physical form, and a compact column is compared as the bytes (or the\n // `uuid`) it holds — never collated or ASCII-folded as text.\n const id =\n target.kind === \"column\" && scalar\n ? this.scalarShape(scalar.model, scalar.field).id\n : undefined;\n const text =\n !(target.kind === \"column\" && target.key === true && !insensitive) &&\n state !== undefined &&\n state.array !== true &&\n (state.type === \"string\" || state.type === \"enum\") &&\n !isCompact(id);\n const pattern =\n operator === \"contains\" ||\n operator === \"startsWith\" ||\n operator === \"endsWith\";\n const exact = (expression: Sql, field = scalar) =>\n text\n ? a.expressions.caseSensitiveText(\n expression,\n field?.physical.nativeType,\n pattern || insensitive\n )\n : expression;\n const nativeType = scalar?.physical.nativeType;\n // The database's own case fold, compared exactly: case is the one\n // difference `mode: \"insensitive\"` ignores, and which letters have a case\n // is the database's answer.\n const folded =\n text && insensitive\n ? a.expressions.caseSensitiveText(\n a.expressions.caseFold(column, nativeType)\n )\n : column;\n /**\n * An enum compared against ANOTHER COLUMN compares its SPELLING — on BOTH\n * sides, on every dialect. PostgreSQL gives each enum field its own type,\n * so `status = review_status` has no operator there (42883) while MySQL and\n * SQLite, which store the value as text, answer it; casting the operand\n * alone left the filtered column typed as its own enum and produced\n * `post_status = text`. A LITERAL operand still binds an enum-typed\n * parameter against the bare column, so ordinary enum equality keeps its\n * index. Ordered comparison has no portable answer and is refused at\n * admission (`validation/scalars/enum.ts`), so equality — and the `not`\n * that negates it — is the whole reach of this fact.\n */\n const spelledAsText = (member: BoundOperand): boolean =>\n member.kind === \"field\" &&\n (state?.type === \"enum\" || member.scalar.physical.state.type === \"enum\");\n const comparableColumn = (member: BoundOperand): Sql =>\n exact(spelledAsText(member) ? this.#cast(column, \"text\") : column);\n /** An operand as it stands: neither folded nor compared exactly. */\n const raw = (member: BoundOperand): Sql => {\n if (member.kind === \"field\") {\n const reference = this.#preparedColumn(\n member.scalar,\n member.up === undefined ? alias : this.#outerAlias(member.up, alias)\n );\n return spelledAsText(member)\n ? this.#cast(reference, \"text\")\n : reference;\n }\n if (member.kind === \"sql\")\n return this.value(\n new Sql(\n member.strings,\n member.operands.map((slot) =>\n slot.kind === \"field\"\n ? this.#preparedColumn(slot.scalar, alias)\n : slot.value\n )\n )\n );\n return scalar && !counted\n ? this.#targetValue(target, scalar, member.value, id)\n : this.value(member.value);\n };\n const bind = (member: BoundOperand, fold = false): Sql => {\n const operand = raw(member);\n if (member.kind !== \"field\")\n return fold ? a.expressions.caseFold(operand) : operand;\n return fold\n ? a.expressions.caseSensitiveText(\n a.expressions.caseFold(operand, member.scalar.physical.nativeType)\n )\n : exact(operand, member.scalar);\n };\n switch (operator) {\n case \"equals\": {\n const single = operand!;\n const literal = single.kind === \"value\" ? single.value : undefined;\n if (single.kind === \"value\" && literal === null)\n return this.#isNull(column);\n if (state?.type === \"point\" && state.array !== true)\n return this.#geoPoint(\"equals\").equals(column, literal as GeoPoint);\n if (state?.array === true && Array.isArray(literal))\n return this.#eq(column, bind(single));\n if (\n insensitive &&\n (single.kind !== \"value\" ||\n typeof literal === \"string\" ||\n literal instanceof Sql)\n )\n return this.#eq(folded, bind(single, true));\n if (text && single.kind === \"value\" && !(literal instanceof Sql))\n return a.operators.exactTextEq(column, bind(single), nativeType);\n return this.#eq(comparableColumn(single), bind(single));\n }\n case \"lt\":\n case \"lte\":\n case \"gt\":\n case \"gte\":\n return a.operators[operator](\n text && insensitive ? folded : exact(column),\n bind(operand!, text && insensitive)\n );\n default:\n return this.#lowerOtherOperation(predicate, {\n column:\n pattern &&\n !(\n operator === \"startsWith\" &&\n operand?.kind === \"value\" &&\n typeof operand.value === \"string\"\n )\n ? exact(column)\n : column,\n source: column,\n folded,\n insensitive,\n text,\n exact,\n bind,\n raw,\n nativeType,\n state,\n });\n }\n }\n /**\n * The less common filter operators, kept out of {@link lowerOperation} so a\n * first query that compares by equality never compiles them.\n */\n #lowerOtherOperation(\n predicate: BoundOperation,\n {\n column,\n source,\n folded,\n insensitive,\n text,\n exact,\n bind,\n raw,\n nativeType,\n state,\n }: {\n column: Sql;\n /** The target before any case-sensitivity wrapping. */\n source: Sql;\n folded: Sql;\n insensitive: boolean;\n text: boolean;\n exact: (expression: Sql) => Sql;\n bind: (member: BoundOperand, fold?: boolean) => Sql;\n raw: (member: BoundOperand) => Sql;\n nativeType: NativeTypeDeclaration | undefined;\n state: ScalarStateOf | undefined;\n }\n ): Sql {\n const a = this.adapter;\n const { operator, operand } = predicate;\n const scalar = predicate.target.scalar;\n const members = () => predicate.operands ?? [];\n switch (operator) {\n case \"in\":\n case \"notIn\": {\n const negated = operator === \"notIn\";\n const operands = members();\n if (operands.length === 0)\n return negated ? this.#true() : this.#false();\n if (insensitive) {\n const comparisons = operands.map((member) =>\n negated\n ? a.operators.neq(folded, bind(member, true))\n : this.#eq(folded, bind(member, true))\n );\n // One comparison per member: balanced, as an `OR` is (platform-15).\n return balancedOr(comparisons, (arms) =>\n negated ? this.#and(...arms) : this.#or(...arms)\n );\n }\n const list = a.literals.list(operands.map((member) => bind(member)));\n if (negated) return a.operators.notIn(exact(column), list);\n return text\n ? a.operators.exactTextIn(column, list, nativeType)\n : a.operators.in(column, list);\n }\n case \"contains\":\n case \"startsWith\":\n case \"endsWith\":\n if (insensitive)\n return a.operators.insensitiveText(\n operator,\n source,\n raw(operand!),\n nativeType\n );\n return operator === \"startsWith\" &&\n operand!.kind === \"value\" &&\n typeof operand!.value === \"string\"\n ? a.operators.startsWithPrefix(column, operand!.value, nativeType)\n : a.operators[`${operator}Text`](column, bind(operand!));\n case \"has\":\n return predicate.value === null\n ? this.#false()\n : a.arrays.has(\n column,\n this.#scalarValue(\n scalar!.physical.scalar,\n predicate.value,\n scalar!.field\n )\n );\n case \"hasEvery\":\n case \"hasSome\": {\n const values = predicate.value as unknown[];\n // Every member of none holds of any list there is; some member of none, of no list.\n if (values.length === 0)\n return operator === \"hasEvery\"\n ? this.#isNotNull(column)\n : this.#false();\n return a.arrays[operator](\n column,\n this.#scalarValue(scalar!.physical.scalar, values, scalar!.field)\n );\n }\n case \"isEmpty\":\n return predicate.value\n ? a.arrays.isEmpty(column)\n : a.operators.not(a.arrays.isEmpty(column));\n case \"within\": {\n const area = predicate.value as GeoArea;\n const geoPoint = this.#geoPoint(\"within\");\n if (\"bounds\" in area) return geoPoint.withinBounds(column, area.bounds);\n if (geoPoint.withinPolygon)\n return geoPoint.withinPolygon(column, area.polygon);\n throw new FeatureNotSupportedError(\n \"point\",\n \"within polygon\",\n \"GeoPoint polygon filtering is not supported by this provider.\"\n );\n }\n default: {\n // `distance`, the one operator left. Admission enumerates this\n // operator set once, per scalar type (`validation/scalars/**`), and\n // `prepareOperation` carries the key it admitted; there is no second\n // operator list here to disagree with it (AGENTS.md: \"Do not add a\n // second operator switch\").\n const specification = predicate.value as Input;\n const expression = this.#distanceExpression(\n column,\n state!,\n scalar!.field,\n specification,\n \"filter\"\n );\n // The index probe. `distance <= X` implies `withinBounds(box(X))`, so\n // the box is a redundant conjunct the provider can answer from the\n // spatial index before it evaluates one great-circle distance. It is\n // added only where preparation saw POSITIVE polarity\n // ({@link PreparedPredicate.probe}); the adapter spells both arms.\n const upper = predicate.probe\n ? distanceUpperBound(specification)\n : undefined;\n const probe =\n upper === undefined\n ? []\n : [\n this.#geoPoint(\"distance filter\").withinBounds(\n column,\n geoBoundsForDistance(specification.to as GeoPoint, upper)\n ),\n ];\n return this.#and(\n ...probe,\n ...([\"lt\", \"lte\", \"gt\", \"gte\"] as const)\n .filter((bound) => specification[bound] !== undefined)\n .map((bound) =>\n a.operators[bound](expression, this.value(specification[bound]))\n )\n );\n }\n }\n }\n /**\n * One operand, bound in the domain of the expression it is COMPARED WITH.\n * A `_count` never reaches here: `lowerOperation` binds its row-count\n * operand as a plain value.\n *\n * Everything compares inside the field's own domain except a `_sum` over an\n * exact decimal: the compared expression is the column's sum, whose value is\n * wider than one column can hold, so the operand's cast widens the PRECISION\n * while keeping the field's SCALE — every summed row carries that scale, and an\n * operand at another one would be a different number on SQLite. The adapter\n * states how wide its exact HAVING cast can be; the refusal below is the\n * shipped sentence, verbatim.\n */\n #targetValue(\n target: PreparedTarget,\n scalar: PreparedScalar,\n value: unknown,\n id: IdentifierColumn | undefined\n ): Sql {\n if (\n target.kind === \"aggregate\" &&\n (target.aggregate === \"_min\" || target.aggregate === \"_max\")\n ) {\n const aggregateId = this.scalarShape(scalar.model, scalar.field).id;\n if (isCompact(aggregateId))\n return aggregatedIdentifier(\n this.adapter,\n aggregateId,\n this.#scalarValue(\n scalar.physical.scalar,\n value,\n scalar.field,\n aggregateId\n )\n );\n }\n if (target.kind === \"aggregate\" && target.aggregate === \"_sum\")\n return this.#sumTargetValue(scalar, value, id);\n return this.#scalarValue(scalar.physical.scalar, value, scalar.field, id);\n }\n /** A `_sum` operand, out of line: only a decimal HAVING widens its cast. */\n #sumTargetValue(\n scalar: PreparedScalar,\n value: unknown,\n id: IdentifierColumn | undefined\n ): Sql {\n const state = scalar.physical.state;\n const domain = exactDecimalDomain(state);\n const operand = domain ? decimalSumOperand(value, domain) : undefined;\n // A value that is not an exact decimal is the ordinary binder's refusal.\n if (!domain || operand === undefined)\n return this.#scalarValue(scalar.physical.scalar, value, scalar.field, id);\n const { canonical, coefficient } = operand;\n const precision =\n this.adapter.aggregates.decimalSumOperandPrecision(coefficient);\n if (precision === undefined) {\n const digits = coefficient.startsWith(\"-\")\n ? coefficient.length - 1\n : coefficient.length;\n engineFault(\n `The 'having' _sum operand for decimal field '${scalar.field}' needs ${digits} coefficient digits, but its value is outside this provider's exact HAVING operand cast domain. ` +\n \"The provider may compute a wider sum, but VibORM cannot express this operand through its exact decimal cast without changing or refusing the value written.\"\n );\n }\n return this.adapter.literals.decimal(canonical, {\n precision: Math.max(domain.precision, precision),\n scale: domain.scale,\n });\n }\n /**\n * THE JSON NULL TRUTH TABLE and the document operator set. A JSON column's\n * operands are documents rather than scalars, which is a storage difference,\n * not a second semantic interpretation of the same operator.\n *\n * The target always names a scalar here: `lowerOperation` reaches this only\n * when that scalar's own state is a JSON document — never for a `_count`,\n * which has no column domain. A path with a null sentinel is refused at\n * admission (`pathSentinelRefusal`, validation/scalars/json.ts).\n */\n #lowerJsonOperation(predicate: BoundOperation, column: Sql): Sql {\n const a = this.adapter;\n const path = [\n ...(predicate.target.kind === \"column\"\n ? (predicate.target.path ?? [])\n : []),\n ];\n const value = predicate.value;\n const target = a.json.extract(column, path);\n const text = (kind: TextMatch, member: unknown): Sql => {\n const operand = this.#literal(member);\n return predicate.insensitive\n ? a.operators.insensitiveText(\n kind,\n a.json.foldableStringAtPath(column, path),\n operand\n )\n : a.operators[`${kind}Text`](\n a.json.stringAtPath(column, path),\n operand\n );\n };\n switch (predicate.operator) {\n case \"equals\": {\n const sentinel = jsonNullKindOf(value);\n if (sentinel) {\n const isDatabaseNull = this.#isNull(column);\n const isJsonNull = a.json.equals(target, a.json.value(null));\n if (sentinel === \"DbNull\") return isDatabaseNull;\n if (sentinel === \"JsonNull\") return isJsonNull;\n return this.#or(isDatabaseNull, isJsonNull);\n }\n if (value === null && path.length === 0) return this.#isNull(column);\n return a.json.equals(target, a.json.value(value));\n }\n case \"lt\":\n case \"lte\":\n case \"gt\":\n case \"gte\": {\n const compare = a.operators[predicate.operator];\n if (typeof value === \"number\")\n return compare(a.json.numberAtPath(column, path), this.value(value));\n if (typeof value === \"string\")\n return compare(a.json.stringAtPath(column, path), this.value(value));\n return engineFault(\n `JSON filter '${predicate.operator}' requires a number or string operand.`\n );\n }\n case \"string_contains\":\n return text(\"contains\", value);\n case \"string_starts_with\":\n return text(\"startsWith\", value);\n case \"string_ends_with\":\n return text(\"endsWith\", value);\n case \"array_contains\":\n return a.json.contains(\n target,\n a.json.value(Array.isArray(value) ? value : [value])\n );\n case \"array_starts_with\":\n return a.json.equals(\n a.json.extract(column, [...path, \"0\"]),\n a.json.value(value)\n );\n default:\n // `array_ends_with`, the one operator left: the same upstream owner as\n // the scalar operator switch above enumerates the JSON document\n // operators once, at admission.\n return a.json.equals(a.json.lastElement(target), a.json.value(value));\n }\n }\n /** One distance expression, for filters, ordering and projection alike. */\n #distanceExpression(\n column: Sql,\n state: ScalarState,\n field: string,\n specification: Input,\n usage: \"filter\" | \"orderBy\" | \"select\",\n servable = false\n ): Sql {\n if (state.type === \"vector\") {\n if (!this.adapter.capabilities.supportsVector)\n throw new FeatureNotSupportedError(\n \"vector\",\n usage,\n usage === \"orderBy\"\n ? \"vector ordering requires a pgvector-enabled PostgreSQL driver\"\n : \"vector distance select requires a pgvector-enabled PostgreSQL driver\"\n );\n const to = specification.to as number[];\n const { dimension } = state;\n if (dimension !== undefined && to.length !== dimension)\n unsupported(\n `Vector distance ${usage} dimension mismatch for '${field}': expected ${dimension} values, received ${to.length}.`\n );\n const metric = specification.metric === \"cosine\" ? \"cosine\" : \"l2\";\n return this.adapter.vector[metric](\n column,\n this.adapter.vector.literal(to),\n usage === \"orderBy\" ? (servable ? \"servable\" : \"exact\") : undefined\n );\n }\n const geoPoint = this.#geoPoint(`distance ${usage}`);\n if (!geoPoint.distance)\n throw new FeatureNotSupportedError(\n \"point\",\n `distance ${usage}`,\n \"GeoPoint distance is not supported by this provider.\"\n );\n const target = specification.to as GeoPoint;\n return geoPoint.distance(\n column,\n geoPoint.value(this.value(target.longitude), this.value(target.latitude))\n );\n }\n #lowerRelationPredicate(\n predicate: Extract<PreparedPredicate, { kind: \"relation\" }>,\n parentAlias?: string\n ): Sql {\n if (\n predicate.quantifier === \"every\" &&\n predicate.link === undefined &&\n !(predicate.predicate && states(predicate.predicate))\n )\n return this.#true();\n const { edge, closure } = predicate;\n const childAlias = this.#rowAlias(edge.target);\n const linkAlias = predicate.link ? this.alias() : undefined;\n // A semijoin over a plain reference: `some`/`is` with a body, neither a\n // walk nor a variant arm. Its `FROM` takes the semijoins among its\n // conjuncts that read a row above it (`joins`), and it is one of those\n // where it is a conjunct of a semijoin body and reads above that body.\n const semijoin =\n closure === undefined &&\n predicate.predicate !== undefined &&\n (predicate.quantifier === \"some\" || predicate.quantifier === \"is\") &&\n edge.kind === \"reference\" &&\n edge.discriminator === undefined;\n const frame: LoweringFrame = {\n alias: childAlias,\n escaped: false,\n ...(semijoin && { joins: [] }),\n };\n const parent = semijoin ? this.#frames.at(-1) : undefined;\n const joinable = parent?.joins !== undefined;\n // The body reads above its parent where lowering it marks the parent, so\n // the parent's own mark waits aside meanwhile.\n const marked = parent?.escaped === true;\n if (joinable) parent!.escaped = false;\n this.#frames.push(frame);\n let nested: Sql | undefined;\n const body = predicate.predicate;\n const enclosing: Enclosing = {};\n try {\n nested =\n body === undefined\n ? undefined\n : this.#inside(enclosing, () =>\n predicate.quantifier === \"none\" ||\n predicate.quantifier === \"isNot\"\n ? this.#opposite(() => this.#lowerPredicate(body, childAlias))\n : this.#lowerPredicate(body, childAlias)\n );\n } finally {\n this.#frames.pop();\n }\n if (predicate.link) {\n // A layer's own rule reads what it states; a caller's filter is a test\n // of a column a direct read of it could hide.\n if (!this.#lowersLayer)\n this.domain?.refuseHiddenLinkRow(\n this,\n edge,\n predicate.linkFields!,\n \"filter\"\n );\n const held = this.#lowerPredicate(predicate.link, linkAlias);\n nested = nested ? this.#and(nested, held) : held;\n }\n if (joinable) {\n const above = parent!.escaped;\n parent!.escaped ||= marked;\n if (above) {\n // `EXISTS (… WHERE p AND EXISTS (… WHERE q))` is `EXISTS (… JOIN …\n // WHERE p AND q)`: the inner EXISTS is two-valued, so a conjunct\n // that holds for one joined row holds for the outer row. Correlated\n // past its parent, the nested EXISTS is a subplan PostgreSQL runs per\n // outer row and parent row; joined, the outer one is one semijoin\n // (PGlite, 200k rows: a count 864 ms to 87 ms).\n parent!.joins!.push(\n this.#inner(\n this.table(edge.target, childAlias),\n this.#correlated(\n edge,\n parentAlias ?? \"\",\n childAlias,\n predicate.unscoped === undefined,\n readsRelation(predicate.predicate!)\n )\n ),\n ...frame.joins!\n );\n return nested!;\n }\n }\n const stated = nested\n ? [\n predicate.quantifier === \"every\"\n ? this.adapter.operators.not(nested)\n : nested,\n ]\n : [];\n const quantified = this.#quantified(predicate);\n // What the quantifier ranges over (membership, the related domain, a\n // walk's hops) stands negated where it does not hold (`none`, `every`,\n // `isNot`): fewer rows there make the test hold more often.\n const range = (): Sql => {\n if (closure) {\n // The walk is this EXISTS's OWN `WITH`, never wrapped in a derived table\n // or a LATERAL: MySQL answers every outer row from one evaluation of a\n // wrapped correlated recursive CTE wherever the EXISTS is not flattened.\n // The walk owns membership and visibility; the reader joins by key.\n const { cte, cteName, walk, childColumns } = this.walk(\n edge,\n parentAlias ?? \"\",\n closure\n );\n const query = sql`${cte} ${this.adapter.subqueries.existsCheck(\n sql`${this.#named(this.#escaped(cteName), walk)} ${this.#inner(\n this.table(edge.target, childAlias),\n this.sameRow(\n edge.target,\n childAlias,\n childColumns.map((name) => this.#at(walk, name))\n )\n )}${this.#attachPoint(childAlias)}`,\n this.#and(...stated)\n )}`;\n // Admission refuses a `$row` across a recursive relation: what the\n // walk states reads no row above the one it reaches.\n return this.#sharedWalk(\n edge,\n parentAlias ?? \"\",\n childAlias,\n closure,\n stated,\n query,\n quantified,\n // A walk `every` judges reaches back from the rows its predicate\n // does not hold of: never the few its author stated.\n closure.selective === true && predicate.quantifier !== \"every\"\n );\n }\n return this.#relationExists(\n edge,\n parentAlias ?? \"\",\n childAlias,\n predicate.unscoped === undefined,\n stated,\n quantified,\n enclosing,\n predicate.predicate !== undefined && readsRelation(predicate.predicate),\n frame.escaped,\n frame.joins,\n linkAlias\n );\n };\n return quantified.holds ? range() : this.#opposite(range);\n }\n /**\n * How `predicate`'s quantifier tests its relation's subquery: a row exists\n * (`some`, an `is` with a body, an `isNot` without one) or none does. Of no\n * row, `is` and `isNot` read as each other; `every` tests that no row\n * fails its body.\n */\n #quantified(\n predicate: Extract<PreparedPredicate, { kind: \"relation\" }>\n ): Quantified {\n const { quantifier } = predicate;\n const holds =\n quantifier === \"some\" ||\n quantifier === (predicate.predicate ? \"is\" : \"isNot\");\n return { of: this.adapter.filters[holds ? \"some\" : \"none\"], holds };\n }\n /**\n * The related domain of a relation's rows, where `scoped`. Where the filter\n * goes on below (`deeper`), a dialect that sums nested heights adds this\n * level's `WHERE` height to every level under it: the domain, isolated,\n * pays its own height once, at the end of its branch\n * (`subqueries.isolated`; ENG-6, review 2).\n */\n #relatedWhere(\n edge: Membership,\n child: string,\n scoped: boolean,\n deeper: boolean\n ): Sql | undefined {\n const domain = scoped ? this.domainOf(edge.target, \"related\") : undefined;\n const lowered = domain && this.lowerSelector(domain, child)!;\n return lowered && deeper\n ? this.adapter.subqueries.isolated(lowered)\n : lowered;\n }\n /** A joined relation's `ON`: its membership, then its related domain. */\n #correlated(\n edge: Membership,\n parent: string,\n child: string,\n scoped: boolean,\n deeper: boolean\n ): Sql {\n const member = this.#membershipWhere(edge, child, parent);\n const related = this.#relatedWhere(edge, child, scoped, deeper);\n return related ? this.#and(member, related) : member;\n }\n /**\n * `EXISTS (SELECT 1 FROM target WHERE correlation AND stated)`: inside a\n * statement sharing its bodies ({@link sharingBodies}), a slot the\n * statement settles to that where the body is lowered once, and else to a\n * test of the body's key set, `EXISTS (SELECT 1 FROM <set> WHERE set.k =\n * parent.fk)`: a semijoin on the correlated columns, read under the same\n * layers and values, so it takes exactly the rows the EXISTS takes. A\n * reference edge only (a junction's and a variant's membership stay\n * where they are), and a body that states something. A junction's\n * membership is its join where the dialect plans that better, on\n * PostgreSQL outside a bounded read ({@link junctionJoin}).\n */\n #relationExists(\n edge: Membership,\n parent: string,\n child: string,\n scoped: boolean,\n stated: readonly Sql[],\n quantified: Quantified,\n enclosing: Enclosing,\n deeper = false,\n correlatedAbove = false,\n joins: readonly Sql[] = [],\n link?: string\n ): Sql {\n const a = this.adapter;\n const junctions = a.capabilities.joinsJunctionFilters;\n // A `$through` condition reads the link row, so that row is joined whatever\n // the dialect prefers: the membership's `IN` keeps it out of the body.\n const joined =\n edge.kind === \"junction\" &&\n (link !== undefined ||\n junctions === true ||\n (junctions === \"unbounded\" && !this.#bounded))\n ? this.#junctionJoin(edge, child, parent, link)\n : undefined;\n const member =\n joined?.correlation ?? this.#membershipWhere(edge, child, parent);\n // The related domain is read in this body: a walk it holds lives where\n // its text does.\n const related = this.#inside(enclosing, () =>\n this.#relatedWhere(edge, child, scoped, deeper)\n );\n // A flag join keeps SQLite from flattening the derived table each level\n // of a nested filter reads from on D1, adding the level's height to every\n // level above it (a three-arm rule at 15 levels passes depth 100).\n const table =\n joined?.from ??\n (a.capabilities.boundsExpressionDepth === true\n ? this.table(edge.target, child)\n : this.#attached(edge.target, child));\n const inline = quantified.of(\n a.subqueries.existsCheck(\n joins.length === 0 ? table : sql`${table} ${sql.join(joins, \" \")}`,\n this.#and(related ? this.#and(member, related) : member, ...stated)\n )\n );\n const shared = this.#shared;\n const conditions = related ? [related, ...stated] : stated;\n if (\n shared === undefined ||\n correlatedAbove ||\n joins.length > 0 ||\n edge.kind !== \"reference\" ||\n edge.discriminator !== undefined ||\n conditions.length === 0\n )\n return inline;\n const query = assembleAdapterSelect(a, {\n columns: listed(\n edge.pairs.map((pair, index) =>\n this.#named(this.column(edge.target, pair.target, child), `k${index}`)\n )\n ),\n from: this.#attached(edge.target, child),\n where: this.#and(\n ...conditions,\n ...(quantified.holds ? this.#setBound(edge.target, child) : [])\n ),\n });\n const placed = this.#placed(\n shared,\n sharedKey(query),\n () => ({ query, correlated: true }),\n inline,\n quantified,\n parent,\n edge.source,\n edge.pairs.map((pair) => pair.source)\n );\n enclosing.body = placed.body;\n return placed.slot;\n }\n /**\n * A place the statement reads a shared body at: the body `key` names,\n * stated once (`state`, where it is new), and the slot the statement\n * settles to `inline`, or to a test of the body as `quantified` reads it:\n * of the keys `fields` of `model` name on `alias`, where it has keys.\n */\n #placed(\n shared: SharedBodies,\n key: string,\n state: (name: string) => Omit<SharedBody, \"name\" | \"slots\">,\n inline: Sql,\n quantified: Quantified,\n alias: string,\n model?: AnyModel,\n fields: readonly string[] = [],\n within?: PlacedBody[\"within\"]\n ): { readonly body: SharedBody; readonly slot: Sql } {\n let body = shared.byKey.get(key);\n if (body === undefined) {\n const name = `__shared_${shared.order.length}`;\n body = { name, slots: [], ...state(name) };\n shared.byKey.set(key, body);\n shared.order.push(body);\n }\n const { name } = body;\n const use = quantified.of(\n this.adapter.subqueries.existsCheck(\n memberRead(this.adapter, name),\n model\n ? this.#and(\n ...fields.map((field, index) =>\n this.#eq(\n this.column(model, field, alias),\n this.#at(name, `k${index}`)\n )\n )\n )\n : this.#true()\n )\n );\n const slot = new SqlSlot(use);\n body.slots.push({\n slot,\n inline,\n use,\n test: {\n alias,\n columns: model\n ? fields.map((field) => this.columnName(model, field))\n : [],\n holds: quantified.holds,\n },\n within,\n });\n return { body, slot };\n }\n /**\n * A recursive filter's walk from `parent`, `inline`, inside a statement\n * sharing its bodies: a slot the statement settles to `inline` where the\n * walk is lowered once, and else to a test of its REACHING SET, `EXISTS\n * (SELECT 1 FROM <set> WHERE set.k = parent.key)`. Equal walks (the same\n * text once aliases are renumbered, and the same values: the same edge,\n * range, related domain and `stated`) share one set ({@link sharedKey}).\n * The set holds the key of every stored row from which the walk reaches a\n * row `stated` holds of ({@link reachingSet}), so it answers for `parent`\n * where `parent` reads the stored row ({@link rows}) or the walk's first\n * hop reads only its key: elsewhere (a produced row's new value, a masked\n * window) the walk keeps its place, as it does on a dialect bounding\n * recursion iterations, whose walks stay as they were. `selective`: its\n * author stated the rows it reaches back from few, which may lift it from\n * the start ({@link sharingBodies}).\n */\n #sharedWalk(\n edge: Membership,\n parent: string,\n child: string,\n closure: Closure,\n stated: readonly Sql[],\n walk: Sql,\n quantified: Quantified,\n selective: boolean\n ): Sql {\n const shared = this.#shared;\n const model = edge.source;\n const keys = this.schema.keys(model);\n const inline = quantified.of(walk);\n if (\n shared === undefined ||\n this.adapter.capabilities.boundsRecursionIterations === true ||\n !(\n this.#rows.get(parent) === model ||\n hopFieldsOf(edge).every((field) => keys.includes(field))\n )\n )\n return inline;\n // A set a positive test reads may be bounded, one a negative test reads\n // never is ({@link setBound}): the two, and two bounds, are not one set.\n const bound = quantified.holds ? this.#setBound(model, child) : [];\n const bounded = bound.length > 0;\n const key = bounded\n ? `${sharedKey(walk)} bounded ${sharedKey(bound[0]!)}`\n : sharedKey(walk);\n const { body, slot } = this.#placed(\n shared,\n key,\n (name) => ({\n query: this.#reachingSet(name, edge, child, closure, stated, bounded),\n correlated: false,\n recursive: true,\n }),\n inline,\n quantified,\n parent,\n model,\n keys,\n this.#enclosing.at(-1)\n );\n if (selective) body.selective = true;\n return slot;\n }\n /**\n * The two terms of a walk's reaching set `name`: the key of every stored\n * row from which 1..`depth` hops of `edge` (every hop when `depth` is\n * false), each into a row of the related domain, reach a row `stated`\n * (lowered on `child`) holds of, and, where `self` holds, of every row it\n * holds of. Read backwards from those rows: the anchor states them (at\n * depth 0 where `self` holds; their predecessors at depth 1, each through a\n * row of the domain, where it does not), and the recursive member adds the\n * predecessors of each row of the set the domain takes, one depth further,\n * below `depth`. A hidden row stops the walk below it, as forwards: it\n * passes nothing on. `UNION` on the key (and depth, when bounded) ends\n * every cycle and states a diamond's row once per depth.\n */\n #reachingSet(\n name: string,\n edge: Membership,\n child: string,\n closure: Closure,\n stated: readonly Sql[],\n bounded: boolean\n ): Sql {\n const a = this.adapter;\n const model = edge.source;\n const { depth, self } = closure;\n const keys = this.schema.keys(model);\n const keyColumns = keys.map((_, index) => `k${index}`);\n const depthColumn = \"depth\";\n const at = (value: Sql) =>\n depth === false ? [] : [this.#named(value, depthColumn)];\n const domain = this.domainOf(edge.target, \"related\");\n const related = (alias: string) =>\n domain ? [this.lowerSelector(domain, alias)!] : [];\n const bound = bounded\n ? (alias: string) => this.#setBound(model, alias)\n : undefined;\n let anchor: Sql;\n if (self)\n anchor = assembleAdapterSelect(a, {\n columns: listed([\n ...this.#aliased(keyColumns, this.#rowKey(model, child)),\n ...at(this.#cast(this.value(0), \"integer\")),\n ]),\n from: this.#attached(model, child),\n where: this.#all([...stated, ...(bound?.(child) ?? [])]),\n });\n else {\n const first = this.#predecessor(\n edge,\n (field) => this.column(model, field, child),\n bound\n );\n anchor = assembleAdapterSelect(a, {\n columns: listed([\n ...this.#aliased(keyColumns, first.key),\n ...at(this.#cast(this.value(1), \"integer\")),\n ]),\n from: sql.join([this.#attached(model, child), ...first.joins], \" \"),\n where: this.#all([...related(child), ...stated]),\n });\n }\n const set = this.alias();\n const carried = (column: string) => this.#at(set, column);\n // Every key the set states is a stored row's where its predecessors are\n // joined rows: with no domain to read, the row is not joined again.\n const reached =\n domain !== undefined || !this.#joinsPredecessor(edge)\n ? this.alias()\n : undefined;\n const before = this.#predecessor(\n edge,\n (field) =>\n reached === undefined\n ? carried(keyColumns[keys.indexOf(field)]!)\n : this.column(model, field, reached),\n bound\n );\n const recursive = assembleAdapterSelect(a, {\n columns: listed([\n ...this.#aliased(keyColumns, before.key),\n ...at(a.expressions.add(carried(depthColumn), this.value(1))),\n ]),\n from: sql.join(\n [\n this.#named(this.#escaped(name), set),\n ...(reached === undefined\n ? []\n : [\n this.#inner(\n this.table(model, reached),\n this.#and(\n this.sameRow(model, reached, keyColumns.map(carried)),\n ...related(reached)\n )\n ),\n ]),\n ...before.joins,\n ],\n \" \"\n ),\n where: this.#all(\n depth === false\n ? []\n : [a.operators.lt(carried(depthColumn), this.value(depth))]\n ),\n });\n return a.setOperations.union(anchor, recursive);\n }\n /**\n * Whether the rows one hop of `edge` leads from are joined to be named\n * ({@link predecessor}), reading nothing of the row they lead into but its\n * key: then each names a stored row.\n */\n #joinsPredecessor(edge: Membership): boolean {\n const keys = this.schema.keys(edge.source);\n if (edge.kind !== \"reference\")\n return (\n !this.#covers(\n edge.sourceSide.members.map((member) => member.referencedField),\n keys\n ) &&\n edge.targetSide.members.every((member) =>\n keys.includes(member.referencedField)\n )\n );\n return (\n edge.discriminator === undefined &&\n !this.#covers(\n edge.pairs.map((pair) => pair.source),\n keys\n ) &&\n edge.pairs.every((pair) => keys.includes(pair.target))\n );\n }\n /** Whether `fields` are exactly `keys`, in any order. */\n #covers(fields: readonly string[], keys: readonly string[]): boolean {\n return (\n fields.length === keys.length &&\n keys.every((field) => fields.includes(field))\n );\n }\n /**\n * The rows one hop of `edge` leads into `into` from, as their keys and the\n * joins that read them: the hop's own columns where they are the key (a\n * reference's target columns, a junction's source columns), and else the\n * row joined by its membership. A key read from a column names a row that\n * may not exist; it then passes nothing on and matches no row.\n */\n #predecessor(\n edge: Membership,\n into: CarriedRow,\n bound?: (row: string) => readonly Sql[]\n ): { readonly key: readonly Sql[]; readonly joins: readonly Sql[] } {\n const model = edge.source;\n const keys = this.schema.keys(model);\n if (edge.kind === \"reference\") {\n const sources = edge.pairs.map((pair) => pair.source);\n // A bounded walk joins the row its bound reads.\n if (\n bound === undefined &&\n edge.discriminator === undefined &&\n this.#covers(sources, keys)\n )\n return {\n key: keys.map((field) =>\n into(edge.pairs[sources.indexOf(field)]!.target)\n ),\n joins: [],\n };\n const row = this.alias();\n const arm = edge.discriminator;\n return {\n key: this.#rowKey(model, row),\n joins: [\n this.#inner(\n this.table(model, row),\n this.#and(\n ...(arm === undefined\n ? []\n : [\n this.#eq(\n arm.side === \"source\"\n ? this.column(model, arm.field, row)\n : into(arm.field),\n this.value(arm.value)\n ),\n ]),\n ...edge.pairs.map((pair) =>\n this.#eq(\n this.column(model, pair.source, row),\n into(pair.target)\n )\n ),\n ...(bound?.(row) ?? [])\n )\n ),\n ],\n };\n }\n const link = this.alias();\n const linked = this.#inner(\n this.#tableNamed(edge.table, link),\n this.#side(edge, \"targetSide\", link, into, true)\n );\n const referenced = edge.sourceSide.members.map(\n (member) => member.referencedField\n );\n if (bound === undefined && this.#covers(referenced, keys))\n return {\n key: keys.map((field) =>\n this.#at(\n link,\n edge.sourceSide.members[referenced.indexOf(field)]!.junctionField\n )\n ),\n joins: [linked],\n };\n const row = this.alias();\n return {\n key: this.#rowKey(model, row),\n joins: [\n linked,\n this.#inner(\n this.table(model, row),\n this.#and(\n ...this.junctionSideConditions(edge.sourceSide, link, row),\n ...(bound?.(row) ?? [])\n )\n ),\n ],\n };\n }\n /**\n * A relation filter's junction joined to its target, `junction INNER JOIN\n * target ON target.key = junction.target`, and the junction's correlation to\n * the parent row, `junction.source = parent.key`, for the EXISTS's own\n * `WHERE`: the same rows as the target's membership in a correlated junction\n * subquery ({@link membershipWhere}), a pair joined on equal keys being a\n * pair the membership's `IN` admits (a NULL key matches in neither). SQLite\n * walks it from the junction's key per parent row instead of rebuilding the\n * membership's set for every target row (200k posts, 300k links: a\n * tagged-post count 1,240 → 61 ms, an `every` count 2,910 → 65 ms).\n * PostgreSQL hashes it into a semijoin: the same count on PostgreSQL 18,\n * 479 → 7 ms, but 0.2 ms more planning, so a bounded read keeps the\n * membership.\n */\n #junctionJoin(\n edge: Extract<Membership, { kind: \"junction\" }>,\n child: string,\n parent: string,\n link = this.alias()\n ): { readonly from: Sql; readonly correlation: Sql } {\n return {\n from: sql`${this.#tableNamed(edge.table, link)} ${this.#inner(\n this.table(edge.target, child),\n this.#and(\n ...edge.targetSide.members.map((field) =>\n this.#eq(\n this.column(edge.target, field.referencedField, child),\n this.#at(link, field.junctionField)\n )\n )\n )\n )}`,\n correlation: this.#side(edge, \"sourceSide\", link, parent, true),\n };\n }\n /**\n * `EXISTS (SELECT 1 FROM target WHERE related AND stated)`, correlated to\n * nothing: inside a statement sharing its bodies, every occurrence with the\n * same text and values settles to one `WITH` member holding at most one row,\n * and each reads it as `EXISTS (SELECT 1 FROM <member>)`.\n */\n #lowerExists(\n predicate: Extract<PreparedPredicate, { kind: \"exists\" }>,\n alias: string\n ): Sql {\n const a = this.adapter;\n const { model } = predicate;\n const child = this.#rowAlias(model);\n const frame = { alias: child, escaped: false };\n this.#frames.push(frame);\n let stated: Sql[];\n try {\n stated = predicate.predicate\n ? [this.#lowerPredicate(predicate.predicate, child)]\n : [];\n } finally {\n this.#frames.pop();\n }\n const domain = this.domainOf(model, \"related\");\n const lowered = domain && this.lowerSelector(domain, child);\n const related =\n lowered && predicate.predicate && readsRelation(predicate.predicate)\n ? a.subqueries.isolated(lowered)\n : lowered;\n const conditions = related ? [related, ...stated] : stated;\n const where =\n conditions.length === 0 ? this.#true() : this.#and(...conditions);\n const inline = a.subqueries.existsCheck(\n this.#attached(model, child),\n where\n );\n const shared = this.#shared;\n // Correlated to a row above it: written where it is.\n if (shared === undefined || frame.escaped) return a.filters.some(inline);\n const query = assembleAdapterSelect(a, {\n columns: sql`1`,\n from: this.#attached(model, child),\n where,\n limit: this.value(1),\n });\n return this.#placed(\n shared,\n sharedKey(query),\n () => ({ query, correlated: false }),\n a.filters.some(inline),\n { of: (read) => a.filters.some(read), holds: true },\n alias\n ).slot;\n }\n /**\n * Does the PARENT row claim a membership in this arm?\n *\n * A variant ROW carrier stores the claim on the parent itself — a\n * discriminator naming the arm and a reference to the row — so \"linked\" is\n * answerable without reading the target at all. That is what separates an\n * EMPTY slot (no claim) from an ORPHANED one (a claim whose row is gone),\n * which the target subquery alone reports identically as `null`.\n *\n * `undefined` where the claim is not the parent's to make: the membership is\n * then the child's or a junction's, and this owner says nothing about it.\n */\n #parentClaimsArm(edge: Membership, parentAlias: string): Sql | undefined {\n if (\n edge.kind !== \"reference\" ||\n edge.owner !== \"source\" ||\n edge.discriminator?.side !== \"source\"\n )\n return undefined;\n return this.#and(\n this.#eq(\n this.column(edge.source, edge.discriminator.field, parentAlias),\n this.value(edge.discriminator.value)\n ),\n ...edge.pairs.map((pair) =>\n this.#isNotNull(this.column(edge.source, pair.source, parentAlias))\n )\n );\n }\n /** The one join of a relation to its parent, under the {@link related} domain. */\n correlation(\n edge: Membership,\n parent: string | CarriedRow,\n target: string,\n scoped = true\n ): Sql {\n const member = this.#membershipWhere(edge, target, parent);\n return scoped ? this.#related(edge, target, member) : member;\n }\n /**\n * The one place the related domain enters a relation read, conjoined to the\n * `member` condition that reached `target`: outside any quantifier's\n * negation, so `every`, `none` and a negated count read \"every VISIBLE\n * member\", and on every edge, so a to-one projection, `is`/`isNot`, a to-one\n * order term and an upward recursion read a hidden target as an absent one.\n */\n #related(edge: Membership, target: string, member: Sql): Sql {\n const domain = this.domainOf(edge.target, \"related\");\n if (domain === undefined) return member;\n return this.#and(member, this.lowerSelector(domain, target)!);\n }\n /** `held` locks the links a junction's membership is read from, where the provider can. */\n memberWhere(\n edge: Membership,\n parent: Input,\n alias: string,\n held = false\n ): Sql {\n return this.#membershipWhere(edge, alias, parent, held);\n }\n #membershipWhere(\n edge: Membership,\n target: string,\n source: string | Input | CarriedRow,\n held = false\n ): Sql {\n if (edge.kind === \"reference\") {\n // The source row's own column, where the source is a row and not values.\n const given = typeof source === \"object\" ? source : undefined;\n const read =\n typeof source === \"string\"\n ? (field: string) => this.column(edge.source, field, source)\n : typeof source === \"function\"\n ? source\n : undefined;\n return this.#and(\n ...(edge.discriminator\n ? [\n this.#eq(\n edge.discriminator.side === \"source\"\n ? read\n ? read(edge.discriminator.field)\n : this.value(given![edge.discriminator.field])\n : this.column(edge.target, edge.discriminator.field, target),\n this.value(edge.discriminator.value)\n ),\n ]\n : []),\n ...edge.pairs.map((pair) =>\n read\n ? this.#eq(\n read(pair.source),\n this.column(edge.target, pair.target, target)\n )\n : this.#eq(\n this.column(edge.target, pair.target, target),\n this.fieldValue(edge.target, pair.target, given![pair.source])\n )\n )\n );\n }\n const junction = this.alias();\n // Membership first: the index on the source side finds the small target\n // worklist before the provider visits those target identities.\n return this.adapter.operators.in(\n rowValue(\n edge.targetSide.members.map((field) =>\n this.column(edge.target, field.referencedField, target)\n )\n ),\n this.#scalar({\n columns: listed(\n edge.targetSide.members.map((field) =>\n this.#at(junction, field.junctionField)\n )\n ),\n from: this.#tableNamed(edge.table, junction),\n where: this.#side(edge, \"sourceSide\", junction, source, true),\n forUpdate: held,\n })\n );\n }\n #lowerOrder(terms: readonly OrderTerm[]): Sql | undefined {\n if (terms.length === 0) return undefined;\n const a = this.adapter;\n return listed(\n terms.map((term) => {\n const direction = term.descending ? \"desc\" : \"asc\";\n if (!term.nullable || term.nulls === undefined)\n return a.orderBy[direction](term.expression);\n return term.nulls === \"first\"\n ? a.orderBy.nullsFirst(term.expression, direction)\n : a.orderBy.nullsLast(term.expression, direction);\n })\n );\n }\n /**\n * One order owner. A scalar key, a to-one relation path, a collection\n * `_count`, a distance and a grouped aggregate are all sort keys; only a\n * direct scalar key can also serve as a cursor's total order.\n */\n #orderTerms(\n model: AnyModel,\n input: Arguments[\"orderBy\"],\n alias: string,\n cursored = false,\n joins?: OrderJoins,\n approximate = false\n ): OrderTerm[] {\n if (!input) return [];\n const terms: OrderTerm[] = [];\n for (const order of entries(input)) {\n for (const field of Object.keys(order)) {\n const direction = order[field];\n if (direction !== undefined)\n terms.push(\n this.#orderTerm(\n model,\n field,\n direction,\n alias,\n cursored,\n joins,\n approximate && terms.length === 0\n )\n );\n }\n }\n return terms;\n }\n #orderTerm(\n model: AnyModel,\n field: string,\n direction: unknown,\n alias: string,\n cursored = false,\n joins?: OrderJoins,\n servable = false\n ): OrderTerm {\n if (model[\"~\"].state.relations[field])\n return this.#relationOrderTerm(\n model,\n field,\n direction as Input,\n alias,\n joins\n );\n const physical = this.physical(model, field);\n const state = physical.state;\n const column = this.#operand(model, field, alias);\n const nullable = physical.nullable || this.#gatedHere(model, field);\n if (direction !== \"asc\" && direction !== \"desc\") {\n const specification = direction as Input;\n if (specification._distance !== undefined) {\n // A cursor's eligibility is a fact about the REQUEST; a provider's\n // vector support is a fact about the PROVIDER. Classifying the order\n // first is what keeps `page`'s sentence the answer on a driver that\n // happens not to support vectors — `distanceExpression` consults the\n // capability while it BUILDS, so it would otherwise pre-empt it.\n if (cursored) unsupported(CURSOR_ORDER_REFUSAL);\n const distance = specification._distance as Input;\n const point = state.type === \"point\";\n return this.#sortKey(\n this.#distanceExpression(\n column,\n state,\n field,\n distance,\n \"orderBy\",\n servable\n ),\n distance.sort === \"desc\",\n point ? \"last\" : undefined,\n point,\n undefined,\n point ? true : undefined\n );\n }\n return this.#sortKey(\n column,\n specification.sort === \"desc\",\n specification.nulls as \"first\" | \"last\" | undefined,\n nullable,\n field\n );\n }\n return this.#sortKey(\n column,\n direction === \"desc\",\n undefined,\n nullable,\n field\n );\n }\n /**\n * A to-one path is one value of the related row; a collection orders by\n * `_count`. Where the page takes joins and the edge reaches at most one row\n * by a key ({@link #joinsOnce}), the row is LEFT JOINed once per path, its\n * related domain in the ON clause so a parent whose row is hidden or absent\n * stays with NULL, and a deeper hop chains off the joined alias. Otherwise\n * it is a correlated scalar subquery, whose inner hops stay inside it.\n */\n #relationOrderTerm(\n model: AnyModel,\n field: string,\n specification: Input,\n alias: string,\n joins?: OrderJoins\n ): OrderTerm {\n const a = this.adapter;\n // A collection orders by `_count`, and that count is the projection's own\n // count owner — including a variant carrier, which has no single membership.\n const { edges: counted } = this.countedMemberships(model, field);\n if (\n counted.length > 1 ||\n counted[0]!.many ||\n specification._count !== undefined\n )\n return this.#sortKey(\n this.#correlatedCount(counted, undefined, alias),\n specification._count === \"desc\",\n undefined,\n false\n );\n const edge = counted[0]!;\n const [nested] = Object.entries(specification);\n if (joins && this.#joinsOnce(edge)) {\n const path = `${alias}.${field}`;\n let joined = joins.aliases.get(path);\n if (joined === undefined) {\n joined = this.alias();\n joins.aliases.set(path, joined);\n joins.joins.push(\n a.joins.left(\n this.table(edge.target, joined),\n this.correlation(edge, alias, joined)\n )\n );\n }\n const term = this.#orderTerm(\n edge.target,\n nested![0],\n nested![1],\n joined,\n false,\n joins\n );\n return this.#sortKey(term.expression, term.descending, term.nulls, true);\n }\n const childAlias = this.alias();\n const correlation = this.correlation(edge, alias, childAlias);\n const inner = this.#orderTerm(\n edge.target,\n nested![0],\n nested![1],\n childAlias\n );\n const value = assembleAdapterSelect(a, {\n columns: inner.expression,\n from: this.table(edge.target, childAlias),\n where: correlation,\n limit: this.value(1),\n });\n return this.#sortKey(\n a.subqueries.scalar(value),\n inner.descending,\n inner.nulls,\n true\n );\n }\n /**\n * A join keeps one row per parent only where the resolver proves the\n * correlated key unique on the target: the parent holds the key, which\n * references a target key, or the target holds it under a unique key. A\n * junction or a variant carrier has no such proof.\n */\n #joinsOnce(edge: Membership): boolean {\n const resolved = edge.scope.edge;\n return (\n edge.kind === \"reference\" &&\n resolved.kind === \"foreignKey\" &&\n (edge.owner === \"source\" || resolved.unique)\n );\n }\n #sortKey(\n expression: Sql,\n descending: boolean,\n nulls: \"first\" | \"last\" | undefined,\n nullable: boolean,\n field?: string,\n expressionNulls?: true\n ): OrderTerm {\n return {\n expression,\n descending,\n nulls: nulls ?? (descending ? \"first\" : \"last\"),\n expressionNulls,\n nullable,\n field,\n };\n }\n #reverseOrder(terms: readonly OrderTerm[]): OrderTerm[] {\n return terms.map((term) => ({\n ...term,\n descending: !term.descending,\n nulls:\n term.nulls === undefined || term.expressionNulls\n ? term.nulls\n : term.nulls === \"first\"\n ? (\"last\" as const)\n : (\"first\" as const),\n }));\n }\n /**\n * One page owner: the root read and every nested node use it, so a nested\n * window is the ordinary page operator inside its parent's correlation.\n */\n #page(\n model: AnyModel,\n args: Pick<\n Partial<Arguments>,\n \"orderBy\" | \"take\" | \"skip\" | \"cursor\" | \"distinct\"\n >,\n alias: string,\n purpose?: RowPurpose,\n joined = true,\n approximate = false\n ): {\n readonly orderBy?: Sql;\n /** The to-one order joins the page's FROM takes after its own. */\n readonly joins?: Sql[];\n readonly limit?: Sql;\n readonly offset?: Sql;\n readonly cursor?: Sql;\n readonly distinct?: Sql;\n readonly distinctOrderBy?: Sql;\n readonly distinctOrder?: QueryParts[\"distinctOrder\"];\n } {\n const backward = args.take !== undefined && args.take < 0;\n const cursored = args.cursor !== undefined;\n const joins: OrderJoins | undefined = joined\n ? { aliases: new Map(), joins: [] }\n : undefined;\n const requested = this.#orderTerms(\n model,\n args.orderBy,\n alias,\n cursored,\n joins,\n approximate\n );\n const total = this.#totalOrder(model, requested, args.cursor, alias);\n // The single raise point for every other non-scalar key: a relation term\n // builds with `field: undefined` and is classified here.\n if (cursored && requested.some((term) => term.field === undefined))\n unsupported(CURSOR_ORDER_REFUSAL);\n const terms = total ?? requested;\n const presented = backward ? this.#reverseOrder(terms) : terms;\n const distinct = (args.distinct?.length ?? 0) > 0;\n return {\n orderBy: this.#lowerOrder(presented),\n joins: joins?.joins.length ? joins.joins : undefined,\n distinctOrderBy:\n backward && distinct ? this.#lowerOrder(terms) : undefined,\n distinctOrder:\n distinct && terms.length > 0\n ? this.#distinctOrder(terms, presented)\n : undefined,\n limit:\n args.take === undefined ? undefined : this.value(Math.abs(args.take)),\n offset: args.skip === undefined ? undefined : this.value(args.skip),\n cursor:\n args.cursor === undefined\n ? undefined\n : this.#cursorCondition(\n model,\n backward ? this.#reverseOrder(total!) : total!,\n args.cursor,\n purpose\n ),\n distinct: args.distinct?.length\n ? listed(\n args.distinct.map((field) => this.#operand(model, field, alias))\n )\n : undefined,\n };\n }\n /**\n * A distinct page's order read from its own rows: each term projected once\n * as `_ordN` beside the window that picks each group's representative, and\n * the presented order over those columns. The emulation's outer `ORDER BY`\n * reads them, so one window (`_rn`) does the work a second one ranking every\n * row (`_ord`) did: one sort fewer (200k rows: PGlite 273 → 127 ms, SQLite\n * 253 → 121 ms). `presented` is `terms`, reversed where the page is.\n */\n #distinctOrder(\n terms: readonly OrderTerm[],\n presented: readonly OrderTerm[]\n ): QueryParts[\"distinctOrder\"] {\n return {\n keys: listed(\n terms.map((term, index) => this.#named(term.expression, `_ord${index}`))\n ),\n orderBy: this.#lowerOrder(\n presented.map((term, index) => ({\n ...term,\n expression: this.#escaped(`_ord${index}`),\n }))\n )!,\n };\n }\n /** A windowed read needs a deterministic total order, not just the caller's. */\n #totalOrder(\n model: AnyModel,\n requested: readonly OrderTerm[],\n cursor: Input | undefined,\n alias: string\n ): OrderTerm[] {\n if (getModelKeyCatalog(model).rowKey === undefined && cursor === undefined)\n return [...requested];\n const terms = this.#completeOrder(\n model,\n requested,\n alias,\n cursor ? Object.keys(this.#identityEntries(model, cursor)) : []\n );\n // Fill the owned completed array directly. Nullable keys need an explicit\n // placement, and cursor comparisons consume the complete term descriptors;\n // ordinary non-nullable ordering does not use a null placement.\n for (let index = 0; index < terms.length; index++) {\n const term = terms[index]!;\n if (term.nulls === undefined && (term.nullable || cursor !== undefined)) {\n terms[index] = {\n ...term,\n nulls: term.descending ? \"first\" : \"last\",\n };\n }\n }\n return terms;\n }\n /**\n * The caller's terms completed by the model's identity: the ONE complete-key\n * tie-break. A windowed page and a recursive sibling order both need a\n * deterministic order and both read it here, so equal sort keys break the\n * same way wherever one parent's rows are ordered — a second spelling (the\n * row key in constraint order) ordered the same tied siblings differently\n * under recursion than under the ordinary window.\n */\n #completeOrder(\n model: AnyModel,\n requested: readonly OrderTerm[],\n alias: string,\n cursorFields: readonly string[] = []\n ): OrderTerm[] {\n const terms = [...requested];\n const ordered = new Set<string>();\n for (const term of terms) {\n if (term.field !== undefined) ordered.add(term.field);\n }\n const identity = this.keyOrder(model);\n const completion =\n cursorFields.length === 0 ? identity : [...identity, ...cursorFields];\n for (const field of completion) {\n if (ordered.has(field)) continue;\n ordered.add(field);\n const physical = this.physical(model, field);\n terms.push(\n this.#sortKey(\n this.#operand(model, field, alias),\n false,\n \"last\",\n physical.nullable || this.#gatedHere(model, field),\n field\n )\n );\n }\n return terms;\n }\n /** A strict unique selector's exact field values, compound keys expanded. */\n #identityEntries(model: AnyModel, input: Input): Input {\n const identity: Input = {};\n for (const [name, value] of Object.entries(input)) {\n const key = findAddressableKey(model, name);\n if (key?.name)\n for (const field of key.fields)\n identity[field] = (value as Input)[field];\n else identity[name] = value;\n }\n return identity;\n }\n /**\n * One null-aware lexicographic window against the cursor row. Where every\n * key is NOT NULL and shares a direction the same meaning is spelled as a\n * row-value comparison, which a planner can turn into a range seek; any\n * other window with a NOT NULL leading key states that key's bound beside\n * it, so the seek survives mixed directions and nullable later keys.\n */\n #cursorCondition(\n model: AnyModel,\n order: readonly OrderTerm[],\n cursor: Input,\n purpose: RowPurpose | undefined\n ): Sql {\n const a = this.adapter;\n const identity = this.#identityEntries(model, cursor);\n const sourceAlias = this.alias();\n // The anchor is a candidate like any other: a hidden one is a missing one.\n const scope = purpose && this.domainOf(model, purpose);\n const where = this.#and(\n ...(scope ? [this.lowerSelector(scope, sourceAlias)!] : []),\n ...Object.entries(identity).map(([field, value]) => {\n if (value === null)\n engineFault(\n `Cursor field '${field}' cannot be null. Cursor must point to a specific record.`\n );\n return this.#eq(\n this.#operand(model, field, sourceAlias),\n this.fieldValue(model, field, value)\n );\n })\n );\n const descending = order[0]!.descending;\n const sargable = order.every(\n (term) => !term.nullable && term.descending === descending\n );\n const cursorRow = (columns: Sql[]) =>\n assembleAdapterSelect(a, {\n columns: listed(columns),\n from: this.table(model, sourceAlias),\n where,\n limit: this.value(1),\n });\n const keyColumns = order.map((term) =>\n this.#operand(model, term.field!, sourceAlias)\n );\n if (sargable)\n return (descending ? a.operators.lte : a.operators.gte)(\n rowValue(order.map((term) => term.expression)),\n a.subqueries.scalar(cursorRow(keyColumns))\n );\n const cursorAlias = this.alias();\n const carrier = (index: number) => `${CURSOR_CARRIER_PREFIX}${index}`;\n const derived = cursorRow(\n keyColumns.map((column, index) => this.#named(column, carrier(index)))\n );\n const comparisons = order.map((term, index) => ({\n row: term.expression,\n cursor: this.#at(cursorAlias, carrier(index)),\n term,\n }));\n const equalities: Sql[] = [];\n const afterTerms: Sql[] = [];\n for (const { row, cursor: key, term } of comparisons) {\n const compare = term.descending ? a.operators.lt : a.operators.gt;\n const strict = this.#and(this.#isNotNull(row), compare(row, key));\n afterTerms.push(\n this.#and(\n ...equalities,\n term.nulls === \"first\"\n ? this.#or(\n this.#and(this.#isNull(key), this.#isNotNull(row)),\n this.#and(this.#isNotNull(key), strict)\n )\n : this.#and(\n this.#isNotNull(key),\n this.#or(this.#isNull(row), strict)\n )\n )\n );\n equalities.push(\n this.#or(\n this.#and(this.#isNull(row), this.#isNull(key)),\n this.#and(\n this.#isNotNull(row),\n this.#isNotNull(key),\n this.#eq(row, key)\n )\n )\n );\n }\n afterTerms.push(this.#and(...equalities));\n const window = a.operators.exists(\n assembleAdapterSelect(a, {\n columns: this.#true(),\n from: this.#aside(derived, cursorAlias),\n where: this.#or(...afterTerms),\n })\n );\n // Every row after the anchor sorts at or past its NOT NULL leading key:\n // that bound, implied by the window, is the range a planner can seek.\n const [lead] = order;\n if (lead!.nullable) return window;\n return this.#and(\n (lead!.descending ? a.operators.lte : a.operators.gte)(\n lead!.expression,\n a.subqueries.scalar(cursorRow([keyColumns[0]!]))\n ),\n window\n );\n }\n /**\n * One `SELECT`, its statement sharing its relation bodies where the adapter\n * does ({@link sharingBodies}): a row a write locates or captures\n * (`FOR UPDATE`, after the `WITH`) or re-reads, and a premise's probe, as\n * a read's. Inside a statement already sharing (a read's), it joins that\n * statement's scope.\n */\n override select(\n model: AnyModel,\n args: Partial<Arguments>,\n membership?: { edge: Membership; parent: Input },\n controls: SqlSelectControls = {}\n ): Query {\n return this.#sharingQuery(() =>\n this.#select(model, args, membership, controls)\n );\n }\n /** The query `build` makes, its statement sharing its bodies where the adapter does. */\n #sharingQuery(build: () => Query): Query {\n return this.#shares(\n build,\n (query) => query.sql,\n (query, statement) => ({ ...query, sql: statement })\n );\n }\n #select(\n model: AnyModel,\n args: Partial<Arguments>,\n membership: { edge: Membership; parent: Input } | undefined,\n controls: SqlSelectControls\n ): Query {\n const alias = this.rootAlias();\n if (controls.source === undefined) this.#rows.set(alias, model);\n // The shipped owner sequence, and the reason it is stated here: when one\n // call violates two contracts at once, the refusal the caller sees is the\n // one whose owner runs first. `buildFind` (`operations/find-common.ts`)\n // pages before it selects and selects before it builds the `where`, so the\n // cursor refusal outranks a projection refusal and both outrank a `where`\n // refusal. Nothing below reads the projection or the selector, so this is\n // an ORDER, not a dependency (`g4/unit01-review-followup-3.md` finding K).\n // A locking read keeps its order terms correlated: PostgreSQL refuses\n // FOR UPDATE on the nullable side of an outer join.\n const page = this.#page(\n model,\n args,\n alias,\n controls.purpose,\n !controls.forUpdate,\n controls.approximate\n );\n const prepared = controls.projection ?? this.prepareProjection(model, args);\n const projection = this.lowerProjection(\n prepared,\n alias,\n controls.purpose !== undefined\n );\n const given =\n controls.selector ??\n (args.where === undefined\n ? undefined\n : this.prepareSelector(model, args.where, false, false));\n const selector =\n controls.purpose === undefined\n ? given\n : this.#within(model, given, controls.purpose);\n const filter = selector ? this.lowerSelector(selector, alias) : undefined;\n const unless =\n controls.unless &&\n this.adapter.operators.not(\n this.adapter.expressions.coalesce(\n this.#opposite(() => this.lowerSelector(controls.unless!, alias)) ??\n this.#true(),\n this.#false()\n )\n );\n const columns = listed(projection);\n const where = this.#selectWhere(\n model,\n alias,\n membership,\n filter,\n unless,\n page.cursor,\n controls\n );\n const shared = this.#shared;\n if (shared && controls.source === undefined && !controls.forUpdate)\n shared.root ??= { alias, scope: sql`${columns} ${where ?? sql.empty}` };\n return {\n sql: assembleAdapterSelect(this.adapter, {\n columns,\n from:\n controls.source === undefined\n ? // FOR UPDATE refuses the nullable side of an outer join.\n controls.forUpdate\n ? this.table(model, alias)\n : this.#attached(model, alias)\n : this.#named(this.#escaped(controls.source), alias),\n joins: page.joins,\n where,\n orderBy: page.orderBy,\n limit: page.limit,\n offset: page.offset,\n forUpdate: controls.forUpdate,\n ...(page.distinct\n ? {\n distinct: page.distinct,\n distinctOrderBy: page.distinctOrderBy,\n distinctOrder: page.distinctOrder,\n distinctColumnAliases: prepared.fields.map((field) => field.name),\n }\n : {}),\n }),\n shape: prepared.shape,\n };\n }\n /** {@link select}'s conjunction, in its order; `undefined` for none. */\n #selectWhere(\n model: AnyModel,\n alias: string,\n membership: { edge: Membership; parent: Input } | undefined,\n filter: Sql | undefined,\n unless: Sql | undefined,\n cursor: Sql | undefined,\n controls: Pick<SqlSelectControls, \"condition\" | \"identity\">\n ): Sql | undefined {\n const where: Sql[] = [];\n if (membership)\n where.push(this.memberWhere(membership.edge, membership.parent, alias));\n if (filter) where.push(filter);\n if (unless) where.push(unless);\n if (cursor) where.push(cursor);\n if (controls.identity)\n where.push(this.lowerIdentity(model, controls.identity, alias));\n const { condition } = controls;\n if (condition)\n where.push(\n typeof condition === \"function\" ? condition(alias) : condition\n );\n return where.length === 0 ? undefined : this.#and(...where);\n }\n /**\n * Every read verb is one cardinality and shape decision over the same\n * select, projection and decoder owners, its statement sharing its\n * relation bodies where the adapter does ({@link sharingBodies}).\n */\n override read(\n model: AnyModel,\n operation: ReadOperation,\n args: Arguments\n ): Read {\n this.#bounded =\n operation === \"findUnique\" ||\n operation === \"findFirst\" ||\n operation === \"exist\" ||\n (operation !== \"groupBy\" && args.take !== undefined);\n return this.#shares(\n () => this.#read(model, operation, args),\n (read) => read.query.sql,\n (read, statement) => ({\n ...read,\n query: { ...read.query, sql: statement },\n })\n );\n }\n #read(model: AnyModel, operation: ReadOperation, args: Arguments): Read {\n switch (operation) {\n case \"findUnique\": {\n // The one read verb whose `where` is a unique selector: its addressable\n // entries name the row through the constraint, exactly as the shipped\n // `buildWhereUnique` compiles them, while `findFirst`/`findMany` read\n // the same object as a filter.\n const query = this.select(model, args, undefined, {\n selector:\n args.where === undefined\n ? undefined\n : this.prepareSelector(model, args.where, true, false),\n purpose: \"root\",\n });\n return {\n query,\n single: true,\n value: query.shape,\n result: firstRow,\n };\n }\n case \"findFirst\": {\n // A negative take selects from the end of the window: the signed unit\n // limit flips the total order and still returns one row.\n const take = args.take === undefined ? 1 : Math.sign(args.take);\n const query = this.select(\n model,\n { ...this.#ordered(model, args), take },\n undefined,\n this.#candidates(operation, args)\n );\n return {\n query,\n single: true,\n value: query.shape,\n result: firstRow,\n };\n }\n case \"findMany\": {\n const backward = args.take !== undefined && args.take < 0;\n const query = this.select(\n model,\n this.#ordered(model, args),\n undefined,\n this.#candidates(operation, args)\n );\n return {\n query,\n single: false,\n value: rowSet(query),\n result: backward ? reversedRows : rowIdentity,\n };\n }\n default:\n return this.#readAggregate(model, operation, args);\n }\n }\n /** A row read's root candidates, its order servable where it may be. */\n #candidates(operation: ReadOperation, args: Arguments): SqlSelectControls {\n return approximateOrder(operation, args)\n ? { ...ROOT_CANDIDATES, approximate: true }\n : ROOT_CANDIDATES;\n }\n /** Counting and aggregate reads, out of line from the row reads above. */\n #readAggregate(\n model: AnyModel,\n operation: Exclude<ReadOperation, \"findUnique\" | \"findFirst\" | \"findMany\">,\n args: Arguments\n ): Read {\n switch (operation) {\n case \"exist\": {\n // Existence is order-blind and `exist` admits only `where`: the\n // filtered table itself, with no total order to sort or scan by.\n const a = this.adapter;\n const alias = this.rootAlias();\n const rows = assembleAdapterSelect(a, {\n columns: a.literals.true(),\n from: this.table(model, alias),\n where: this.lowerWhere(model, args.where, alias),\n });\n const query: Query = {\n sql: a.clauses.select(\n a.identifiers.aliased(a.operators.exists(rows), \"_count\")\n ),\n shape: { kind: \"object\", fields: { _count: BOOLEAN_LEAF } },\n expectedRows: {\n count: 1,\n missing: new QueryEngineError(\n \"Provider omitted the required existence result row.\"\n ),\n },\n };\n return {\n query,\n single: false,\n value: BOOLEAN_LEAF,\n result: (rows) => rows[0]?._count ?? false,\n };\n }\n case \"count\": {\n const selected = args.select ? (args.select as Input) : undefined;\n const outputs: { name: string; field?: string }[] = selected\n ? [\n ...(selected._all ? [{ name: \"_all\" }] : []),\n ...Object.keys(selected)\n .filter((field) => field !== \"_all\" && selected[field])\n .map((field) => ({ name: field, field })),\n ]\n : [{ name: \"_count\" }];\n const fields = outputs.flatMap(({ field }) =>\n field === undefined ? [] : [field]\n );\n const query = this.aggregated(\n model,\n args,\n fields,\n (alias) =>\n outputs.map(({ name, field }): [string, Sql] => [\n name,\n this.adapter.aggregates.count(\n field === undefined\n ? undefined\n : this.#operand(model, field, alias)\n ),\n ]),\n () => ({\n kind: \"object\",\n fields: Object.fromEntries(\n outputs.map(({ name }) => [name, COUNT_LEAF])\n ),\n })\n );\n query.expectedRows = {\n count: 1,\n missing: new QueryEngineError(\n \"Provider omitted the required aggregate result row.\"\n ),\n };\n return {\n query,\n // `count` publishes a number and `exist` a boolean: one VALUE, not one\n // row, so neither is `single` — the row they decode is scaffolding.\n single: selected !== undefined,\n value: selected ? query.shape : COUNT_LEAF,\n result: (rows) =>\n selected ? (rows[0] ?? {}) : ((rows[0]?._count as number) ?? 0),\n };\n }\n case \"aggregate\": {\n const prepared = this.#prepareAggregates(model, args);\n const query = this.aggregated(\n model,\n args,\n prepared.fields,\n (alias) => prepared.columns(alias),\n () => ({ kind: \"object\", fields: prepared.fields_ })\n );\n return {\n query,\n single: true,\n value: query.shape,\n result: aggregateRow,\n };\n }\n case \"groupBy\": {\n const query = this.grouped(model, args);\n return {\n query,\n single: false,\n value: rowSet(query),\n result: rowIdentity,\n };\n }\n default:\n return unreachable(operation, \"read operation\");\n }\n }\n /**\n * One aggregate statement. Aggregates are order-blind, so only a page\n * (`take`, `skip`, `cursor`) needs a window: the same filter, total order,\n * cursor and page, aggregated outside it. An unpaged aggregate reads the\n * filtered table itself, which leaves the provider its count fast path and\n * covering indexes instead of a key-ordered scan or a sort.\n */\n private aggregated(\n model: AnyModel,\n args: Arguments,\n fields: readonly string[],\n columns: (alias: string) => [string, Sql][],\n shape: (alias: string) => Extract<Shape, { kind: \"object\" }>\n ): Query {\n const inner = this.rootAlias();\n // The default order only decides which rows a page holds.\n const page = this.#page(model, this.#ordered(model, args), inner, \"root\");\n const filter = this.lowerWhere(model, args.where, inner);\n const aggregate = (alias: string, from: Sql, where?: Sql): Query => ({\n sql: assembleAdapterSelect(this.adapter, {\n columns: listed(\n columns(alias).map(([name, expression]) =>\n this.#named(expression, name)\n )\n ),\n from,\n where,\n }),\n shape: shape(alias),\n });\n // A read-gated model aggregates a masked window (K5): its gate lowered\n // once per row, not once per aggregate over the field.\n if (\n !((page.limit ?? page.offset ?? page.cursor) || this.#gates(model)?.size)\n )\n return aggregate(inner, this.table(model, inner), filter);\n const window = assembleAdapterSelect(this.adapter, {\n columns: fields.length\n ? listed(\n [...new Set(fields)].map((field) =>\n this.#named(\n this.#operand(model, field, inner),\n this.columnName(model, field)\n )\n )\n )\n : this.#named(this.value(1), \"0viborm_row\"),\n from: this.table(model, inner),\n joins: page.joins,\n where: this.#and(\n ...(filter ? [filter] : []),\n ...(page.cursor ? [page.cursor] : [])\n ),\n orderBy: page.orderBy,\n limit: page.limit,\n offset: page.offset,\n });\n const outer = this.alias();\n // The window masks its read-gated columns: the aggregate reads them as\n // they are.\n return this.#overMasked(() => aggregate(outer, this.#aside(window, outer)));\n }\n /** The admitted aggregate selections, as columns and as decoder leaves. */\n #prepareAggregates(\n model: AnyModel,\n args: Arguments\n ): {\n readonly fields: string[];\n readonly fields_: Record<string, Shape | Leaf>;\n columns(alias: string): [string, Sql][];\n } {\n const a = this.adapter;\n const fields: string[] = [];\n const shape: Record<string, Shape | Leaf> = {};\n const builders: ((alias: string) => [string, Sql])[] = [];\n for (const name of AGGREGATES) {\n const selection = args[name];\n if (!selection) continue;\n if (name === \"_count\" && selection === true) {\n shape._count = COUNT_LEAF;\n builders.push(() => [\"_count\", a.aggregates.count()]);\n continue;\n }\n const selected = Object.entries(selection as Input).filter(\n ([, include]) => include\n );\n if (selected.length === 0) continue;\n const leaves: Record<string, Leaf> = {};\n for (const [field] of selected) {\n if (field !== \"_all\") fields.push(field);\n leaves[field] = this.#aggregateLeaf(model, name, field);\n }\n shape[name] = { kind: \"object\", fields: leaves };\n builders.push((alias) => [\n name,\n a.json.objectFromColumns(\n selected.map(([field]) => {\n const leaf = leaves[field]!;\n const scalar =\n field === \"_all\" ? undefined : this.scalar(model, field);\n const split = this.splitSum(leaf);\n if (split)\n return [\n field,\n a.json.array(\n split\n .sql(this.#preparedColumn(scalar!, alias))\n .parts.map((part) => this.#carriedValue(leaf, part))\n ),\n ];\n return [\n field,\n this.#carriedValue(\n leaf,\n this.#aggregateExpression(name, scalar, alias)\n ),\n ];\n })\n ),\n ]);\n }\n return {\n fields,\n fields_: shape,\n columns: (alias) => builders.map((build) => build(alias)),\n };\n }\n /** One aggregate leaf classification: projection, `having` and `orderBy`. */\n #aggregateLeaf(model: AnyModel, aggregate: Aggregate, field: string): Leaf {\n if (aggregate === \"_count\") return COUNT_LEAF;\n const leaf = this.scalarShape(model, field);\n if (aggregate === \"_avg\" && leaf.type !== \"decimal\")\n return { kind: \"scalar\", type: \"number\", nullable: true };\n // Admission admits `_sum` only on the summable types, every one widened.\n return {\n ...leaf,\n nullable: true,\n widened: aggregate === \"_sum\" ? true : undefined,\n };\n }\n /**\n * A split `_sum` as `having` compares it and a grouped `orderBy` sorts it:\n * the sum the projection publishes, not the provider's own `SUM`, which\n * can raise or answer another number (engine-10).\n */\n #splitSumSql(scalar: PreparedScalar, column: Sql): SplitSumSql | undefined {\n return this.splitSum(\n this.#aggregateLeaf(scalar.model, \"_sum\", scalar.field)\n )?.sql(column);\n }\n #aggregateExpression(\n aggregate: Aggregate,\n scalar: PreparedScalar | undefined,\n alias?: string\n ): Sql {\n const a = this.adapter;\n const column = scalar ? this.#preparedColumn(scalar, alias) : undefined;\n const state = scalar?.physical.state;\n // biome-ignore lint/style/useDefaultSwitchClause: the Aggregate union is exhaustive; a default would be dead code.\n switch (aggregate) {\n case \"_count\":\n return a.aggregates.count(column);\n case \"_sum\":\n return (\n this.#splitSumSql(scalar!, column!)?.value ??\n a.aggregates.sum(column!)\n );\n case \"_min\":\n case \"_max\": {\n // Admission admits `_all` under `_count` alone, so these name a\n // column. A compact identifier is aggregated in the spelling it\n // TRAVELS in (`identifier.ts`); every other column is aggregated as\n // stored.\n const operand = aggregatedIdentifier(\n a,\n this.scalarShape(scalar!.model, scalar!.field).id,\n column!\n );\n return aggregate === \"_min\"\n ? a.aggregates.min(operand, state?.type === \"boolean\")\n : a.aggregates.max(operand, state?.type === \"boolean\");\n }\n case \"_avg\":\n return state?.type === \"decimal\" && state.decimal\n ? a.aggregates.decimalAvg(column!, state.decimal)\n : a.aggregates.avg(column!);\n }\n }\n override selectSeries(\n prepared: PreparedProjection,\n identities: Input[],\n operation: \"createMany\" | \"updateMany\" = \"createMany\"\n ): Query {\n return this.#sharingQuery(() =>\n this.#selectSeries(prepared, identities, operation)\n );\n }\n #selectSeries(\n prepared: PreparedProjection,\n identities: Input[],\n operation: \"createMany\" | \"updateMany\"\n ): Query {\n const model = prepared.model;\n const alias = this.rootAlias();\n const projection = this.lowerProjection(prepared, alias);\n const predicates = identities.map((identity) =>\n this.lowerIdentity(model, identity, alias)\n );\n return {\n sql: assembleAdapterSelect(this.adapter, {\n columns: listed(projection),\n from: this.table(model, alias),\n where: balancedOr(predicates, (arms) => this.#or(...arms)),\n // The place of each row is a number the statement states: one it binds is text to a provider that is told no type, and ten sorts before two.\n orderBy: this.adapter.expressions.caseWhen(\n predicates.map((when, index) => ({\n when,\n then: sql.raw(String(index)),\n })),\n sql.raw(String(identities.length))\n ),\n }),\n shape: prepared.shape,\n expectedRows: this.seriesExpectation(model, identities.length, operation),\n };\n }\n /**\n * `visible`: every row this projection reads is one the domain takes, so\n * each layer's `read` holds there and its evidence tests the rest alone; a\n * row captured by identity (a write's) is not (K5).\n */\n lowerProjection(\n projection: PreparedProjection,\n alias?: string,\n visible = false\n ): Sql[] {\n const columns: Sql[] = [];\n for (const field of projection.fields) {\n columns.push(\n this.#named(\n this.#lowerProjectionField(projection, field, alias, visible),\n field.name\n )\n );\n }\n return columns;\n }\n /** Count, distance and polymorphic members, out of line from plain columns. */\n #lowerSpecialProjectionField(\n projection: PreparedProjection,\n field: Exclude<\n PreparedProjectionField,\n { kind: \"scalar\" | \"sentinel\" | \"relation\" | \"evidence\" | \"gate\" }\n >,\n alias?: string\n ): Sql {\n const a = this.adapter;\n let expression: Sql;\n if (field.kind === \"counts\") {\n expression = a.json.objectFromColumns(\n field.counts.map((count) => [\n count.relation,\n this.#correlatedCount(\n count.edges,\n count.selector,\n alias ?? \"\",\n count.negated\n ),\n ])\n );\n } else if (field.kind === \"distance\") {\n expression = this.#distanceExpression(\n this.column(projection.model, field.field, alias),\n this.physical(projection.model, field.field).scalar[\"~\"].state,\n field.field,\n field.specification,\n \"select\"\n );\n } else {\n // The slot's own document: one entry per SELECTED arm, and — for a\n // junction-carried slot — one integrity entry naming every CONFIGURED\n // member (D-26). The integrity entry is a sibling of the arms, so it is\n // answered whatever `only` selected, including nothing at all.\n const integrity: [string, Sql][] =\n field.memberships.length === 0\n ? []\n : [\n [\n POLYMORPHIC_COLLECTION_ORPHANS_KEY,\n this.#document(\n a.json.objectFromColumns(\n field.memberships.map((member) => [\n member.variant,\n this.#orphanedMemberships(member.edge, alias ?? \"\"),\n ])\n )\n ),\n ],\n ];\n const resolved = this.schema.index\n .get(projection.model)!\n .get(field.name)!;\n if (resolved.edge.kind === \"variantRowCarrier\") {\n const edge = resolved.edge;\n const type = this.column(\n projection.model,\n edge.storage.typeColumn.name,\n alias\n );\n const id = this.column(\n projection.model,\n edge.storage.idColumn.name,\n alias\n );\n const empty = slotMayBeEmpty(resolved)\n ? this.#and(this.#isNull(type), this.#isNull(id))\n : this.#false();\n const valid = this.#and(\n this.#isNotNull(id),\n this.#or(\n ...edge.members.map((member) =>\n this.#eq(type, this.value(member.entry.storedValue))\n )\n )\n );\n const invalid = this.#when(\n this.#or(empty, valid),\n this.value(0),\n this.value(1)\n );\n integrity.push([\n POLYMORPHIC_COLLECTION_ORPHANS_KEY,\n this.#document(a.json.objectFromColumns([[\"$storage\", invalid]])),\n ]);\n }\n expression = this.#object([\n ...field.arms.map((arm) => {\n const row = this.#lowerRelationProjection(arm, alias ?? \"\");\n const claim = field.many\n ? undefined\n : this.#parentClaimsArm(arm.edge, alias ?? \"\");\n // A claimed arm always carries a DOCUMENT: the empty one says\n // \"linked, and the row is gone\", which the decoder refuses from\n // the arm's own selected keys (Arnaud's D-19 — no private carrier\n // column). An unclaimed arm stays null, which is an empty slot.\n return [\n arm.variant,\n this.#document(\n claim\n ? this.#when(\n claim,\n a.expressions.coalesce(\n row,\n this.#missingArm(arm.edge, alias ?? \"\")\n ),\n this.#null()\n )\n : row\n ),\n ] as [string, Sql];\n }),\n ...integrity,\n ]);\n }\n return expression;\n }\n #lowerProjectionField(\n projection: PreparedProjection,\n field: PreparedProjectionField,\n alias?: string,\n visible = false\n ): Sql {\n let expression: Sql;\n if (field.kind === \"scalar\") {\n expression = this.projectedColumn(projection.model, field.name, alias);\n } else if (field.kind === \"sentinel\") {\n expression = this.#cast(this.#literal(1), \"integer\");\n } else if (field.kind === \"evidence\" || field.kind === \"gate\") {\n expression = this.domain!.project!.lower(\n this,\n projection.model,\n field,\n alias,\n visible\n );\n } else if (field.kind === \"relation\") {\n expression = this.#duplicateMembershipGuard(\n field.edge,\n alias ?? \"\",\n field.recurrence\n ? this.#lowerRecursiveRelationProjection(\n field,\n field.recurrence,\n alias ?? \"\"\n )\n : this.#lowerRelationProjection(field, alias ?? \"\")\n );\n } else {\n expression = this.#lowerSpecialProjectionField(projection, field, alias);\n }\n return expression;\n }\n /** A condition as a value: true or false, never NULL; `undefined` holds. */\n truth(condition: Sql | undefined): Sql {\n return condition === undefined\n ? this.#true()\n : this.#when(condition, this.#true(), this.#false());\n }\n /**\n * What a claimed arm whose row did not come back carries: the empty\n * document, \"the row is gone\", which the decoder refuses. Under a related\n * domain the row may exist and be hidden, which reads as an empty slot, so\n * the empty document then also needs the row to be physically absent: a\n * membership test with no domain, evaluated only for a claim that read no\n * row. Without a domain, the bytes are the ones a plain client emits.\n */\n #missingArm(edge: Membership, parentAlias: string): Sql {\n if (this.domainOf(edge.target, \"related\") === undefined)\n return this.#object([]);\n const target = this.alias();\n return this.#when(\n this.adapter.operators.exists(\n this.adapter.subqueries.existsCheck(\n this.table(edge.target, target),\n this.correlation(edge, parentAlias, target, false)\n )\n ),\n this.#null(),\n this.#object([])\n );\n }\n /**\n * How many of this member's memberships name a row that is gone.\n *\n * A polymorphic member table carries no real foreign key to its target on\n * every provider, so a disabled constraint or a raw write can leave the\n * membership behind; reading the slot must then FAIL, not report the row as\n * absent — existence and membership are execution semantics (rule 4), and a\n * silent absence is a wrong answer.\n *\n * The probe is a SIBLING scalar subquery of the arm's row window: it carries\n * no user filter, no cursor and no window, so it is evaluated outside — and\n * therefore ahead of — the arm's own `WHERE` and `LIMIT`, exactly as the\n * shipped `guardJunctionIntegrity` did\n * (`builders/include-many-to-many.ts` at `ff5e77ca`). It is emitted for every\n * configured member, so `only` cannot hide one (Arnaud's D-26).\n */\n /**\n * A SINGULAR polymorphic inverse holding more than one membership is\n * malformed provider state, even where a missing unique constraint allowed\n * it — and the row window cannot say so: a target filter that leaves one\n * visible row, or the `LIMIT 1` itself, hides the second member.\n *\n * So the count is a SIBLING scalar subquery over the member table, ahead of\n * the row subquery's `WHERE` and its `LIMIT`, and the refusal is carried in\n * the VALUE, not raised in SQL — no provider has a portable `RAISE`. The\n * branch emits a JSON ARRAY where the leaf owes one row object, which is the\n * shape the decoder already refuses by name and which no projection of a\n * model row can produce (the shipped `guardJunctionIntegrity`,\n * `builders/include-many-to-many.ts` at `ff5e77ca`).\n *\n * Only a polymorphic member table: an ordinary pair table's inverse is\n * enforced by its own unique constraint and its bytes are unchanged.\n */\n #duplicateMembershipGuard(\n edge: Membership,\n parentAlias: string,\n projected: Sql\n ): Sql {\n if (\n edge.kind !== \"junction\" ||\n edge.many ||\n edge.scope.edge.kind !== \"variantJunctionCarrier\"\n )\n return projected;\n const members = this.#links(edge, this.alias(), parentAlias);\n return this.#when(\n this.adapter.operators.gt(members, this.value(1)),\n this.adapter.json.emptyArray(),\n projected\n );\n }\n #orphanedMemberships(\n edge: Extract<Membership, { kind: \"junction\" }>,\n parentAlias: string\n ): Sql {\n const junction = this.alias();\n const target = this.alias();\n return this.#links(\n edge,\n junction,\n parentAlias,\n this.adapter.filters.none(\n this.adapter.subqueries.existsCheck(\n this.table(edge.target, target),\n this.#side(edge, \"targetSide\", junction, target)\n )\n )\n );\n }\n /** What a link of `edge`, read as `link`, holds where its `side` reaches the row `endpoint` names: among the links a row scope lets be read, where `bound`. */\n #side(\n edge: Extract<Membership, { kind: \"junction\" }>,\n side: \"sourceSide\" | \"targetSide\",\n link: string,\n endpoint: string | Input | CarriedRow,\n bound = false\n ): Sql {\n return this.#and(\n ...this.junctionSideConditions(edge[side], link, endpoint),\n ...(bound ? this.#linkBound(edge, link) : [])\n );\n }\n /** How many links of `edge`, read as `junction`, the row `parentAlias` reads holds, among those `more` holds of. */\n #links(\n edge: Extract<Membership, { kind: \"junction\" }>,\n junction: string,\n parentAlias: string,\n ...more: Sql[]\n ): Sql {\n return this.#scalar({\n columns: this.adapter.aggregates.count(),\n from: this.#tableNamed(edge.table, junction),\n where: this.#and(\n ...this.junctionSideConditions(edge.sourceSide, junction, parentAlias),\n ...more\n ),\n });\n }\n /**\n * One slot's correlated count, shared by the `_count` projection and `_count`\n * ordering. A variant carrier's arms are summed, because the slot's population\n * is their union ({@link countedMemberships}).\n */\n #correlatedCount(\n edges: readonly Membership[],\n selector: Pick<PreparedSelector, \"model\" | \"predicate\"> | undefined,\n parentAlias: string,\n negated = false\n ): Sql {\n const a = this.adapter;\n // An ungrouped, unlimited COUNT(*) answers exactly one row, so the\n // scalar subquery is never NULL and needs no COALESCE.\n const counted = edges.map((edge) => {\n const childAlias = this.alias();\n const filter = selector\n ? negated\n ? this.#opposite(() => this.lowerSelector(selector, childAlias)!)\n : this.lowerSelector(selector, childAlias)!\n : undefined;\n return this.#scalar({\n columns: a.aggregates.count(),\n from: this.table(edge.target, childAlias),\n where: this.#and(\n this.correlation(edge, parentAlias, childAlias),\n ...(filter ? [negated ? a.operators.not(filter) : filter] : [])\n ),\n });\n });\n return counted.reduce((total, arm) => a.expressions.add(total, arm));\n }\n #lowerRelationProjection(\n relation: PreparedRelationProjection,\n alias: string\n ): Sql {\n const a = this.adapter;\n const {\n edge,\n arguments: nested,\n projection,\n linkRow,\n linkWhere,\n } = relation;\n const childAlias = this.#rowAlias(edge.target);\n const child = this.lowerProjection(projection, childAlias, true);\n const childFields = Object.keys(projection.shape.fields);\n // A nested node is the ordinary page operator inside the parent's\n // correlation scope; `take: -n` reverses the window exactly as at the root.\n const window = this.#page(edge.target, nested, childAlias, \"related\");\n const source = this.#memberSource(edge, alias, childAlias);\n const lowered = linkWhere && this.lowerSelector(linkWhere, source.link);\n // The link row is the one this page's own join reads the target through,\n // flat here and an object below: a JSON column in a page would have no\n // equality for `DISTINCT`, and a key holds at most one row per target. No\n // member's name holds a `$` (F001), so none of the page's columns is this.\n const linkColumn = (index: number) => `$through_${index}`;\n if (linkRow)\n for (const [index, field] of linkRow.fields.entries())\n child.push(\n this.#named(\n this.projectedColumn(linkRow.model, field, source.link),\n linkColumn(index)\n )\n );\n const page = assembleAdapterSelect(a, {\n columns: listed(child),\n from: source.from,\n joins:\n source.joins && window.joins\n ? [...source.joins, ...window.joins]\n : (source.joins ?? window.joins),\n where: this.#and(\n source.where,\n ...(nested.selector\n ? [this.lowerSelector(nested.selector, childAlias)!]\n : []),\n ...(lowered ? [lowered] : []),\n ...(window.cursor ? [window.cursor] : [])\n ),\n orderBy: window.orderBy,\n // The aggregate below reads this page IN ORDER, so an ordered page\n // states its bound. MySQL merges an UNLIMITED derived table into the\n // query that reads it and the merge takes the ORDER BY with it, and the\n // rows then arrive in storage order — measured, both answers from the\n // same aggregate over the same page. What the bound buys is the MERGE\n // RULE, which is the documented fact: MySQL does not merge a derived\n // table that states a LIMIT. That the same page then answered in the\n // requested order is the measurement beside it, not a documented\n // property of materialising. The caller's window is that bound wherever\n // it asked for one — including the offset-only window, whose bare\n // OFFSET already needs the same spelling — and where it asked for none,\n // the dialect's own \"no limit\" value is. A dialect that needs no bound\n // to keep a derived order declares none (PostgreSQL) and emits nothing.\n limit: edge.many\n ? (window.limit ?? (window.orderBy ? a.noLimitValue : undefined))\n : this.value(1),\n offset: window.offset,\n ...(window.distinct\n ? {\n distinct: window.distinct,\n distinctOrderBy: window.distinctOrderBy,\n distinctOrder: window.distinctOrder,\n distinctColumnAliases: [\n ...projection.fields.map((field) => field.name),\n ...(linkRow ? linkRow.fields.map((_, i) => linkColumn(i)) : []),\n ],\n }\n : {}),\n });\n const pageAlias = this.alias();\n const members = childFields.map((field): [string, Sql] => [\n field,\n this.#carriedValue(\n projection.shape.fields[field]!,\n this.#at(pageAlias, field)\n ),\n ]);\n for (const gate of projection.shape.gates ?? NO_GATES)\n members.push([gate, this.#at(pageAlias, gate)]);\n if (linkRow)\n members.push([\n \"$through\",\n this.#object(\n linkRow.fields.map((field, index): [string, Sql] => [\n field,\n this.#carriedValue(\n linkRow.shape.fields[field]!,\n this.#at(pageAlias, linkColumn(index))\n ),\n ])\n ),\n ]);\n const object = this.#object(members);\n const expression = this.#scalar({\n columns: edge.many ? a.json.agg(object) : object,\n from: this.#aside(page, pageAlias),\n });\n return expression;\n }\n\n /**\n * One physical row identity, encoded through the existing JSON carrier rule:\n * the one encoder of the carrier's root, node keys and edge endpoints, whose\n * texts the decoder matches.\n */\n #recursiveIdentity(model: AnyModel, key: readonly Sql[]): Sql {\n return this.adapter.json.array(\n this.schema.keys(model).map((field, index) => {\n // The carried key is the RAW column, so a byte identifier takes its\n // transport spelling here, as every projected column already has.\n const leaf = this.scalarShape(model, field);\n return this.#carriedValue(\n leaf,\n transportedIdentifier(\n this.adapter,\n leaf.id,\n key[index]!,\n leaf.nullable\n )\n );\n })\n );\n }\n\n /** One row's complete key, addressed through `alias`. */\n #rowKey(model: AnyModel, alias: string): Sql[] {\n return this.schema\n .keys(model)\n .map((field) => this.column(model, field, alias));\n }\n /** The complete-key join of one model alias to carried key columns. */\n sameRow(model: AnyModel, alias: string, carried: readonly Sql[]): Sql {\n return this.#and(\n ...this.#rowKey(model, alias).map((column, index) =>\n this.#eq(column, carried[index]!)\n )\n );\n }\n\n /**\n * One hop of a walk, from `current` into `next`, under the {@link related}\n * domain. A reference hop is the ordinary {@link correlation}; a junction\n * hop joins the junction table, and its target as a relation page does\n * ({@link memberSource}): the membership's `IN (SELECT … WHERE link.source =\n * current.key)` correlates to `next`'s sibling, which PostgreSQL cannot turn\n * into a semi-join, so it would run once per target row at every hop.\n */\n #step(\n edge: Membership,\n current: string | CarriedRow,\n next: string,\n scoped = true\n ): Sql {\n if (edge.kind !== \"junction\")\n return this.#inner(\n this.table(edge.target, next),\n this.correlation(edge, current, next, scoped)\n );\n const link = this.alias();\n return sql`${this.#inner(\n this.#tableNamed(edge.table, link),\n this.#side(edge, \"sourceSide\", link, current, true)\n )} ${this.#junctionTarget(edge, link, next)}`;\n }\n /**\n * Where one parent's relation page reads its rows. A junction membership\n * reads FROM the junction, joined to its target by key, so the junction's\n * source-side index drives the page whatever the target's statistics say:\n * behind {@link correlation}'s `IN (SELECT …)` SQLite, once ANALYZE has\n * run, scans a target smaller than its fixed guess of the list's length,\n * once per parent (parity-04). PostgreSQL and MySQL already plan that\n * membership as this join. The junction's primary key spans both sides\n * and each side references a complete row key, so every member is read\n * once, as the membership reads it.\n */\n #memberSource(\n edge: Membership,\n parent: string,\n child: string\n ): { from: Sql; joins?: Sql[]; where: Sql; link?: string } {\n if (edge.kind !== \"junction\")\n return {\n from: this.#attached(edge.target, child),\n where: this.correlation(edge, parent, child),\n };\n const link = this.alias();\n return {\n link,\n from: this.#tableNamed(edge.table, link),\n joins: [this.#junctionTarget(edge, link, child)],\n where: this.#side(edge, \"sourceSide\", link, parent),\n };\n }\n /** A junction's target joined from `link`, under the {@link related} domain. */\n #junctionTarget(\n edge: Extract<Membership, { kind: \"junction\" }>,\n link: string,\n next: string\n ): Sql {\n return this.#inner(\n this.table(edge.target, next),\n this.#related(edge, next, this.#side(edge, \"targetSide\", link, next))\n );\n }\n\n /**\n * The ONE walk of a recursive membership: a recursive CTE of the rows\n * reached from `parentAlias` by 1..`depth` hops of `edge` (every hop when\n * `depth` is false). Each hop reads the related domain (the anchor's\n * {@link correlation}, then {@link step}), so a hidden row stops the walk\n * below it, and `UNION` on\n * the carried key (and depth, when bounded) ends every cycle and visits a\n * diamond's row once per depth. Two readers:\n * - the recursive projection asks for `edges`: each reached row carries the\n * row it was reached from, and the per-hop `selector` narrows every hop;\n * - a recursive filter reads the reached SET, plus the start row itself at\n * depth 0 when `self` holds. The start row joins the FIRST hop in the\n * anchor, so the recursive member stays the projection's and needs no\n * depth guard: a start-only anchor would spend one of MySQL's\n * `cte_max_recursion_depth` iterations and fail `{ depth: 1000 }`.\n * The two are ONE derived-table term, so the CTE keeps exactly two\n * top-level terms: PlanetScale's Neki cannot resolve the CTE from the\n * recursive member of a third (42P01).\n * Where the driver bounds a statement's relations (`sharesRelationBodies`),\n * each reached row carries the columns its next hop reads ({@link hopFields}), so the\n * recursive member joins no row again to leave it; the start row carries\n * them as the statement reads it, so where the hop reads more than its key\n * and it is not the stored row ({@link rows}: a produced row's new value, a\n * masked window), the walk joins every row again, and so also leaves the\n * start row by its stored columns, as it always has. The first hop stays in\n * the anchor even where the start row alone would do: PostgreSQL plans the\n * recursive member as a hash join over a scan of the table, and an anchor\n * hop is an index probe (10× the acceptance fixture: an `accessGrant` read\n * 124 → 785 ms with the start row alone).\n */\n walk(\n edge: Membership,\n parentAlias: string,\n start:\n | Closure\n | {\n readonly depth: number | false;\n readonly edges: true;\n readonly selector?: Pick<PreparedSelector, \"model\" | \"predicate\">;\n },\n scoped = true\n ) {\n const a = this.adapter;\n const model = edge.target;\n const keys = this.schema.keys(model);\n const scope = this.alias();\n const cteName = `__${scope}_recursive`;\n const { depth } = start;\n const edges = \"edges\" in start;\n const parentColumns = edges\n ? keys.map((_, index) => `__${scope}_parent_${index}`)\n : [];\n const childColumns = keys.map((_, index) => `__${scope}_child_${index}`);\n const depthColumn = `__${scope}_depth`;\n const selector = edges ? start.selector : undefined;\n const hop = (value: Sql) =>\n depth === false ? [] : [this.#named(value, depthColumn)];\n const reached = (alias: string) =>\n selector ? [this.lowerSelector(selector, alias)!] : [];\n\n const self = !edges && start.self;\n const carries =\n this.sharesBodies &&\n (!self ||\n this.#rows.get(parentAlias) === model ||\n hopFieldsOf(edge).every((field) => keys.includes(field)));\n const hopFields = carries\n ? hopFieldsOf(edge).filter((field) => !keys.includes(field))\n : [];\n const hopColumns = hopFields.map((_, index) => `__${scope}_hop_${index}`);\n const row = (alias: string) => [\n ...this.#aliased(childColumns, this.#rowKey(model, alias)),\n ...this.#aliased(\n hopColumns,\n hopFields.map((field) => this.column(model, field, alias))\n ),\n ];\n const anchorChild = this.alias();\n const firstHop = assembleAdapterSelect(a, {\n columns: listed([\n ...this.#aliased(parentColumns, this.#rowKey(model, parentAlias)),\n ...row(anchorChild),\n ...hop(this.#cast(this.value(1), \"integer\")),\n ]),\n from: this.table(model, anchorChild),\n where: this.#and(\n this.correlation(edge, parentAlias, anchorChild, scoped),\n ...reached(anchorChild)\n ),\n });\n const seed = self ? this.alias() : undefined;\n const anchor = seed\n ? assembleAdapterSelect(a, {\n columns: listed(\n [\n ...childColumns,\n ...hopColumns,\n ...(depth === false ? [] : [depthColumn]),\n ].map((column) => this.#at(seed, column))\n ),\n from: this.#aside(\n a.setOperations.union(\n a.clauses.select(\n listed([\n ...row(parentAlias),\n ...hop(this.#cast(this.value(0), \"integer\")),\n ])\n ),\n firstHop\n ),\n seed\n ),\n })\n : firstHop;\n\n const walk = this.alias();\n const carried = (column: string) => this.#at(walk, column);\n let current: string | CarriedRow;\n let reread: Sql | undefined;\n if (carries)\n current = (field) =>\n carried(\n keys.includes(field)\n ? childColumns[keys.indexOf(field)]!\n : hopColumns[hopFields.indexOf(field)]!\n );\n else {\n current = this.alias();\n reread = this.#inner(\n this.table(model, current),\n this.sameRow(model, current, childColumns.map(carried))\n );\n }\n const next = this.alias();\n const recursive = assembleAdapterSelect(a, {\n columns: listed([\n ...this.#aliased(parentColumns, childColumns.map(carried)),\n ...row(next),\n ...hop(a.expressions.add(carried(depthColumn), this.value(1))),\n ]),\n from: sql.join(\n [\n this.#named(this.#escaped(cteName), walk),\n ...(reread ? [reread] : []),\n this.#step(edge, current, next, scoped),\n ],\n \" \"\n ),\n where: this.#all([\n ...(depth === false\n ? []\n : [a.operators.lt(carried(depthColumn), this.value(depth))]),\n ...reached(next),\n ]),\n });\n return {\n cte: a.cte.recursive(cteName, anchor, recursive, \"distinct\"),\n cteName,\n scope,\n /** The walk's own alias, free again for a reader outside the CTE. */\n walk,\n parentColumns,\n childColumns,\n depthColumn,\n };\n }\n /** `then` where `when` holds, `otherwise` where it does not. */\n #when(when: Sql, then: Sql, otherwise: Sql): Sql {\n return this.adapter.expressions.caseWhen([{ when, then }], otherwise);\n }\n /** One value, read by a subquery. */\n #scalar(parts: Parameters<typeof assembleAdapterSelect>[1]): Sql {\n return this.adapter.subqueries.scalar(\n assembleAdapterSelect(this.adapter, parts)\n );\n }\n /** Every one of `conditions`: none states no WHERE rather than `WHERE TRUE`. */\n #all(conditions: readonly Sql[]): Sql | undefined {\n return conditions.length === 0 ? undefined : this.#and(...conditions);\n }\n /** Each expression aliased as the column of the same index. */\n #aliased(names: readonly string[], expressions: readonly Sql[]): Sql[] {\n return names.map((name, index) => this.#named(expressions[index]!, name));\n }\n\n /**\n * A recursive relation remains one ordinary projected field. The recursive\n * CTE carries only edge facts; one node table supplies each projected row,\n * and the decoder owns path occurrences and cutoff omission. The recursive\n * member expands every reached row below the bound with the same\n * correlation and filter and prunes nothing (the cycle policy belongs to the\n * decoder), because `decodeRecursiveCarrier` refuses a carrier in which a\n * parent lacks its children at any level it is reached below the cutoff.\n */\n #lowerRecursiveRelationProjection(\n relation: PreparedRelationProjection,\n recurrence: NormalizedRecurrence,\n parentAlias: string\n ): Sql {\n const a = this.adapter;\n const model = relation.edge.target;\n const {\n cte,\n cteName,\n scope,\n walk,\n parentColumns,\n childColumns,\n depthColumn,\n } = this.walk(relation.edge, parentAlias, {\n depth: recurrence.depth,\n edges: true,\n selector: relation.arguments.selector,\n });\n const walkColumn = (name: string) => this.#at(walk, name);\n\n const ids = this.alias();\n const idColumns = childColumns.map((_, index) => `__${scope}_id_${index}`);\n const distinctIds = assembleAdapterSelect(a, {\n distinct: listed(childColumns.map(walkColumn)),\n distinctColumnAliases: idColumns,\n columns: listed(this.#aliased(idColumns, childColumns.map(walkColumn))),\n from: this.#named(this.#escaped(cteName), walk),\n });\n const node = this.#rowAlias(model);\n const nodeDocument = this.#object(\n relation.projection.fields.map((field) => [\n field.name,\n this.#carriedValue(\n // A gate is the one member the decoded shape does not list.\n relation.projection.shape.fields[field.name] ?? BOOLEAN_LEAF,\n this.#lowerProjectionField(relation.projection, field, node, true)\n ),\n ])\n );\n const nodeCarrier = this.#object([\n [\n RECURSIVE_CARRIER.key,\n this.#recursiveIdentity(model, this.#rowKey(model, node)),\n ],\n [RECURSIVE_CARRIER.row, nodeDocument],\n ]);\n const idTable = this.#aside(distinctIds, ids);\n const table = this.table(model, node);\n const sameNode = this.sameRow(\n model,\n node,\n idColumns.map((name) => this.#at(ids, name))\n );\n // Where the caller states each walk reaches few rows (`fewRows`), each is\n // read by its key (`capabilities.readsNodesByKey`): joined, PostgreSQL,\n // guessing ten rows a level, hashed the whole table once per outer row.\n const byKey =\n recurrence.fewRows &&\n a.capabilities.readsNodesByKey &&\n this.#document(\n this.#scalar({\n columns: nodeCarrier,\n from: table,\n where: sameNode,\n })\n );\n const nodes = this.#scalar({\n columns: a.json.agg(byKey || nodeCarrier),\n from: byKey ? idTable : sql`${idTable} ${this.#inner(table, sameNode)}`,\n });\n\n const edgeWalk = this.alias();\n const edgeChild = this.alias();\n const edgeColumn = (name: string) => this.#at(edgeWalk, name);\n const edgeCarrierName = `__${scope}_edge`;\n const edgePairs: [string, Sql][] = [\n [\n RECURSIVE_CARRIER.parent,\n this.#recursiveIdentity(model, parentColumns.map(edgeColumn)),\n ],\n [\n RECURSIVE_CARRIER.child,\n this.#recursiveIdentity(model, childColumns.map(edgeColumn)),\n ],\n ];\n if (recurrence.depth !== false)\n edgePairs.push([RECURSIVE_CARRIER.depth, edgeColumn(depthColumn)]);\n const edgeCarrier = this.#object(edgePairs);\n // Each parent's siblings in the caller's order, ties broken by the order\n // owner's one complete key — the ordinary window's tie-break, not another.\n // An order of key columns alone is read from the walk's own: joined\n // only to be ordered, PostgreSQL, guessing ten rows a level, hashed the\n // whole table once per outer row. Any other term is read from the joined\n // child, after the walk's `UNION`, never carried through it.\n const keys = this.schema.keys(model);\n const order = this.#completeOrder(\n model,\n this.#orderTerms(model, relation.arguments.orderBy, edgeChild),\n edgeChild\n );\n const keyed = order.map((term) =>\n term.field === undefined || this.#gatedHere(model, term.field)\n ? -1\n : keys.indexOf(term.field)\n );\n const joins = keyed.includes(-1);\n const siblingOrder = this.#lowerOrder(\n joins\n ? order\n : order.map((term, index) => ({\n ...term,\n expression: edgeColumn(childColumns[keyed[index]!]!),\n }))\n );\n const walked = this.#named(this.#escaped(cteName), edgeWalk);\n const edgePage = assembleAdapterSelect(a, {\n columns: this.#named(edgeCarrier, edgeCarrierName),\n from: joins\n ? sql`${walked} ${this.#inner(\n this.table(model, edgeChild),\n this.sameRow(model, edgeChild, childColumns.map(edgeColumn))\n )}`\n : walked,\n orderBy: listed([\n ...parentColumns.map((name) => a.orderBy.asc(edgeColumn(name))),\n ...(siblingOrder ? [siblingOrder] : []),\n ]),\n // MySQL otherwise merges the derived page into the aggregate reader and\n // drops its ORDER BY. The adapter's unbounded LIMIT prevents that merge.\n limit: a.noLimitValue,\n });\n const edgePageAlias = this.alias();\n const edges = this.#scalar({\n columns: a.json.agg(\n this.#document(this.#at(edgePageAlias, edgeCarrierName))\n ),\n from: this.#aside(edgePage, edgePageAlias),\n });\n\n const carrier = (nodeFacts: Sql, edgeFacts: Sql) =>\n this.#object([\n [\n RECURSIVE_CARRIER.root,\n this.#recursiveIdentity(model, this.#rowKey(model, parentAlias)),\n ],\n [RECURSIVE_CARRIER.nodes, this.#document(nodeFacts)],\n [RECURSIVE_CARRIER.edges, this.#document(edgeFacts)],\n ]);\n if (!a.capabilities.supportsLateralJoins)\n return a.subqueries.scalar(\n sql`${cte} ${a.clauses.select(carrier(nodes, edges))}`\n );\n // MySQL materializes a correlated recursive CTE that is read twice (the\n // nodes and the edges) once for the whole statement and hands every outer\n // row the first row's facts. A lateral derived table is re-evaluated per\n // outer row by definition, so the CTE and both readers live inside one\n // wherever the provider spells LATERAL (PostgreSQL, MySQL); SQLite, which\n // has no LATERAL, evaluates the correlated CTE per row as written above.\n const one = this.alias();\n const facts = this.alias();\n const nodeFacts = `__${scope}_nodes`;\n const edgeFacts = `__${scope}_edges`;\n return this.#scalar({\n columns: carrier(this.#at(facts, nodeFacts), this.#at(facts, edgeFacts)),\n from: this.#aside(a.clauses.select(sql`1`), one),\n joins: [\n a.joins.lateral(\n sql`${cte} ${a.clauses.select(\n listed([\n this.#named(nodes, nodeFacts),\n this.#named(edges, edgeFacts),\n ])\n )}`,\n facts\n ),\n ],\n });\n }\n grouped(model: AnyModel, args: Arguments): Query {\n const alias = this.rootAlias();\n // The ONE `by` authority. Admission normalises `by` to an array and\n // refuses its duplicates; the grouped read computes the grouped column SET\n // once and hands it to the two owners that have to know it — `having` and\n // the grouped `orderBy` — instead of each re-reading `args`.\n const by = args.by!;\n const grouped: ReadonlySet<string> = new Set(by);\n // A read-gated model groups a masked window of its filtered rows (K5): a\n // gate lowered once per row, where a gate repeated in the grouping, the\n // projection and the order would be three expressions to the provider.\n const window = this.domain?.project?.window(this, model, args.where);\n if (window)\n return this.#overMasked(() =>\n this.#grouped(model, args, alias, by, grouped, {\n from: this.#aside(window, alias),\n })\n );\n return this.#grouped(model, args, alias, by, grouped, {\n from: this.table(model, alias),\n where: this.lowerWhere(model, args.where, alias),\n });\n }\n #grouped(\n model: AnyModel,\n args: Arguments,\n alias: string,\n by: readonly string[],\n grouped: ReadonlySet<string>,\n rows: { readonly from: Sql; readonly where?: Sql }\n ): Query {\n const aggregates = this.#prepareAggregates(model, args);\n const fields: Record<string, Shape | Leaf> = {};\n const columns: Sql[] = by.map((field) => {\n const leaf = this.scalarShape(model, field);\n // A masked group reads a gated key as absent: the NULL group.\n fields[field] = this.#gatedHere(model, field)\n ? { ...leaf, nullable: true }\n : leaf;\n return this.#named(this.projectedColumn(model, field, alias), field);\n });\n for (const [name, expression] of aggregates.columns(alias)) {\n fields[name] = aggregates.fields_[name]!;\n columns.push(this.#named(expression, name));\n }\n return {\n sql: assembleAdapterSelect(this.adapter, {\n columns: listed(columns),\n from: rows.from,\n where: rows.where,\n groupBy: listed(by.map((field) => this.column(model, field, alias))),\n having: args.having\n ? this.#lowerPredicate(\n this.#prepareHaving(model, args.having as Input),\n alias\n )\n : undefined,\n orderBy: this.#lowerOrder(\n this.#groupOrderTerms(model, args.orderBy, alias, grouped)\n ),\n limit: args.take === undefined ? undefined : this.value(args.take),\n offset: args.skip === undefined ? undefined : this.value(args.skip),\n }),\n shape: { kind: \"object\", fields },\n };\n }\n /** `having` is the same predicate vocabulary over aggregate targets. */\n #prepareHaving(model: AnyModel, having: Input): PreparedPredicate {\n return conjunction(\n Object.entries(having).flatMap(([key, value]) => {\n if (value === undefined) return [];\n // Prisma negates each NOT arm and conjoins the negations.\n if (this.combinator(model, key))\n return [\n this.combine(\n key,\n entries(value).map((clause) =>\n this.#prepareHaving(model, clause as Input)\n )\n ),\n ];\n const scalar = this.scalar(model, key);\n const filter = value as Input;\n const aggregated = AGGREGATES.filter(\n (name) => filter[name] !== undefined\n );\n // A field-keyed condition names a grouped column: admission refuses\n // one outside `by` at its path (`args/aggregate.ts`).\n if (aggregated.length === 0)\n return [this.prepareOperations({ kind: \"column\", scalar }, value)];\n return aggregated.map((aggregate) =>\n this.prepareOperations(\n { kind: \"aggregate\", aggregate, scalar },\n filter[aggregate]\n )\n );\n })\n );\n }\n /**\n * A grouped read orders by a grouped field or by an aggregate; admission\n * refuses any other field at its `orderBy` path (`args/aggregate.ts`).\n */\n #groupOrderTerms(\n model: AnyModel,\n input: Arguments[\"orderBy\"],\n alias: string,\n grouped: ReadonlySet<string>\n ): OrderTerm[] {\n const terms = entries(input ?? {}).flatMap((order) =>\n Object.entries(order).flatMap(([name, direction]) => {\n if (direction === undefined) return [];\n if (!isAggregate(name))\n return [this.#orderTerm(model, name, direction, alias)];\n return Object.entries(direction as Input).flatMap(([field, sort]) => {\n const scalar =\n field === \"_all\" ? undefined : this.scalar(model, field);\n const split =\n name === \"_sum\" &&\n this.#splitSumSql(scalar!, this.#preparedColumn(scalar!, alias));\n return (\n split\n ? split.order\n : [this.#aggregateExpression(name, scalar, alias)]\n ).map((key) => this.#sortKey(key, sort === \"desc\", undefined, false));\n });\n })\n );\n const ordered = new Set(terms.map((term) => term.field));\n for (const field of grouped)\n if (!ordered.has(field))\n terms.push(this.#orderTerm(model, field, \"asc\", alias));\n return terms;\n }\n}\n","/**\n * One call in SQL: what it is, where its statements go, and what a read or a\n * write asks of both. A read is one statement, sent and decoded here; a write\n * is the write path's (`../write`), which asks this for what a statement can\n * answer and for the failure a caller sees.\n */\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport type { AnyDriver } from \"@drivers/driver\";\nimport {\n borrowPositionalResult,\n resolvePositionalResultDriver,\n} from \"@drivers/positional-result\";\nimport { transferPreparedStatement } from \"@drivers/prepared-statement-provenance\";\nimport type { QueryExecutionContext } from \"@drivers/types\";\nimport {\n QueryError,\n retainWriteOutcomeFailure,\n TransactionError,\n VibORMErrorCode,\n} from \"@errors\";\nimport { type AnyModel, getModelKeyCatalog } from \"@schema/model\";\nimport { Sql, sql } from \"@sql\";\nimport {\n compileBindBudgetChunks,\n normalizedBindParameterLimit,\n} from \"../../bind-budget\";\nimport type { PreparedBatchOperation } from \"../../types\";\nimport type { Sent, Statement } from \"../write/send\";\nimport { InsertValue } from \"./insert-value\";\nimport {\n InvalidScalarResult,\n type PreparedProjection,\n type Query,\n type Read,\n type ResultRefusal,\n refusesWhileDecoding,\n returningSafeProjection,\n throughDerived,\n} from \"./query\";\nimport { type EngineBackend, engineBackend } from \"./query-backend\";\nimport type { CallScope } from \"./row-scope\";\nimport {\n type EngineSchema,\n type Input,\n type Operation,\n record,\n} from \"./schema\";\nimport { SqlQueries } from \"./sql-queries\";\nimport { listed, nameOf, tableOf } from \"./terms\";\n\n/** The rows a write returns, named where a statement answers over them. */\nconst MUTATION_ROWS = \"__viborm_mutation\";\n/** That answer, kept apart where it opens a CTE of its own. */\nconst MUTATION_ANSWER = \"__viborm_answer\";\n\nconst ATOMIC_RESOLUTION_OPERATIONS: ReadonlySet<string> = new Set([\n \"update\",\n \"delete\",\n \"upsert\",\n]);\n\n/** One member of a caller's unit, run so that its failure undoes only itself. */\nexport type MemberRollback = <T>(\n execute: (driver: AnyDriver) => Promise<T>,\n context: QueryExecutionContext\n) => Promise<T>;\n\n/** Where a write says what it left durable, to what listens for it. */\nexport interface WriteOutcomeSeam {\n readonly committedSegment?: () => Promise<void>;\n readonly mayBeVisible?: () => Promise<void>;\n}\n\n/** Whose unit the call runs in: its own, or a transaction its caller holds. */\nexport type ExecutionBinding =\n | {\n readonly kind: \"borrowed-transaction\";\n readonly driver: AnyDriver;\n readonly memberRollback?: MemberRollback;\n readonly operationRegion?: MemberRollback;\n readonly writeOutcome?: WriteOutcomeSeam;\n }\n | { readonly kind: \"standalone\"; readonly writeOutcome?: WriteOutcomeSeam };\n\nexport class SqlOperationContext {\n readonly schema: EngineSchema;\n readonly scope: CallScope | undefined;\n readonly modelName: string;\n readonly operation: Operation;\n readonly driver: AnyDriver & { readonly adapter: DatabaseAdapter };\n readonly queries: SqlQueries;\n readonly backend: EngineBackend | undefined;\n /** Whether the call owns its unit, or prepares a package for an owner. */\n readonly #owner: \"standalone\" | \"borrowed-transaction\" | \"batch-preparation\";\n readonly #caller: QueryExecutionContext | undefined;\n #correlation: string | undefined;\n #package: PreparedBatchOperation<unknown> | undefined;\n\n constructor(\n schema: EngineSchema,\n factoryDriver: AnyDriver,\n modelName: string,\n operation: Operation,\n binding?: ExecutionBinding,\n preparing = false,\n caller?: QueryExecutionContext,\n scope?: CallScope\n ) {\n this.schema = schema;\n this.scope = scope;\n this.modelName = modelName;\n this.operation = operation;\n this.#caller = caller;\n this.#owner = preparing\n ? \"batch-preparation\"\n : (binding?.kind ?? \"standalone\");\n this.driver = (\n binding?.kind === \"borrowed-transaction\" ? binding.driver : factoryDriver\n ) as this[\"driver\"];\n // The language is the driver's the call was made on: a transaction's view of it writes the same.\n this.backend =\n factoryDriver.backend && engineBackend(factoryDriver.backend);\n this.queries = new (this.backend?.queries ?? SqlQueries)(\n schema,\n this.driver.adapter,\n this.driver.result,\n scope?.domain,\n scope\n ) as SqlQueries;\n }\n\n /** What every statement of the call is attributed to. */\n get attribution(): QueryExecutionContext {\n return this.#caller ?? this.#own;\n }\n\n /** The call's own record of itself: an error's meta, whoever the caller is. */\n get #own(): QueryExecutionContext {\n return {\n model: this.modelName,\n operation: this.operation,\n correlationId: (this.#correlation ??= crypto.randomUUID()),\n };\n }\n\n /** The failure a caller sees: a value the result could not hold says so in the call's words. */\n failure(error: unknown): unknown {\n if (error instanceof InvalidScalarResult) {\n const driver = this.driver.driverName;\n const model = this.modelName;\n const operation = this.operation;\n const { scalarType, reason } = error;\n return new QueryError(\n `The \"${operation}\" result is incompatible with the ${scalarType} scalar domain: ${reason}.`,\n {\n code: VibORMErrorCode.QUERY_RESULT_INVALID,\n meta: { driver, model, operation, scalarType, reason },\n }\n );\n }\n return error instanceof Error && \"refusal\" in error\n ? (error as Error & ResultRefusal).refusal(this.operation, this.modelName)\n : error;\n }\n\n async run<T>(body: () => Promise<T>): Promise<T> {\n try {\n return await body();\n } catch (error) {\n throw this.failure(error);\n }\n }\n\n /** A read's rows as the call publishes them. */\n #published(read: Read, rows: Input[]): Input[] {\n this.queries.assertExpectedRows(read.query, rows.length);\n return this.queries.decodeResult(rows, this.operation, (raw) =>\n this.queries.decodeProjection(read.query.shape, raw)\n );\n }\n\n /**\n * One read: its one statement sent, or queued for the owner the call\n * prepares for, and its rows decoded and decided once. `seen` is told the\n * driver's rows first; it takes object rows, as a prepared parser does.\n */\n async publish(\n read: Read,\n missing?: () => Error,\n seen?: (rows: readonly unknown[]) => void\n ): Promise<unknown> {\n const positional =\n seen === undefined &&\n this.#owner === \"standalone\" &&\n read.value.kind === \"collection\"\n ? resolvePositionalResultDriver(this.driver)\n : undefined;\n if (positional === undefined) {\n const response = await this.driver._execute<Input>(\n read.query.sql,\n this.attribution\n );\n seen?.(response.rows);\n return decide(read, missing, this.#published(read, response.rows));\n }\n const response = await positional(read.query.sql, this.attribution);\n if (\n response.kind === \"positional\" &&\n resolvePositionalResultDriver(this.driver) === positional\n ) {\n this.queries.assertExpectedRows(read.query, response.rows.length);\n return decide(\n read,\n missing,\n this.queries.decodeProjection(\n read.query.shape,\n response.rows,\n false,\n response.columns\n )\n );\n }\n const borrowed =\n response.kind === \"borrowed\"\n ? response.result\n : borrowPositionalResult(response);\n return decide(\n read,\n missing,\n this.#published(read, borrowed.rows.map(record))\n );\n }\n\n /** The read as a package: its statement, and the parser of its one result. */\n publishPrepared(read: Read, missing?: () => Error): undefined {\n const context = this.attribution;\n const prepared = this.driver._prepare(read.query.sql, context);\n // The driver owns the query's identity: what it registered against the\n // object it returned travels with the copy that carries the context.\n const query = transferPreparedStatement(prepared, {\n sql: prepared.sql,\n params: prepared.params ?? [],\n context,\n });\n this.#package = {\n queries: [query],\n parseResult: (results) => {\n const response = results[0];\n if (!response)\n throw new TransactionError(\n `Driver '${this.driver.driverName}' omitted the prepared result for operation '${this.operation}'.`,\n { meta: { ...this.#own } }\n );\n try {\n return decide(\n read,\n missing,\n this.#published(read, response.rows.map(record))\n );\n } catch (error) {\n throw this.failure(error);\n }\n },\n };\n return undefined;\n }\n\n preparedBatch(): PreparedBatchOperation<unknown> | undefined {\n return this.#package;\n }\n\n /** A write of several statements needs a unit that takes all or none. */\n requireAtomicUnit(): void {\n if (this.#owner !== \"standalone\") return;\n const driver = this.driver;\n const meta = { driver: driver.driverName, operation: this.operation };\n if (!(driver.supportsTransactions || driver.supportsBatch))\n throw new TransactionError(\n `Driver \"${driver.driverName}\" supports neither transactions nor atomic batch execution.`,\n { meta }\n );\n if (\n driver.supportsBatch &&\n !driver.supportsTransactions &&\n !driver.adapter.capabilities.supportsReturning &&\n ATOMIC_RESOLUTION_OPERATIONS.has(this.operation)\n )\n throw new TransactionError(\n this.operation === \"upsert\"\n ? \"cannot execute non-returning upsert writes atomically because public result parsing cannot be rolled back after an atomic batch commits\"\n : `Driver '${driver.driverName}' cannot execute '${this.operation}' because public result parsing cannot be rolled back.`,\n { meta }\n );\n }\n\n /** Says what the write left durable; a failure to say it rides the write's own. */\n async stateWriteOutcome(\n say: (() => Promise<void>) | undefined,\n primary?: unknown\n ): Promise<void> {\n if (!say) return;\n try {\n await say();\n } catch (outcomeFailure) {\n if (primary === undefined) throw outcomeFailure;\n throw retainWriteOutcomeFailure(primary, outcomeFailure);\n }\n }\n\n /** The reads of the rows a many-row write names, each within the bind budget. */\n seriesQueries(\n projection: PreparedProjection,\n identities: Input[],\n operation: \"createMany\" | \"updateMany\" = \"createMany\"\n ): Query[] {\n if (identities.length === 0) return [];\n const queries = new Map<Sql, Query>();\n return compileBindBudgetChunks(\n identities.length,\n normalizedBindParameterLimit(this.driver.maxBindParametersPerStatement),\n (start, end) => {\n const query = this.queries.selectSeries(\n projection,\n identities.slice(start, end),\n operation\n );\n queries.set(query.sql, query);\n return query.sql;\n }\n ).map(({ statement }) => queries.get(statement)!);\n }\n\n /**\n * Statements that go together sent as one request, where a backend has\n * such a request: their answers, each as its own statement's. `whole` where\n * they are the call's whole unit, which the request then opens and closes,\n * and stops where one of them asks what is not so. A request that fails\n * says nothing of which statement did: the call is made again without.\n */\n together?(\n driver: AnyDriver,\n statements: readonly Statement[],\n whole: boolean\n ): Promise<Sent[]> | undefined;\n\n /** Whether a call whose own unit `error` undid is made again, the `attempt`th time: never here, where a writer that meets another waits for it. */\n again(_error: unknown, _attempt: number): boolean | Promise<boolean> {\n return false;\n }\n\n /** The rows with every value an extension computes put in; `asks` is how one asks the database in the call's unit, where it can be heard before the rows are written. */\n computed(\n model: AnyModel,\n rows: Input[],\n asks?: (statement: Sql, model: AnyModel) => Promise<readonly Input[]>\n ): Input[] | Promise<Input[]> {\n let fields: Map<string, { value: InsertValue; at: number[] }> | undefined;\n for (let index = 0; index < rows.length; index++) {\n const row = rows[index]!;\n for (const field in row) {\n const value = row[field];\n if (value instanceof InsertValue) {\n fields ??= new Map();\n const entry = fields.get(field) ?? { value, at: [] };\n entry.at.push(index);\n fields.set(field, entry);\n }\n }\n }\n // Most rows hold nothing an extension computes: they are answered at once.\n return fields ? this.#compute(model, rows, fields, asks) : rows;\n }\n\n async #compute(\n model: AnyModel,\n rows: Input[],\n fields: Map<string, { value: InsertValue; at: number[] }>,\n asks?: (statement: Sql, model: AnyModel) => Promise<readonly Input[]>\n ): Promise<Input[]> {\n const spelt = this.queries.spelling(model, this.driver.dialect);\n const computed = rows.map((row) => ({ ...row }));\n for (const [field, { value, at }] of fields) {\n const values = await value.compute(\n {\n model: nameOf(model),\n rows: computed,\n field,\n sql: spelt,\n dialect: spelt.dialect,\n ...(asks && { read: (statement: Sql) => asks(statement, model) }),\n },\n at\n );\n for (const [position, index] of at.entries())\n computed[index]![field] = values[position];\n }\n return computed;\n }\n\n /** {@link answersInStatement}'s projections over a write. */\n #overWrites:\n | WeakMap<\n PreparedProjection,\n { readonly answer: Sql; readonly folds: boolean }\n >\n | undefined;\n\n /**\n * Whether the statement that writes can answer `projection` itself: where\n * the provider returns rows, the projection does not refuse while it\n * decodes, and nothing it reads is a row the statement is still writing.\n */\n answersInStatement(\n model: AnyModel,\n projection: PreparedProjection,\n effect: \"insert\" | \"update\" | \"delete\",\n written?: Input\n ): boolean {\n const capabilities = this.driver.adapter.capabilities;\n if (!capabilities.supportsReturning) return false;\n if (returningSafeProjection(projection)) return true;\n if (refusesWhileDecoding(projection)) return false;\n if (effect === \"delete\") return capabilities.supportsCteWithMutations;\n if (written !== undefined) {\n const keys = getModelKeyCatalog(model).referenceableKeys;\n if (\n keys.some((key) => key.some((field) => Object.hasOwn(written, field)))\n )\n return false;\n }\n return this.#overWrite(model, projection).folds;\n }\n\n #overWrite(\n model: AnyModel,\n projection: PreparedProjection\n ): { readonly answer: Sql; readonly folds: boolean } {\n const known = this.#overWrites?.get(projection);\n if (known !== undefined) return known;\n const a = this.driver.adapter;\n const table = tableOf(model);\n const name = Sql.leafText(a.identifiers.escape(table))!;\n let answer: Sql;\n let folds = true;\n if (a.capabilities.supportsCteWithMutations) {\n answer = this.queries.select(model, {}, undefined, {\n projection,\n source: MUTATION_ROWS,\n }).sql;\n if (a.cte.opens(answer))\n answer = throughDerived(a, answer, MUTATION_ANSWER);\n } else {\n answer = this.queries.sharing(() =>\n listed(this.queries.lowerProjection(projection, table))\n );\n folds = !a.cte.opens(answer);\n }\n // A relation read from the written table would see it before the write.\n folds &&= !Sql.peek(answer).strings.some((text) => {\n for (\n let at = text.indexOf(name);\n at !== -1;\n at = text.indexOf(name, at + 1)\n )\n if (text[at + name.length] !== \".\") return true;\n return false;\n });\n const over = { answer, folds };\n (this.#overWrites ??= new WeakMap()).set(projection, over);\n return over;\n }\n\n /** `statement`, answering `projection` over the rows it writes. */\n answering(\n model: AnyModel,\n statement: Sql,\n projection: PreparedProjection,\n extra: Sql[] = []\n ): Sql {\n const a = this.driver.adapter;\n if (returningSafeProjection(projection))\n return sql`${statement} ${a.mutations.returning(\n listed([...this.queries.lowerProjection(projection), ...extra])\n )}`;\n const { answer } = this.#overWrite(model, projection);\n if (!a.capabilities.supportsCteWithMutations)\n return sql`${statement} ${a.mutations.returning(answer)}`;\n return sql`${a.cte.with([\n {\n name: MUTATION_ROWS,\n query: sql`${statement} ${a.mutations.returning(sql.raw(\"*\"))}`,\n },\n ])} ${answer}`;\n }\n}\n\n/** A read's value; the error of a required row that is not there. */\nfunction decide(\n read: Read,\n missing: (() => Error) | undefined,\n rows: Input[]\n): unknown {\n const value = read.result(rows);\n if (value === null && missing) throw missing();\n return value;\n}\n","/**\n * How a call's statements reach the database: one unit at a time. A dialogue\n * sends each statement once the one before answered, inside a transaction;\n * atomic batches send the statements that go together as one batch. Both\n * send the same statements.\n */\nimport type { AnyDriver } from \"@drivers\";\nimport { deriveStatementExecutionContext } from \"@drivers/execution-context\";\nimport { transferPreparedStatement } from \"@drivers/prepared-statement-provenance\";\nimport type { QueryExecutionContext } from \"@drivers/types\";\nimport {\n NESTED_WRITE_ASSERTION_FLOOR_MESSAGE,\n NestedWriteAssertionError,\n NestedWriteError,\n VibORMErrorCode,\n} from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { Sql } from \"@sql\";\nimport type { PreparedGuardFailure } from \"../../types\";\nimport type { Input } from \"../shared/schema\";\nimport type {\n MemberRollback,\n SqlOperationContext,\n} from \"../shared/sql-operation-context\";\nimport { nameOf } from \"../shared/terms\";\n\n/** What the database says of one statement. */\nexport interface Sent {\n readonly rows: Input[];\n readonly rowCount: number;\n readonly insertId?: unknown;\n}\n\n/** One statement, which suffices by itself, and the model it is sent in the name of. */\nexport interface Statement {\n readonly sql: Sql;\n readonly model: AnyModel;\n /** What it refuses with where it stops its unit. */\n readonly stops?: PreparedGuardFailure;\n /**\n * It stops its unit on what the call believed, not on what it may do: a\n * row it took to be there (`presumed`), or what it read (`read`). The call\n * is then run again on what the database says.\n */\n readonly believed?: \"presumed\" | \"read\";\n /** Its question by itself, where a provider does not say which statement stopped a batch. */\n readonly probe?: Sql;\n /** The answer a question asked for its own sake needs. */\n readonly premise?: \"exists\" | \"notExists\";\n}\n\n/** A unit stopped by one of its own statements: nothing of it was written. */\nexport class Stopped {\n readonly statement: Statement;\n constructor(statement: Statement) {\n this.statement = statement;\n }\n}\n\n/** How a unit of the call's statements reaches the database. */\nexport interface Transport {\n /** Rows the call read are held until its unit ends: no statement asks for them again. */\n readonly holds: boolean;\n /** Whether what was last sent stands once answered, whatever the call does next. */\n loose?: boolean;\n /** Sends statements that go together and answers for each; `last` where the call has no more to say. */\n send(statements: readonly Statement[], last: boolean): Promise<Sent[]>;\n /** Ends the unit: undone where the call `failed`. Nothing to wait for where no unit was opened. */\n end(failed?: unknown): Promise<void> | undefined;\n /**\n * Sends what `body` sends as a part of the unit that is undone alone where\n * it fails. None where the unit has no such part.\n */\n attempt?<T>(body: (send: Transport[\"send\"]) => Promise<T>): Promise<T>;\n}\n\n/** The statement the database refused, by the error it refused it with. */\nexport const refusedBy = new WeakMap<object, Statement>();\n\n/** The failures of what was sent outside any unit that proves it undone: what it wrote may be there. */\nexport const unproven = new WeakSet<object>();\n/** Those of them that say nothing of which statement failed, of several sent as one unit by a driver that does not say when a unit is made: the unit may have been made whole. */\nexport const unsaid = new WeakSet<object>();\nconst loose = (error: unknown): never => {\n if (typeof error === \"object\" && error) unproven.add(error);\n throw error;\n};\n\n/** The context one statement is sent under: the operation's, named for the model it touches. */\nexport const contextOf = (\n operation: SqlOperationContext,\n model: AnyModel\n): QueryExecutionContext => {\n const whole = operation.attribution;\n const name = nameOf(model);\n return whole.model === name\n ? whole\n : deriveStatementExecutionContext(whole, name);\n};\n\n/**\n * A dialogue: each statement is sent once the one before answered, inside\n * the unit `open` opens. On `driver` itself where there is none to open, or\n * where the call is one statement.\n */\nexport function dialogue(\n operation: SqlOperationContext,\n driver: AnyDriver,\n open?: (body: (inside: AnyDriver) => Promise<void>) => Promise<unknown>,\n /** Undoes a part of the unit alone, where the unit is not the call's own to open. */\n rollback?: MemberRollback,\n /** The unit is the call's own: where it fails, the call may be made again. */\n own = false\n): Transport {\n let entered: Promise<AnyDriver> | undefined;\n let unit: Promise<unknown> | undefined;\n let leave: ((failed?: unknown) => void) | undefined;\n const enter = () =>\n (entered ??= new Promise<AnyDriver>((inside, refused) => {\n unit = open!(\n (transport) =>\n new Promise<void>((done, undo) => {\n leave = (failed) => (failed === undefined ? done() : undo(failed));\n inside(transport);\n })\n );\n unit.catch(refused);\n }));\n /** What a statement asks for its own sake: its answer is heard, and says whether the unit goes on. */\n const asked = (statement: Statement) =>\n Boolean(statement.believed) || statement.sql === statement.probe;\n const hear = (transport: AnyDriver, statement: Statement) =>\n // What the call believed is asked, not asserted: a dialogue hears\n // the answer, and a statement that fails would undo its unit.\n transport\n ._execute<Input>(\n statement.believed ? statement.probe! : statement.sql,\n contextOf(operation, statement.model)\n )\n .catch((error) => {\n if (typeof error === \"object\" && error) refusedBy.set(error, statement);\n throw statement.stops && error instanceof NestedWriteAssertionError\n ? new Stopped(statement)\n : error;\n });\n const run = async (\n transport: AnyDriver,\n statements: readonly Statement[],\n together = false\n ): Promise<Sent[]> => {\n const answers: Sent[] = [];\n for (let at = 0; at < statements.length; ) {\n // One request takes what goes together, where the backend has such a request: no further than what is asked for its own sake, which is heard before what follows it is sent.\n let end = at + 1;\n while (\n together &&\n end < statements.length &&\n !(asked(statements[end - 1]!) && !asked(statements[end]!))\n )\n end++;\n const sent = (end - at > 1 &&\n (await operation.together?.(\n transport,\n statements.slice(at, end),\n false\n ))) || [await hear(transport, statements[at]!)];\n for (let place = 0; place < sent.length; place++) {\n const statement = statements[at + place]!;\n if (\n asked(statement) &&\n sent[place]!.rows.length > 0 !== (statement.premise === \"exists\")\n )\n throw new Stopped(statement);\n answers.push(sent[place]!);\n }\n at += sent.length;\n }\n return answers;\n };\n /** Sends statements inside the unit, opened where it is not yet. */\n const within = async (statements: readonly Statement[]) =>\n run(await enter(), statements, own);\n const transport: Transport = {\n holds: true,\n send(statements, last) {\n const whole = last && !entered;\n const alone = !open || (whole && statements.length === 1);\n transport.loose = alone;\n // A call that says everything at once is one unit by itself, where the backend takes a unit as one request.\n const one =\n own && whole && !alone\n ? operation.together?.(driver, statements, true)\n : undefined;\n if (one) {\n transport.loose = true;\n return one.catch(loose);\n }\n return alone\n ? run(driver, statements, own).catch(loose)\n : within(statements);\n },\n ...((open || rollback) && {\n async attempt(body) {\n const within = (inner: AnyDriver) =>\n body((statements) => run(inner, statements));\n return open\n ? (await enter()).withTransaction(\n within,\n undefined,\n operation.attribution\n )\n : rollback!(within, operation.attribution);\n },\n }),\n end(failed) {\n if (!entered) return;\n // A unit that could not be opened has nothing to leave: what refused it is what failed.\n leave?.(failed);\n // What the unit says of its own undoing is said with what undid it.\n return unit!\n .then(\n () => failed,\n (error) => error\n )\n .then((said) => {\n if (said !== failed) throw said;\n });\n },\n };\n return transport;\n}\n\n/** One statement as a batch takes it. */\nexport const prepared = (\n operation: SqlOperationContext,\n driver: AnyDriver,\n statement: Statement\n) => {\n const at = contextOf(operation, statement.model);\n const query = driver._prepare(statement.sql, at);\n return transferPreparedStatement(query, {\n sql: query.sql,\n params: query.params ?? [],\n context: at,\n });\n};\n\n/** Atomic batches: the statements that go together are one batch, durable once it answers. */\nexport function batches(\n operation: SqlOperationContext,\n driver: AnyDriver\n): Transport {\n const send = async (\n statements: readonly Statement[],\n last = true\n ): Promise<Sent[]> => {\n const [alone] = statements;\n // What is more than one statement is one unit, or is not sent.\n if (statements.length > 1 || !last) operation.requireAtomicUnit();\n try {\n return statements.length === 1\n ? [\n await driver._execute<Input>(\n alone!.sql,\n contextOf(operation, alone!.model)\n ),\n ]\n : await driver._executeBatch<Input>(\n statements.map((statement) =>\n prepared(operation, driver, statement)\n ),\n undefined,\n operation.attribution\n );\n } catch (error) {\n // A unit that stops itself is undone; one that fails otherwise may have been made.\n if (!(error instanceof NestedWriteAssertionError)) {\n if (\n statements.length > 1 &&\n !driver.supportsOrderedCommittedSegments &&\n typeof error === \"object\" &&\n error &&\n (error as { meta?: { statementIndex?: number } }).meta\n ?.statementIndex === undefined\n )\n unsaid.add(error);\n loose(error);\n }\n // The statement that stopped the batch is the one the provider points\n // at. Where it points at none, what was asked for its own sake is\n // asked again together, then each judgement; where all still hold, it\n // is the first that judged its rows amid the batch's writes.\n const index = (error as NestedWriteAssertionError).meta.statementIndex;\n const stopping = statements.filter((statement) => statement.stops);\n // The one statement that may stop the batch is the one that did.\n let stopped =\n typeof index === \"number\"\n ? statements[index]\n : stopping.length === 1\n ? stopping[0]\n : undefined;\n if (!stopped) {\n const asked = statements.filter((statement) => statement.premise);\n const answers =\n asked.length > 0\n ? await send(\n asked.map(({ probe, model }) => ({ sql: probe!, model }))\n )\n : [];\n stopped = asked.find(\n ({ premise }, at) =>\n answers[at]!.rows.length > 0 !== (premise === \"exists\")\n );\n for (const statement of stopped ? [] : statements) {\n if (statement.premise || !statement.probe) continue;\n stopped = await send([\n { sql: statement.probe, model: statement.model },\n ]).then(\n () => undefined,\n () => statement\n );\n if (stopped) break;\n }\n }\n stopped ??= statements.find(\n (statement) => statement.stops && !statement.probe\n );\n // Every premise holds again once asked alone: what the call believed is what it runs again on; where it believed nothing, the unit's stop is all there is to say.\n stopped ??= statements.find(\n (statement) => statement.stops && statement.believed\n );\n throw stopped?.stops\n ? new Stopped(stopped)\n : new NestedWriteError(NESTED_WRITE_ASSERTION_FLOOR_MESSAGE, \"\", {\n code: VibORMErrorCode.NESTED_WRITE_ASSERTION_FAILED,\n cause: error as Error,\n });\n }\n };\n return { holds: false, loose: true, send, end: () => undefined };\n}\n","/**\n * The one place a statement is written: under the call's row scope, in the\n * provider's spelling. The store says which rows and what they take; it\n * never says who may.\n */\n\nimport {\n adapterConstraints,\n assembleAdapterSelect,\n getAdapterInternals,\n} from \"@adapters/adapter-internals\";\nimport { NestedWriteError, type UniqueConstraintError } from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport { type Sql, sql } from \"@sql\";\nimport type { PreparedGuardFailure } from \"../../types\";\nimport { writeSinks } from \"../../write-sinks\";\nimport { InsertValue, JoinedValue, Stored } from \"../shared/insert-value\";\nimport type {\n PreparedProjection,\n PreparedSelector,\n Query,\n} from \"../shared/query\";\nimport { Parameter, type WriteJudgement } from \"../shared/row-scope\";\nimport type { Input } from \"../shared/schema\";\nimport type { SqlOperationContext } from \"../shared/sql-operation-context\";\nimport type { SqlQueries } from \"../shared/sql-queries\";\nimport { linkJudgement, linkMembers, type Membership } from \"../shared/storage\";\nimport {\n listed,\n nameOf,\n scalarsOf,\n tableOf,\n unsupported,\n} from \"../shared/terms\";\nimport type { Sent, Statement } from \"./send\";\n\nexport type Junction = Extract<Membership, { kind: \"junction\" }>;\n\n/** A question: the rows of a model a filter names, among the members of a row where it says so. */\nexport interface Question {\n readonly model: AnyModel;\n readonly where?: Input;\n /** The filter was admitted as a unique selector: it names one row at most. */\n readonly unique?: boolean;\n readonly member?: { readonly edge: Membership; readonly of: Input };\n /** The relation the rows are reached through, whose ever members they are. */\n readonly through?: Membership;\n /** What the call means to do with the rows: `join` makes them members, or no longer; of an update, what it writes of them. */\n readonly intent?: \"update\" | \"delete\" | \"join\";\n readonly writes?: readonly string[];\n /** No more than that many of them, the first by their key. */\n readonly limit?: number;\n /** The nested verb that asks, for what it refuses with. */\n readonly verb?: string;\n /** A row must be there: none is the call's refusal. */\n readonly must?: true;\n /**\n * Every row the call may see must be one it may write so: a row it cannot\n * see is passed by, one it sees and may not write is a refusal. With what\n * it refuses with, where not as a row that is not there.\n */\n readonly strict?: boolean | string;\n /**\n * Among the rows a row the call may see still references through a\n * relation that restricts deletes: all of them, or all but the row with\n * that key through that relation.\n */\n readonly referenced?:\n | true\n | { readonly slot: string; readonly identity: Input };\n /** No other rows than those with these keys. */\n readonly only?: readonly Input[];\n /** Rows left out, by their key. */\n readonly except?: readonly Input[];\n /** Rows named by their keys are still to answer the filter they were found by. */\n readonly again?: boolean;\n /** Where none answers, the call makes a row under what the question names: asked without holding the place. */\n readonly makes?: boolean;\n /** A value the write reads from a table it joins: no other rows than those that table names. */\n readonly joined?: JoinedValue;\n}\n\n/** `next` of a value: at once where it is there, no tick spent waiting for what did not wait. */\nexport const after = <T, R>(\n value: T | Promise<T>,\n next: (value: T) => R\n): R | Promise<Awaited<R>> =>\n value instanceof Promise\n ? (value.then(next) as Promise<Awaited<R>>)\n : next(value);\n\nexport class Writer {\n readonly operation: SqlOperationContext;\n /** The dialect its statements are written in. */\n readonly adapter: SqlOperationContext[\"driver\"][\"adapter\"];\n readonly #q: SqlQueries;\n #projections: Map<AnyModel, PreparedProjection[]> | undefined;\n /** Asks the database in the call's unit, where what it says is heard before the next statement is written. */\n readonly hears:\n | ((statement: Sql, model: AnyModel) => Promise<readonly Input[]>)\n | undefined;\n protected computed(\n model: AnyModel,\n rows: Input[]\n ): Input[] | Promise<Input[]> {\n return this.operation.computed(model, rows, this.hears);\n }\n /** A question as a statement that stops its unit unless a row answers it, or where one does. */\n protected asserts(probe: Sql, premise: \"exists\" | \"notExists\"): Sql {\n return this.adapter.assertions[premise](probe);\n }\n constructor(operation: SqlOperationContext, hears?: Writer[\"hears\"]) {\n this.operation = operation;\n this.adapter = operation.driver.adapter;\n this.#q = operation.queries as SqlQueries;\n this.hears = hears;\n }\n /** What a write of the rows a question names is judged at. */\n protected judged(question: Question): WriteJudgement | undefined {\n const edge = question.through ?? question.member?.edge;\n if (question.intent === \"join\" && edge) return linkJudgement(edge);\n if (question.intent === \"delete\") return { kind: \"delete\", writes: [] };\n const { writes } = question;\n if (!writes) return undefined;\n const tombstone = this.operation.scope?.rows.tombstones?.get(\n nameOf(question.model)\n );\n // A caller who writes what a delete that keeps its rows writes is judged as that delete is.\n return tombstone &&\n writes.some(\n (field) =>\n field === tombstone.at || Object.hasOwn(tombstone.assign, field)\n )\n ? { kind: \"update\", writes, marks: true }\n : { kind: \"update\", writes };\n }\n #related(question: Question): \"root\" | \"related\" {\n return question.member || question.through ? \"related\" : \"root\";\n }\n /** The rows a question names, among those the call may take so; `keys` narrows them to rows the call knows. */\n selector(question: Question, keys?: readonly Input[]): PreparedSelector {\n const q = this.#q;\n const { model } = question;\n const only = keys ?? question.only;\n const known = only && q.includeIdentities(model, only);\n // The filter is said again beside the keys; one that reads other rows, only where a write may read its own table.\n const found =\n known && question.again && question.where !== undefined\n ? q.prepareSelector(model, question.where, false)\n : undefined;\n const named = known\n ? found &&\n (found.facts.reads.size === 0 ||\n this.adapter.capabilities.supportsMutationTargetInSubquery)\n ? q.andSelectors(model, [known, found])\n : known\n : q.prepareSelector(model, question.where, question.unique ?? false);\n const { referenced, limit } = question;\n const own = question.except?.length\n ? {\n ...q.andSelectors(model, [\n named,\n q.excludeIdentities(model, question.except),\n ]),\n uniqueKey: named.uniqueKey,\n uniqueValues: named.uniqueValues,\n }\n : named;\n const scope = this.operation.scope;\n const taken = q.candidates(\n own,\n this.#related(question),\n undefined,\n this.judged(question)\n );\n // A delete that keeps its rows takes those an absent control would show, whatever the call's own show.\n const chosen =\n question.intent === \"delete\" &&\n scope &&\n scope.defaults !== scope.domain &&\n scope.rows.tombstones?.has(nameOf(model))\n ? q.candidates(taken, this.#related(question), scope.defaults)\n : taken;\n if (!referenced) return chosen;\n // Of the rows the write takes: the first of them, where it takes no more.\n return q.andSelectors(model, [\n limit === undefined || only ? chosen : q.window(chosen, limit),\n scope!.rows.tombstones!.selector(\n q,\n model,\n scope!.defaults,\n referenced === true ? undefined : referenced\n ),\n ]);\n }\n /** Fields of a row of `model`, as a statement answers with them. */\n fields(model: AnyModel, fields: readonly string[]) {\n return this.#q.prepareProjection(\n model,\n { select: Object.fromEntries(fields.map((field) => [field, true])) },\n true\n );\n }\n /** The whole row of a model, and its key, as projections. */\n protected projection(model: AnyModel, whole: boolean): PreparedProjection {\n let known = this.#projections?.get(model);\n if (!known) {\n const { schema } = this.operation;\n known = [\n this.fields(model, schema.keys(model)),\n this.fields(model, schema.storedFields(model)),\n ];\n (this.#projections ??= new Map()).set(model, known);\n }\n return known[Number(whole)]!;\n }\n protected membership(question: Question) {\n return (\n question.member && {\n edge: question.member.edge,\n parent: question.member.of,\n }\n );\n }\n /** The rows a write names, as its statement says them: among the members of the question's row, where it has one. */\n #among(question: Question, selector: PreparedSelector, alias: string) {\n return this.#within(\n question,\n alias,\n this.#q.lowerSelector(selector, alias)\n );\n }\n /** `named`, among the members of the question's row where it has one. */\n #within(question: Question, alias: string, named: Sql | undefined) {\n const { member } = question;\n if (!member) return named;\n // A write holds the links it reads its rows' membership from: one that goes while the statement waits is no longer read.\n const members = this.#q.memberWhere(member.edge, member.of, alias, true);\n return named ? this.adapter.operators.and(members, named) : members;\n }\n #limited(\n question: Question,\n selector: PreparedSelector,\n keys: unknown\n ): { where?: Sql; suffix?: Sql } {\n const { model, member } = question;\n const named = this.#q.lowerMutationLimit(\n model,\n selector,\n keys || member ? undefined : question.limit\n );\n // Among the members of the question's row: said of the table the statement writes.\n return member\n ? { where: this.#within(question, tableOf(model), named.where) }\n : named;\n }\n /** What a write sets of the rows it takes. */\n #sets(model: AnyModel, set: Input): Sql {\n return listed(\n Object.entries(set).map(([field, value]) =>\n this.#q.updateAssignment(model, field, value)\n )\n );\n }\n /** A write of rows with what bounds it, answering with the rows it wrote as the caller reads them, or so that the call can count them where the provider's own count would count what a cascade changed besides. */\n #answered(\n model: AnyModel,\n build: () => [write: Sql, suffix?: Sql],\n projection: PreparedProjection | undefined,\n counted: boolean\n ): Sql {\n const { capabilities, mutations } = this.adapter;\n const statement = this.#q.sharing(() => {\n const [write, suffix] = build();\n return suffix ? sql`${write} ${suffix}` : write;\n });\n if (projection)\n return this.operation.answering(model, statement, projection);\n return counted && capabilities.countsCascadedChanges\n ? sql`${statement} ${mutations.returning(sql.raw(\"1\"))}`\n : statement;\n }\n /** The rows questions of one model name, read whole in one statement; held where `hold`. */\n read(questions: readonly Question[], hold: boolean): Query {\n const [question] = questions as [Question];\n const selectors = questions.map((each) => this.selector(each));\n const { joined } = question;\n const { filters, subqueries } = this.adapter;\n return this.#q.select(\n question.model,\n question.limit === undefined ? {} : { take: question.limit },\n this.membership(question),\n {\n forUpdate: hold,\n condition:\n joined &&\n ((alias) => {\n const join = joined.join(\n this.#q.spelling(question.model, this.operation.driver.dialect),\n alias\n );\n return this.#q.settleRows(\n filters.some(subqueries.existsCheck(join.source, join.on))\n );\n }),\n projection: this.projection(question.model, true),\n selector:\n selectors.length === 1\n ? selectors[0]\n : {\n model: question.model,\n predicate: {\n kind: \"or\",\n predicates: selectors.map((each) => each.predicate!),\n },\n },\n }\n );\n }\n /** What a call refuses with where a row a question asks for is not there. */\n absent(question: Question, raceable = false): PreparedGuardFailure {\n const edge = question.member?.edge ?? question.through;\n return edge && question.verb\n ? {\n kind: \"nestedWrite\",\n relation: edge.name,\n message: `Cannot ${question.verb} relation '${edge.name}': target record was not found${question.member ? \" for this parent\" : \"\"}.`,\n raceable,\n }\n : { kind: \"notFound\", message: \"\", raceable };\n }\n /**\n * A statement that stops its unit unless each question still names a row:\n * the one `key` names, or every one of the rows several keys name, where\n * given. It stops on what the call `believed`, or, where the row must be\n * there, on the call's refusal itself.\n */\n asks(\n asked: readonly (readonly [Question, (Input | Input[])?])[],\n believed: \"presumed\" | \"read\",\n heard = false,\n held = true\n ): Statement {\n const q = this.#q;\n const { operators } = this.adapter;\n const [[question]] = asked as [[Question]];\n const { model } = question;\n // The rows asked for are held from there to the end of their unit, where the database holds rows: what is written after stands on them.\n const lock = held && this.adapter.capabilities.supportsRowLocks;\n const asking = (\n [each, key]: readonly [Question, (Input | Input[])?],\n more?: Sql\n ) => {\n // Of several rows: as many of them as there are still answer.\n const keys = Array.isArray(key) ? key : undefined;\n return q.select(\n model,\n { take: 1, ...(keys && { skip: keys.length - 1 }) },\n this.membership(each),\n {\n projection: this.projection(model, false),\n forUpdate: lock,\n selector: keys\n ? q.andSelectors(model, [\n this.selector(each),\n q.includeIdentities(model, keys),\n ])\n : this.selector(each),\n ...(key && !keys && { identity: key as Input }),\n ...(more && { condition: more }),\n }\n ).sql;\n };\n // One row answers where every question names one.\n const [first, ...others] = asked as [[Question, (Input | Input[])?]];\n const probe = asking(\n first,\n others.length > 0\n ? operators.and(...others.map((each) => operators.exists(asking(each))))\n : undefined\n );\n return {\n // Where its answer is heard, the question itself is what is sent.\n sql: heard && lock ? probe : this.asserts(probe, \"exists\"),\n probe,\n premise: \"exists\",\n believed: believed === \"presumed\" && question.must ? undefined : believed,\n // Also what an owner that cannot run the call again reports.\n stops: this.absent(question, believed === \"read\"),\n model,\n };\n }\n /**\n * What a row of `model` takes where it is created, or updated: what was\n * admitted of what the caller wrote of it, `raw`, and what the call's\n * extensions write of every such row, where the caller wrote nothing.\n */\n values(\n model: AnyModel,\n kind: \"create\" | \"update\",\n admitted: Input,\n raw: Input = {},\n /** What the row takes of the rows it references: written as the caller's own. */\n takes?: Input\n ): Input {\n const { scope, schema } = this.operation;\n const stamps = scope?.rows.stamps?.get(nameOf(model))?.[kind];\n let source = admitted;\n if (stamps) {\n const kept: Input = {};\n const computed: Input = {};\n for (const field in stamps)\n if (raw[field] === undefined && takes?.[field] === undefined) {\n const value = stamps[field];\n // A value computed where the row is written is no data to admit; a\n // parameter is the call's one instant.\n (value instanceof InsertValue ? computed : kept)[field] =\n value instanceof Parameter ? scope!.instant() : value;\n }\n // Admitted as the caller's own would be, where there is something to admit.\n let written: Input = {};\n if (Object.keys(kept).length > 0)\n written =\n kind === \"create\"\n ? schema.createValues(model, kept)\n : schema.update(model, kept);\n source = { ...admitted };\n for (const field in kept) source[field] = written[field];\n Object.assign(source, computed);\n }\n const values = schema.scalars(model, source);\n // A field kept as stored is not written.\n for (const field in values)\n if (values[field] instanceof Stored) delete values[field];\n return values;\n }\n /**\n * What a row of `model` takes instead of going, where its model keeps the\n * rows it deletes; none where it removes them.\n */\n marks(model: AnyModel): Input | undefined {\n return this.operation.scope?.rows.tombstones?.marks(this, model);\n }\n /**\n * Among the rows that still reference a kept row, the one the call reaches\n * it through restricts nothing: its link is kept, where a removal would\n * have taken it first.\n */\n referenced(member: Question[\"member\"], of?: Input): Question[\"referenced\"] {\n return this.operation.scope!.rows.tombstones!.referenced(\n this.operation.schema,\n member?.edge,\n of\n );\n }\n /** What a kept row is refused with where a row still references it as the database would refuse its removal. */\n restriction(model: AnyModel): PreparedGuardFailure | undefined {\n return this.operation.scope!.rows.tombstones!.restriction(\n this.operation.schema,\n model\n );\n }\n /** A row the call created still holds what the database decided of it: asked where a later unit, on its own, writes that into other rows. */\n still(model: AnyModel, values: Input): Statement {\n const probe = this.#q.select(model, { take: 1 }, undefined, {\n projection: this.projection(model, false),\n selector: this.#q.prepareSelector(model, values, false),\n }).sql;\n return {\n model,\n sql: this.asserts(probe, \"exists\"),\n probe,\n premise: \"exists\",\n stops: {\n kind: \"query\",\n message: `Created record '${nameOf(model)}' changed across a generated-output segment boundary.`,\n raceable: false,\n },\n };\n }\n /** Whether `row` travels in the statement that inserts `count` rows of these `columns`: the same columns, within what the provider binds in one statement. */\n beside(\n model: AnyModel,\n columns: readonly string[],\n count: number,\n row: Input\n ): boolean {\n let fields = 0;\n for (const field in row) if (field !== columns[fields++]) return false;\n // A row of defaults only is a statement of its own.\n if (fields === 0 || fields !== columns.length) return false;\n const bound = this.operation.driver.maxBindParametersPerStatement;\n if (bound === undefined) return true;\n return (\n (count + 1) * fields +\n (this.#q.domain?.judge?.binds(this.#q, model) ?? 0) <=\n bound\n );\n }\n /** Rows of `model`; where the call may not create one, the statement refuses it, in the name of `relation` where they are created through one. */\n insert(\n model: AnyModel,\n values: Input[],\n relation?: string,\n returns?: PreparedProjection,\n beside?: readonly string[],\n skips = false\n ): Statement | Promise<Statement> {\n return after(this.computed(model, values), (rows) => {\n const q = this.#q;\n const { capabilities, mutations } = this.adapter;\n const fields = Object.keys(rows[0]!);\n const judged = q.domain?.judge?.inserted(\n q,\n this.operation,\n model,\n fields,\n rows,\n relation\n );\n // Rows that hold what another row alone may hold are passed by.\n const skip = skips\n ? mutations.skipDuplicates(q.columnName(model, fields[0]!))\n : undefined;\n // A row that states nothing is the database's to fill.\n const written =\n fields.length > 0\n ? mutations.insert(\n q.table(model),\n fields.map((field) => q.columnName(model, field)),\n judged\n ? { select: judged.probe }\n : rows.map((row) =>\n fields.map((field) =>\n q.fieldValue(model, field, row[field])\n )\n ),\n skip?.prefix\n )\n : mutations.insertDefault(q.table(model));\n const insert = skip?.suffix ? sql`${written} ${skip.suffix}` : written;\n return {\n model,\n // It answers with the row it wrote, where the provider returns what it wrote.\n sql:\n returns && capabilities.supportsReturning\n ? this.operation.answering(\n model,\n insert,\n returns,\n // With what the database decides of the row beside, where the call needs both.\n beside ? q.lowerProjection(this.fields(model, beside)) : []\n )\n : insert,\n ...judged,\n };\n });\n }\n /**\n * The rows a question names take `values`: the rows `keys` names, where the\n * call knows them. The statement refuses the rows it would leave where the\n * call may not leave them so.\n */\n update(\n question: Question,\n values: Input,\n keys?: readonly Input[],\n projection?: PreparedProjection,\n counted = !keys\n ): Statement | Promise<Statement> {\n const { model } = question;\n return after(this.computed(model, [values]), ([set]) => {\n const q = this.#q;\n const limit = keys ? undefined : question.limit;\n const { mutations } = this.adapter;\n // A value read of rows the statement joins: each row takes its own.\n const joined = Object.values(values).find(\n (value): value is JoinedValue => value instanceof JoinedValue\n );\n const selector = this.selector(question, keys);\n const judged = this.judged(question);\n let stops: PreparedGuardFailure | undefined;\n const statement = this.#answered(\n model,\n () => {\n const produced =\n judged &&\n q.domain?.judge?.updated(\n q,\n this.operation,\n question,\n (alias) => this.#among(question, selector, alias),\n set!,\n judged,\n limit\n );\n stops = produced?.stops;\n const named: { where?: Sql; suffix?: Sql } =\n produced || this.#limited(question, selector, keys);\n const sets = this.#sets(model, set!);\n const join = joined?.join(\n q.spelling(model, this.operation.driver.dialect),\n tableOf(model)\n );\n return [\n join\n ? mutations.updateFrom(\n q.table(model),\n sets,\n q.settleRows(join.source),\n join.on,\n named.where\n )\n : mutations.update(q.table(model), sets, named.where),\n named.suffix,\n ];\n },\n projection,\n counted\n );\n return { model, sql: statement, stops };\n });\n }\n /**\n * The key the database will compute of the row `key` names, asked of the\n * row before it is written, where no write says what it wrote: the row is\n * held until then.\n */\n computes(question: Question, key: Input, set: Input): Statement | undefined {\n const q = this.#q;\n const { model } = question;\n const { capabilities, identifiers } = this.adapter;\n if (capabilities.supportsReturning) return undefined;\n const table = tableOf(model);\n const { where } = this.#limited(question, this.selector(question, [key]), [\n key,\n ]);\n // The row as its write will leave its key, read as any row is.\n const columns = this.operation.schema.keys(model).map((field) => {\n const column = q.column(model, field, table);\n const value =\n field in set ? q.updateValue(model, field, set[field], column) : column;\n return identifiers.aliased(value, q.columnName(model, field));\n });\n const source = \"__viborm_computed\";\n const read = q.select(model, {}, undefined, {\n projection: this.projection(model, false),\n source,\n });\n return {\n model,\n sql: sql`${this.adapter.cte.with([\n {\n name: source,\n query: assembleAdapterSelect(this.adapter, {\n columns: listed(columns),\n from: q.table(model),\n where,\n forUpdate: true,\n }),\n },\n ])} ${read.sql}`,\n };\n }\n /**\n * The rows a question names are removed: the rows `keys` names, where the\n * call knows them. With `projection`, it answers with them as they were.\n */\n remove(\n question: Question,\n keys?: readonly Input[],\n projection?: PreparedProjection,\n counted = !keys\n ): Statement {\n const { model } = question;\n const selector = this.selector({ ...question, intent: \"delete\" }, keys);\n return {\n model,\n sql: this.#answered(\n model,\n () => {\n const named = this.#limited(question, selector, keys);\n return [\n this.adapter.mutations.delete(this.#q.table(model), named.where),\n named.suffix,\n ];\n },\n projection,\n counted\n ),\n };\n }\n /**\n * The row a question names by one of its model's keys takes `set`; where\n * there is none, `row` is created. It answers with the row as `projection`\n * says.\n */\n either(\n question: Question,\n row: Input,\n set: Input,\n projection: PreparedProjection,\n marker?: Sql\n ): Statement | Promise<Statement> {\n const { model } = question;\n return after(this.insert(model, [row]), (insert) => {\n const q = this.#q;\n const { identifiers, mutations, set: assignments } = this.adapter;\n const table = tableOf(model);\n const conflict = mutations.onConflict(\n listed(\n this.selector(question).uniqueKey!.fields.map((field) =>\n identifiers.escape(q.columnName(model, field))\n )\n ),\n mutations.onConflictUpdate(\n listed(\n Object.entries(set).map(([field, value]) =>\n assignments.assign(\n q.column(model, field),\n q.updateValue(\n model,\n field,\n value,\n q.column(model, field, table)\n )\n )\n )\n )\n )\n );\n return {\n model,\n sql: this.operation.answering(\n model,\n sql`${insert.sql} ${conflict}`,\n projection,\n marker ? [identifiers.aliased(marker, \"__viborm_inserted\")] : []\n ),\n };\n });\n }\n /** Whether the call's writes of the rows a question names are judged beyond what it may see. */\n judges(question: Question): boolean {\n return Boolean(\n this.judged(question) &&\n this.operation.scope?.rows.domain.rules?.has(nameOf(question.model))\n );\n }\n /**\n * A statement that stops its unit, with `stops`, where a row answers the\n * question; of a strict question, where a row the call may see is not one\n * it may write so.\n */\n none(\n question: Question,\n stops: PreparedGuardFailure = typeof question.strict === \"string\"\n ? {\n kind: \"nestedWrite\",\n relation: question.member!.edge.name,\n message: question.strict,\n raceable: false,\n }\n : this.absent(question)\n ): Statement {\n const { model, strict } = question;\n const probe = this.#q.select(\n model,\n { take: 1 },\n this.membership(question),\n {\n projection: this.projection(model, false),\n selector: this.selector(\n strict ? { ...question, intent: undefined } : question\n ),\n ...(strict && {\n unless: this.#q.domainOf(model, \"related\", this.judged(question)),\n }),\n }\n ).sql;\n return {\n sql: this.asserts(probe, \"notExists\"),\n probe,\n premise: \"notExists\",\n stops,\n model,\n };\n }\n /** What the row a question names holds of `field`, as a statement reads it. */\n located(question: Question, field: string): Sql {\n return this.#q.locatedValue(question.model, field, this.selector(question));\n }\n /** One row read by its key, as `projection` says. */\n one(model: AnyModel, key: Input, projection: PreparedProjection): Query {\n return this.#q.select(model, {}, undefined, { identity: key, projection });\n }\n /** The links of `from`'s row through a junction go: the one to `to`, or every one but those to the rows `kept`. */\n unlink(\n edge: Junction,\n from: Input,\n to: Input | undefined,\n kept: readonly Input[]\n ): Statement {\n const q = this.#q;\n const { identifiers, mutations, operators, subqueries } = this.adapter;\n const named = (side: Junction[\"sourceSide\"], row: Input) =>\n Object.fromEntries(\n side.members.map((pair) => [\n pair.junctionField,\n row[pair.referencedField],\n ])\n );\n const own = named(edge.sourceSide, from);\n // Every link but those kept: of the rows the call may take out, and no other.\n const domain = to\n ? undefined\n : q.domainOf(edge.target, \"related\", linkJudgement(edge));\n const seen = q.alias();\n return {\n model: edge.source,\n sql: mutations.delete(\n identifiers.table(edge.table),\n operators.and(\n q.junctionWhere(edge, {\n ...own,\n ...(to && named(edge.targetSide, to)),\n }),\n ...kept.map((row) =>\n operators.not(\n q.junctionWhere(edge, { ...own, ...named(edge.targetSide, row) })\n )\n ),\n ...(domain\n ? [\n operators.exists(\n subqueries.existsCheck(\n q.table(edge.target, seen),\n operators.and(\n ...edge.targetSide.members.map((pair) =>\n operators.eq(\n identifiers.column(edge.table, pair.junctionField),\n q.column(edge.target, pair.referencedField, seen)\n )\n ),\n q.lowerSelector(domain, seen)!\n )\n )\n ),\n ]\n : [])\n )\n ),\n };\n }\n /** Whether the database refused a row for the key a selector names. */\n refusedFor(\n model: AnyModel,\n key: NonNullable<PreparedSelector[\"uniqueKey\"]>,\n error: UniqueConstraintError\n ): boolean {\n const table = tableOf(model);\n const columns = key.fields.map((field) => this.#q.columnName(model, field));\n const constraints = adapterConstraints(this.adapter);\n const { meta } = error;\n // A database whose refusals name no constraint says which columns it found.\n if (!constraints)\n return meta.table === table && meta.columns?.join() === columns.join();\n const expected = (\n key.kind === \"primary\"\n ? constraints.primaryKey(table, columns)\n : constraints.unique(table, key.name ?? columns[0]!, columns)\n ).normalizedError;\n return (\n meta.table === expected.table &&\n meta.constraint === expected.constraint &&\n meta.columns?.join() === expected.columns?.join()\n );\n }\n /** Whether an insert that passes by a row whose key is taken says, for one row, that it did. */\n get passes(): boolean {\n return false;\n }\n /** Whether a write says what it wrote. */\n get says(): boolean {\n return this.adapter.capabilities.supportsReturning;\n }\n /** Whether a write of rows by their keys says how many of them it found: MySQL counts the rows an update changed. */\n counts(kind: string): boolean {\n return kind === \"delete\" || this.operation.driver.dialect !== \"mysql\";\n }\n /** What opens and closes the place a unit keeps the keys the database decides in it. */\n scratch(\n id: string,\n model: AnyModel\n ): { open: Statement[]; close: Statement } {\n const { batchRefs } = getAdapterInternals(this.adapter);\n return {\n open: batchRefs.setup(id).map((statement) => ({ sql: statement, model })),\n close: { sql: batchRefs.cleanup(id), model },\n };\n }\n /**\n * An insert that keeps the one key the database decides of its row where\n * the statements after it in its unit read it, and what they read. None\n * where the provider keeps no such key exactly.\n */\n kept(\n scratch: string,\n name: string,\n fields: readonly string[],\n insert: Statement\n ): { statements: Statement[]; value: Sql } | undefined {\n const { batchRefs } = getAdapterInternals(this.adapter);\n const { model } = insert;\n const [field] = fields;\n const state = scalarsOf(model)[field!]?.[\"~\"].state;\n if (\n fields.length !== 1 ||\n state?.autoGenerate?.kind !== \"increment\" ||\n !batchRefs.storeInsertedKey\n )\n return undefined;\n const [producing, ...storing] = batchRefs.storeInsertedKey(\n scratch,\n name,\n insert.sql,\n this.adapter.identifiers.escape(this.#q.columnName(model, field!))\n );\n return {\n statements: [\n { ...insert, sql: producing! },\n ...storing.map((statement) => ({ sql: statement, model })),\n ],\n value: this.adapter.expressions.cast(\n batchRefs.read(scratch, name),\n state.type === \"bigint\" ? \"bigint\" : \"integer\"\n ),\n };\n }\n /** The key of a row of `model`, as a statement answers with it. */\n key(model: AnyModel): PreparedProjection {\n return this.projection(model, false);\n }\n /** Fields a statement returned, as the call holds them. */\n told(model: AnyModel, fields: readonly string[], rows: Input[]): Input[] {\n return rows.length > 0 && fields.length > 0\n ? (this.#q.decodeProjection(\n this.fields(model, fields).shape,\n rows,\n true\n ) as Input[])\n : [];\n }\n /** The keys a statement returned, as the call holds them. */\n keys(model: AnyModel, rows: Input[]): Input[] {\n return rows.length > 0\n ? (this.#q.decodeProjection(\n this.projection(model, false).shape,\n rows,\n true\n ) as Input[])\n : [];\n }\n /** How many rows a set write that answers so wrote. */\n count(sent: Sent): number {\n return this.adapter.capabilities.countsCascadedChanges\n ? sent.rows.length\n : sent.rowCount;\n }\n /**\n * What a link a model holds takes beside the two rows it joins: the model's\n * defaults and what was written of it, `through`; and what one that is there\n * takes of what was written. Refused where the link cannot be filled, or\n * where a write of its model is judged or observed.\n */\n protected async linked(\n edge: Junction,\n columns: readonly string[],\n through?: Input\n ): Promise<{ row: Input; sets?: Input }> {\n const { schema, scope, attribution } = this.operation;\n const model = edge.declared!.model;\n const name = nameOf(model);\n const beside = schema.linkFields(model, columns);\n const missing = beside.required.filter(\n (field) => through?.[field] === undefined\n );\n if (missing.length > 0)\n throw new NestedWriteError(\n `Cannot link relation '${edge.name}': '${name}' requires ${missing.map((field) => `$through.${field}`).join(\", \")}, which a link cannot fill.`,\n edge.name\n );\n const sink = writeSinks.get(attribution);\n // A written column is a write to the model: what would judge or observe a direct write refuses it.\n if (\n through &&\n (this.#q.domain?.restrictsLinkWrite(this.#q, model) ||\n scope?.rows.stamps?.has(name) ||\n sink?.wants(name, \"create\") ||\n sink?.wants(name, \"update\"))\n )\n unsupported(\n `Cannot write $through of relation '${edge.name}': this client's extensions judge or observe writes to '${name}'. Write the row through the '${name}' delegate.`\n );\n return {\n row: {\n ...schema.createValues(\n model,\n Object.fromEntries(\n beside.defaults\n .filter((field) => !(through && field in through))\n .map((field) => [field, undefined])\n )\n ),\n ...through,\n },\n sets:\n through && Object.keys(through).length > 0\n ? (\n await this.computed(model, [\n schema.scalars(model, schema.update(model, through)),\n ])\n )[0]\n : undefined,\n };\n }\n /**\n * The links that make each second row a member of the first one's through\n * a junction, added where they are not there. A link a model holds is a row\n * of that model: it takes the model's defaults and what was written of it,\n * `through`, and one that is there takes what was written. Where one side\n * holds a single link, the link that side holds takes the other row.\n */\n async link(\n edge: Junction,\n pairs: readonly (readonly [Input, Input])[],\n through?: Input\n ): Promise<Statement[]> {\n const { identifiers, mutations, set } = this.adapter;\n const { uniqueSide, declared } = edge;\n const members = linkMembers(edge);\n const columns = members.map(({ pair }) => pair.junctionField);\n const rows = pairs.map((pair) =>\n members.map(({ side, pair: member }) =>\n this.#q.fieldValue(\n side.model,\n member.referencedField,\n pair[side === edge.sourceSide ? 0 : 1][member.referencedField]\n )\n )\n );\n let takes: Sql | undefined;\n const model = declared?.model;\n const own = model && (await this.linked(edge, columns, through));\n if (model && own) {\n for (const [field, value] of Object.entries(own.row)) {\n columns.push(this.operation.schema.physicalField(model, field).name);\n for (const row of rows)\n row.push(this.#q.fieldValue(model, field, value));\n }\n takes = own.sets && this.#sets(model, own.sets);\n }\n const table = identifiers.table(edge.table);\n const side = (name: \"source\" | \"target\") =>\n edge[`${name}Side`].members.map((pair) => pair.junctionField);\n const other =\n uniqueSide && side(uniqueSide === \"source\" ? \"target\" : \"source\");\n return rows\n .flatMap((row) =>\n other\n ? // The link that side holds takes the other row, unless it holds it.\n mutations.insertAbsent(\n table,\n columns,\n [row],\n side(uniqueSide!),\n listed(\n other.map((column) =>\n set.assign(\n identifiers.escape(column),\n row[columns.indexOf(column)]!\n )\n )\n ),\n this.adapter.operators.and(\n ...other.map((column) =>\n this.adapter.operators.eq(\n identifiers.column(edge.table, column),\n row[columns.indexOf(column)]!\n )\n )\n )\n )\n : []\n )\n .concat(\n other\n ? []\n : mutations.insertAbsent(\n table,\n columns,\n rows,\n declared?.key ?? members.map(({ pair }) => pair.junctionField),\n takes\n )\n )\n .map((statement) => ({ sql: statement, model: edge.source }));\n }\n}\n","/**\n * The image: what one call believes of the rows it touches.\n *\n * The verbs ask it questions and tell it writes, as if it were the database\n * and answered at once. A question it can answer from what it knows is\n * answered from memory. One it cannot is noted, and answered with nothing;\n * the noted questions are then read together, and the verbs run again from\n * the start. Writes are noted, and sent at the end as one unit, behind the\n * statements that stop it where what the call believed no longer holds.\n *\n * What the image cannot know — rows a set write changed, rows the database\n * changed with a row the call removed or renamed, a filter only the database\n * evaluates over a row the call wrote — follows one rule: what is noted is\n * sent, then the question is asked.\n *\n * A unit that stops writes nothing. Where it stopped on a row the call took\n * to be there, that row's question is asked for real and the verbs run\n * again: it is the verbs that refuse, of an image that is right.\n */\nimport {\n NestedWriteError,\n NotFoundError,\n TransactionError,\n UniqueConstraintError,\n UnsupportedOperationError,\n} from \"@errors\";\nimport { type AnyModel, getModelKeyCatalog } from \"@schema/model\";\nimport type { Sql } from \"@sql\";\nimport { createFailureError } from \"../../batch-error-attribution\";\nimport type { PreparedGuardFailure } from \"../../types\";\nimport { type WriteKind, type WriteWatch, writeSinks } from \"../../write-sinks\";\nimport { InsertValue, JoinedValue } from \"../shared/insert-value\";\nimport {\n type PreparedProjection,\n type Query,\n readUpdate,\n returningSafeProjection,\n} from \"../shared/query\";\nimport type { EngineSchema, Input } from \"../shared/schema\";\nimport type { SqlOperationContext } from \"../shared/sql-operation-context\";\nimport { hopFieldsOf, type Membership } from \"../shared/storage\";\nimport { nameOf, same, scalarsOf } from \"../shared/terms\";\nimport {\n refusedBy,\n type Sent,\n type Statement,\n Stopped,\n type Transport,\n} from \"./send\";\nimport { after, type Junction, type Question, Writer } from \"./statements\";\n\n/** A row the call knows: what it holds, as far as the call knows it. */\nexport type Row = Input;\n\n/** What the call read without holding is no longer so: the call may be made again in another unit, or fails with `failure`. */\nexport class Lost {\n readonly failure: unknown;\n constructor(failure: unknown) {\n this.failure = failure;\n }\n}\n\ninterface Meta {\n readonly model: AnyModel;\n /** The question that found it, where one did. */\n readonly question?: Question;\n /** The call creates it. */\n made?: true;\n /** Where the call notes that it creates it. */\n at?: number;\n /** Nothing is known of it but its key: it was taken to be there. */\n partial?: true;\n /** It was taken to be there by values that are not its key: the question that names it. */\n readonly named?: string;\n /** The call removed it. */\n gone?: true;\n /** The call changed its key. */\n moved?: true;\n /** What it held before the call gave it another key. */\n stood?: Input;\n /** The database passed it by: it was one too many. */\n passed?: true;\n /** The fields the call wrote of it, once it wrote one. */\n wrote?: Set<string>;\n /** Of a row the call creates: what is written of a field where the row is created, where that is not what the row holds since. */\n born?: Input;\n /** How many rows the statement that created it said it wrote: of rows written side by side, said of the first. */\n inserted?: number;\n}\n\n/** What a set write says once it is sent. */\nexport interface Later {\n sent?: Sent;\n /** Of a row created where none was found, else updated: which it was, where something asked. */\n created?: boolean;\n}\n\n/**\n * A value the database decides, of a row the call wrote: known once the\n * statement that writes the row is heard.\n */\nclass Pending {\n readonly row: Row;\n readonly field: string;\n /** Where the call notes the write that decides it. */\n readonly at: number;\n /** What the database will compute, written as it will compute it, where the call knows what it computes it of. */\n readonly spell?: () => unknown;\n /** No write of the call decides it: it is what the row holds, never heard and always written as what reads it. */\n readonly named: boolean;\n readonly #name: string;\n constructor(\n row: Row,\n field: string,\n name: string,\n at: number,\n spell?: () => unknown,\n named = false\n ) {\n this.row = row;\n this.field = field;\n this.#name = name;\n this.at = at;\n this.spell = spell;\n this.named = named;\n }\n toString(): string {\n return this.#name;\n }\n}\nconst UNHEARD = Symbol(\"a value the database has not said yet\");\n/** The first row of a part undone alone was passed by: another row holds what it alone may hold. */\nconst PASSED = Symbol(\"a row the database passed by\");\n/** A value as text, whatever numbers it holds. */\nconst text = (value: unknown): string =>\n JSON.stringify(value, (_, each) =>\n typeof each === \"bigint\" ? `${each}n` : each\n );\n/** Thrown where a call that must be one unit is more than one. */\nexport const SEVERAL = Symbol(\"more than one unit\");\n\n/** One thing noted: what it writes when its unit is sent, and where its answer is told. */\ntype Entry = (\n | {\n readonly kind: \"insert\";\n readonly row: Row;\n readonly relation?: string;\n /** The fields of its key the database decides. */\n readonly decided: readonly string[];\n }\n | {\n readonly kind: \"update\";\n readonly row: Row;\n /** The row's key as the write finds it. */\n readonly key: Input;\n readonly set: Input;\n /** The fields of its key the database computes by this write. */\n readonly hears: readonly string[];\n readonly question: Question;\n }\n | {\n readonly kind: \"delete\";\n readonly row: Row;\n readonly key: Input;\n readonly question: Question;\n }\n | {\n readonly kind: \"all\";\n readonly question: Question;\n readonly set?: Input;\n readonly projection?: PreparedProjection;\n }\n | {\n /** Rows created at once: `passes`, only where none holds what one of them alone may hold. */\n readonly kind: \"skipping\";\n readonly model: AnyModel;\n readonly rows: readonly Input[];\n readonly projection?: PreparedProjection;\n readonly passes: boolean;\n }\n | {\n /** The row a question names takes `set`; where there is none, `row` is created. */\n readonly kind: \"either\";\n readonly question: Question;\n readonly row: Input;\n readonly set: Input;\n readonly projection: PreparedProjection;\n /** What says, of the row answered, that the statement created it. */\n readonly marker?: Sql;\n }\n | {\n readonly kind: \"link\";\n readonly edge: Junction;\n readonly from: Row;\n readonly to: Row;\n readonly keys: readonly [Input, Input];\n /** What was written of the link itself, where a model holds it. */\n readonly through?: Input;\n }\n | {\n readonly kind: \"unlink\";\n readonly edge: Junction;\n readonly from: Row;\n readonly to?: Row;\n readonly kept: readonly Row[];\n readonly keys: readonly [Input, Input | undefined, Input[]];\n }\n | {\n readonly kind: \"none\";\n readonly question: Question;\n readonly stops?: PreparedGuardFailure;\n /** What the call read, and goes on from: where it no longer holds, the call runs again. */\n readonly believed?: true;\n }\n | {\n readonly kind: \"read\";\n readonly model: AnyModel;\n readonly rows: readonly Row[];\n /** Of one row, read as this says: the statement that writes the row may answer it. */\n readonly projection?: PreparedProjection;\n readonly queries: () => Query[];\n }\n) & {\n take?(sent: Sent[], queries?: Query[]): void;\n /** The part of the unit it is written in, where that part is undone alone if its first row is refused: `root` on that row's own write. */\n attempt?: number;\n root?: boolean;\n};\n\n/** Statements of a unit, written when it is sent, and where their answers are told. */\ninterface Step {\n write(): Statement[] | Promise<Statement[]>;\n take?(sent: Sent[]): void;\n attempt?: number;\n root?: boolean;\n /** Whether it writes. */\n writes?: boolean;\n /** Its answer says whether a row the call took to be there is: heard before anything more is written. */\n confirms?: boolean;\n}\n\ninterface Answer {\n readonly question: Question;\n readonly rows: Input[];\n}\n\n/** The relations of `model` whose rows hold its key. */\nconst holders = (schema: EngineSchema, model: AnyModel) =>\n model[\"~\"].relationNames.flatMap((name) => {\n if (\"members\" in schema.index.get(model)!.get(name)!.edge) return [];\n const edge = schema.membership(model, name);\n return edge.kind === \"reference\" && edge.owner === \"target\" ? [edge] : [];\n });\n/** The models whose rows the database changes with a row of `model` that goes, or takes another key. */\nconst dependents = new WeakMap<AnyModel, Set<AnyModel>>();\nfunction dependentsOf(schema: EngineSchema, model: AnyModel): Set<AnyModel> {\n let found = dependents.get(model);\n if (!found) {\n found = new Set();\n dependents.set(model, found);\n for (const edge of holders(schema, model)) {\n found.add(edge.target);\n for (const further of dependentsOf(schema, edge.target))\n found.add(further);\n }\n }\n return found;\n}\n\nconst NONE: string[] = [];\n/** The step of a statement that only asks. */\nconst STILL: Step = { write: () => [] };\n/** The fields of a model the database decides where a row leaves them out: its key, and what it counts for the row. */\nconst decidables = new WeakMap<AnyModel, readonly string[]>();\nfunction decidable(schema: EngineSchema, model: AnyModel): readonly string[] {\n let fields = decidables.get(model);\n if (!fields) {\n const scalars = scalarsOf(model);\n fields = [\n ...new Set([\n ...schema.keys(model),\n ...schema\n .storedFields(model)\n .filter(\n (field) =>\n scalars[field]?.[\"~\"].state.autoGenerate?.kind === \"increment\"\n ),\n ]),\n ];\n decidables.set(model, fields);\n }\n return fields;\n}\n\nexport class Store {\n readonly operation: SqlOperationContext;\n readonly writer: Writer;\n /** What watches this run of the call's writes, where something asked to see rows. */\n readonly watch: WriteWatch | undefined;\n readonly #transport: Transport;\n /** What the database answered, by question: kept from one run of the verbs to the next. */\n #answers: Map<string, Answer> | undefined;\n /** The questions asked for real: a run needed more of their row than its key, or the row was not there. */\n #concrete: Set<string> | undefined;\n /** What a run made once and every later run takes again: a row's own copy of what the caller wrote. */\n #copies: Map<string, unknown> | undefined;\n /** How much of what the verbs note is sent already, and what the database said of it. */\n #sent = 0;\n #delivered = 0;\n #heard: Map<number, Sent[]> | undefined;\n /** The rows taken to be there that a unit asked for already, where rows are held. */\n #asserted: Set<string> | undefined;\n /** How many times what the call wrote was made before the call ended. */\n segments = 0;\n /** Everything the call writes was sent: what fails after is its answer. */\n said = false;\n #members: number[] = [];\n /** A row as the statement that read it whole said it. */\n #raw: WeakMap<Input, Input> | undefined;\n // Made where a call first needs them: most calls are one write that knows no row.\n #meta: WeakMap<Row, Meta> | undefined;\n #known: Map<string, Row> | undefined;\n #log: Entry[] = [];\n #missed: Map<string, { question?: Question; after: number }> | undefined;\n /** Whether each part undone alone was written, once sent; and the part being noted. */\n #outcomes: Map<number, boolean> | undefined;\n #attempting: number | undefined;\n #presumed:\n | Map<string, { question: Question; row?: Row; at: number }>\n | undefined;\n #used: Map<Answer, number> | undefined;\n /** What the database may hold of a model beyond what the call knows: every field of its rows, or those named. */\n #stale = new Map<AnyModel, Set<string> | true>();\n /** The models the call wrote a row of, and the junctions it wrote a link of. */\n #touched = new Set<AnyModel | string>();\n #again = false;\n /** The value a statement being written waits for the database to say. */\n #waited: Pending | undefined;\n /** The verbs ran on this store already: what a run noted is put away before the next. */\n #ran = false;\n #made = 0;\n /** The call's unit is handed over: what the call hears of it comes too late to stop it. */\n #handed = false;\n constructor(operation: SqlOperationContext, transport: Transport) {\n this.operation = operation;\n this.#transport = transport;\n this.writer = new (operation.backend?.writer ?? Writer)(\n operation,\n // Given to the writer as it is made: a function stored in it afterwards keeps the whole call from the next collection.\n transport.holds ? (sql, model) => this.#hear({ sql, model }) : undefined\n );\n this.watch = writeSinks.get(operation.attribution)?.attempt();\n }\n /** Asks the database in the call's unit, once what was written before is sent. */\n #hear = async (statement: Statement): Promise<Input[]> =>\n (await this.#transport.send([statement], false))[0]!.rows;\n /** Runs the verbs on the image the store holds: their answer, or none where the database must say more first. */\n #settle<T>(work: () => () => T): (() => T) | undefined {\n for (;;) {\n // A store begins as a run leaves it to the next.\n if (this.#ran) {\n this.#meta = undefined;\n this.#known = undefined;\n this.#log = [];\n this.#missed = undefined;\n this.#presumed = undefined;\n this.#used = undefined;\n this.#stale = new Map();\n this.#touched = new Set();\n this.#again = false;\n this.#made = 0;\n this.#members = [];\n this.#says = [];\n this.#absences = [];\n this.#left = undefined;\n }\n this.#ran = true;\n let answer: (() => T) | undefined;\n let refused: { error: unknown } | undefined;\n try {\n answer = work();\n } catch (error) {\n refused = { error };\n }\n // What a run refuses on an image that could not answer it says nothing.\n if (this.#again) continue;\n if (this.#missed?.size) return;\n if (refused) throw refused.error;\n return answer!;\n }\n }\n /** Runs the verbs until they ran on an image that could answer them, once the database said what the first run missed. */\n async #learnt<T>(work: () => () => T): Promise<() => T> {\n for (;;) {\n await this.#learn();\n const answer = this.#settle(work);\n if (answer) return answer;\n }\n }\n /**\n * Runs the verbs, then sends what they wrote. `work` answers how the\n * call's answer is read once its writes are sent.\n */\n async run<T>(work: () => () => T): Promise<T> {\n for (let races = 0; ; ) {\n try {\n // Most calls are answered by their first run: no tick is spent waiting for it.\n const answer = this.#settle(work) ?? (await this.#learnt(work));\n const [only] = this.#log;\n // A call that is one write naming its rows itself, and that took nothing for granted, is sent as it is.\n if (\n this.#log.length === 1 &&\n (only!.kind === \"all\" ||\n only!.kind === \"skipping\" ||\n only!.kind === \"either\") &&\n only!.attempt === undefined &&\n !(this.#presumed?.size || this.#used?.size || this.#sent)\n ) {\n const whole = this.#whole(only as never);\n const sent = await this.#transport.send(\n whole instanceof Promise ? await whole : whole,\n true\n );\n this.said = true;\n this.#sent = 1;\n // What was written outside a unit the call can undo is made, where a row was written.\n if (\n this.#transport.loose &&\n sent.some((each) => each.rowCount > 0 || each.rows.length > 0)\n )\n this.segments++;\n only!.take?.(sent);\n return answer();\n }\n await this.#deliver(this.#steps(this.#log.length), true);\n return answer();\n } catch (error) {\n if (error instanceof Lost) throw error;\n if (!(error instanceof Stopped))\n throw this.#says.reduce((failure, say) => say(failure), error);\n const { stops, believed, model } = error.statement;\n // The call may not leave the row it would write, a row that must be\n // there is not, or what it wrote before cannot be taken back.\n if (!believed || this.#delivered > 0)\n throw createFailureError(\n stops!,\n nameOf(model),\n this.operation.operation\n );\n // What the call took for granted is asked for real; what it read is read again.\n if (believed === \"presumed\")\n for (const id of this.#presumed?.keys() ?? [])\n (this.#concrete ??= new Set()).add(id);\n // Only a unit that holds nothing of what it reads asks again what it read: it plans again on what the database says now, three times at most.\n else if (++races > 3)\n throw new NotFoundError(nameOf(model), this.operation.operation);\n else this.#answers = undefined;\n this.#asserted = undefined;\n this.#outcomes = undefined;\n this.#sent = 0;\n }\n }\n }\n /** Runs the verbs, and hands their unit over instead of sending it. */\n async prepare<T>(work: () => () => T) {\n this.#handed = true;\n const answer = this.#settle(work) ?? (await this.#learnt(work));\n const written: { statements: Statement[]; step: Step }[] = [];\n try {\n for (const step of this.#steps(this.#log.length))\n written.push({ statements: await step.write(), step });\n } catch (error) {\n // None of its statements may wait for what the database says.\n throw error === UNHEARD ? SEVERAL : error;\n }\n return {\n statements: written.flatMap((entry) => entry.statements),\n answer: (sent: readonly Sent[]) => {\n let at = 0;\n for (const { statements, step } of written) {\n step.take?.(sent.slice(at, at + statements.length));\n at += statements.length;\n }\n return answer();\n },\n };\n }\n /**\n * One unit of reads: the questions the last run could not answer, the\n * first of them. Those asked of what the call wrote are read once what it\n * noted before them is sent.\n */\n async #learn(): Promise<void> {\n const after = Math.min(\n ...[...(this.#missed?.values() ?? [])].map((missed) => missed.after)\n );\n // Before a unit handed over, only the call's own row may be looked for: found, the unit asks for it again; not found, the key it is created under refuses a row that came since.\n if (\n this.#handed &&\n [...(this.#missed?.values() ?? [])].some(\n ({ question, after: asked }) =>\n asked > 0 ||\n !question?.unique ||\n question.must ||\n question.through ||\n question.member\n )\n )\n throw SEVERAL;\n const steps = after > this.#sent ? this.#steps(after) : [];\n // Questions that each name one row of a model, sought the same way, are one statement.\n const groups = new Map<string, [string, Question][]>();\n const pins = (question: Question) =>\n question.unique && !(question.member || question.limit)\n ? this.writer.selector(question).uniqueValues\n : undefined;\n const group = (question: Question) =>\n pins(question) &&\n text([\n nameOf(question.model),\n question.through?.name,\n question.intent,\n question.writes,\n question.makes,\n ]);\n for (const [id, { question, after: asked }] of this.#missed ?? []) {\n if (asked !== after || !question) continue;\n const key = group(question) || id;\n groups.set(key, [...(groups.get(key) ?? []), [id, question]]);\n }\n // A row taken to be there is read with them rather than asked for after.\n for (const [id, { question, row }] of this.#presumed ?? []) {\n const together = row && groups.get(group(question) || \"\");\n if (together) together.push([id, question]);\n }\n /** A question asked of the row it is asked of as the database has said it by then. */\n const told = ({ member, ...question }: Question): Question => ({\n ...question,\n member: member && { ...member, of: this.#said(member.of) },\n });\n for (const asked of groups.values()) {\n const [[, first]] = asked as [[string, Question]];\n const { model } = first;\n let query: Query;\n /** What each question of the group is answered with, once heard. */\n let found: [string, Question, Input[]][] | undefined;\n const take = ([sent]: Sent[]) => {\n const rows = this.operation.queries.decodeQuery(query, sent!.rows);\n for (const [at, row] of rows.entries())\n (this.#raw ??= new WeakMap()).set(row, sent!.rows[at]!);\n const before = found;\n found = asked.map(([id, question]) => [\n id,\n question,\n asked.length === 1\n ? rows\n : rows.filter((row) =>\n [...pins(question)!].every(([field, value]) =>\n same(row[field], value)\n )\n ),\n ]);\n for (const [id, question, answer] of found)\n (this.#answers ??= new Map()).set(id, { question, rows: answer });\n return before;\n };\n // A place where the call would make a row is not held where holding it holds the place of a row that is not there: two calls holding it would wait on each other.\n const loose =\n this.#transport.holds &&\n first.makes === true &&\n this.writer.adapter.capabilities.locksMissingKeys === true;\n steps.push({\n // Asked of the row it is asked of as the database has said it by then.\n write: () => {\n query = this.writer.read(\n asked.map(([, question]) => told(question)),\n this.#transport.holds && !loose\n );\n return [{ sql: query.sql, model }];\n },\n take,\n });\n // The rows found there are read again by their keys, and held: the call goes on with what they hold from then on.\n if (loose)\n steps.push({\n write: () => {\n if (!found) throw UNHEARD;\n const again = found\n .filter(([, , rows]) => rows.length > 0)\n .map(([, question, rows]) => ({\n ...told(question),\n only: rows.map((row) =>\n this.operation.schema.identity(model, row)\n ),\n again: true,\n }));\n if (again.length === 0) return [];\n query = this.writer.read(again, true);\n return [{ sql: query.sql, model }];\n },\n take: (sent) => {\n if (sent.length === 0) return;\n const before = take(sent)!;\n // A row that no longer answers: what the call read is no longer so.\n if (\n found!.some(\n ([, , rows], at) => rows.length < before[at]![2].length\n )\n )\n throw new Lost(this.#absent(first, true));\n },\n });\n }\n await this.#deliver(steps, false);\n this.#delivered = this.#sent;\n }\n #name(model: AnyModel, values: Input): string {\n const keys = this.operation.schema.keys(model);\n // A row of a model without a key is no other row the call knows.\n if (keys.length === 0) return `${nameOf(model)}#${++this.#made}`;\n // An instant names its row the same as a `Date` and as the text the engine writes of it.\n return `${nameOf(model)}:${keys\n .map((field) => {\n const value = values[field];\n return value instanceof Date ? value.toISOString() : String(value);\n })\n .join(\"|\")}`;\n }\n /** What a row holds that makes other rows its members through a relation: asked of the row as it stands now, whatever the call writes of it next. */\n #of({ edge, of }: NonNullable<Question[\"member\"]>): Input {\n // What a link holds of the row: its key, or the fields the junction references of it.\n return Object.fromEntries(\n [\n ...new Set([\n ...(edge.kind === \"reference\"\n ? []\n : this.operation.schema.keys(edge.source)),\n ...hopFieldsOf(edge),\n ]),\n ].map((field) => [field, of[field]])\n );\n }\n /** What the call holds of a row it knows. */\n #about(row: Row) {\n return this.#meta?.get(row) as Meta;\n }\n /** What refuses the call where the row a question names is not there. */\n #absent(question: Question, lost?: boolean) {\n return createFailureError(\n this.writer.absent(question, lost),\n nameOf(question.model),\n this.operation.operation\n );\n }\n /** A question as a statement asks it: of a row it names the members of, what only the database holds written as what reads it. */\n #asked<Q extends Question>(question: Q): Q {\n const { member } = question;\n return member\n ? {\n ...question,\n member: { ...member, of: this.#said(this.#of(member)) },\n }\n : question;\n }\n /** A row's key as it stands now. */\n #key(row: Row): Input {\n return this.operation.schema.identity(this.#about(row).model, row);\n }\n /** Values as a statement takes them: what the database decides must have been heard. */\n #said(values: Input): Input {\n const heard: Input = {};\n for (const field in values) {\n const value = values[field];\n const said = value instanceof Pending ? value.row[value.field] : value;\n // What cannot be heard before the unit goes on is written as the database will compute it.\n if (said instanceof Pending) {\n if (!said.named && (this.#transport.holds || !said.spell)) {\n this.#waited = said;\n throw UNHEARD;\n }\n heard[field] = said.spell!();\n } else if (said !== undefined) heard[field] = said;\n }\n return heard;\n }\n /** The one handle of a row, by its key. */\n #intern(model: AnyModel, values: Input, question?: Question): Row {\n const name = this.#name(model, values);\n let row = this.#known?.get(name);\n if (!row) {\n row = { ...values };\n (this.#known ??= new Map()).set(name, row);\n (this.#meta ??= new WeakMap()).set(row, { model, question });\n }\n return row;\n }\n /**\n * Whether a row the call knows answers a question now: `undefined` where\n * only the database can say. `was` says whether it answered before the\n * call wrote it, where that is known.\n */\n #holds(\n row: Row,\n question: Question,\n was: boolean | undefined\n ): boolean | undefined {\n const meta = this.#about(row);\n if (meta.gone) return false;\n const { member } = question;\n const selector = this.writer.selector(question);\n const { facts } = selector;\n const name = this.#name(meta.model, row);\n if (question.except?.some((key) => this.#name(meta.model, key) === name))\n return false;\n /** Whether the call wrote, of the row, a field the question reads. */\n const rewritten =\n meta.wrote !== undefined &&\n [...meta.wrote].some((field) => facts.fields.has(field));\n // A value the row holds that is not the one asked for: it does not answer, whose ever member it is. One spelled another way may be the one asked for: the database says.\n let unsure = false;\n for (const [field, value] of facts.equals) {\n if (!Object.hasOwn(row, field) || row[field] instanceof Pending) continue;\n const holds = this.operation.queries.told(\n meta.model,\n field,\n row[field],\n value\n );\n if (holds === false) return false;\n unsure ||= holds === undefined;\n }\n if (member?.edge.kind === \"reference\") {\n const { discriminator, pairs } = member.edge;\n // Of the variant the relation reaches.\n if (discriminator) {\n const holder = discriminator.side === \"target\" ? row : member.of;\n if (!(discriminator.field in holder)) return undefined;\n if (holder[discriminator.field] !== discriminator.value) return false;\n }\n for (const pair of pairs) {\n if (!(pair.target in row && pair.source in member.of)) return undefined;\n const [holds, held] = [row[pair.target], member.of[pair.source]];\n // A value only the database holds is the same as itself, and its to compare with any other.\n if (\n holds !== held &&\n (holds instanceof Pending || held instanceof Pending)\n )\n return undefined;\n if (!same(holds, held)) return false;\n }\n } else if (member) {\n const linked = this.#linked(member.edge as Junction, member.of, row);\n if (linked === false) return false;\n // A link the call did not make is the database's to say. A row that did not answer answers now only by what the call wrote of what the question reads.\n if (linked === undefined && !was)\n return was === false && !rewritten ? false : undefined;\n }\n for (const field of facts.equals.keys())\n if (row[field] instanceof Pending) return undefined;\n // Stated in full by what the call knows of the row.\n if (\n facts.exact &&\n !(selector.scoped || unsure) &&\n [...facts.equals.keys()].every((field) => field in row)\n )\n return true;\n // What the call wrote of it changes nothing the question reads: it answers as it did.\n if (was && !meta.made && facts.reads.size === 0 && !rewritten) return true;\n return undefined;\n }\n /** Whether the call itself linked or unlinked two rows through a junction: `undefined` where it did neither. */\n #linked(edge: Junction, from: Row, to: Row): boolean | undefined {\n let linked: boolean | undefined;\n for (const entry of this.#log) {\n if (!(entry.kind === \"link\" || entry.kind === \"unlink\")) continue;\n if (entry.edge.table !== edge.table) continue;\n const [a, b] =\n entry.edge.source === edge.source ? [from, to] : [to, from];\n const side = entry.edge.uniqueSide;\n if (entry.kind === \"link\") {\n if (entry.from === a && entry.to === b) linked = true;\n // The one link a row of that side holds took another row.\n else if (side === \"source\" ? entry.from === a : side && entry.to === b)\n linked = false;\n } else if (\n entry.from === a &&\n (entry.to === b || !(entry.to || entry.kept.includes(b)))\n )\n linked = false;\n }\n return linked;\n }\n /**\n * A question that names one row by its key, of a row that must be there,\n * is not asked: the row is taken to be there, with nothing known of it but\n * its key, and the unit that writes asks first. A run that reads more of\n * the row has the question asked for real.\n */\n #presume(id: string, question: Question): Row[] | undefined {\n const { schema } = this.operation;\n const { model } = question;\n const pins = this.writer.selector(question).uniqueValues;\n const keys = schema.keys(model);\n if (!(question.must && question.unique && pins) || this.#concrete?.has(id))\n return undefined;\n // A row named by values no other row has, that are not its key: its key is what the database holds of it, written wherever it is needed as what reads it there. Not of a member, nor where a write may not read the table it writes.\n const named = !keys.every((field) => pins.has(field));\n if (\n named &&\n (question.member ||\n question.through ||\n !this.writer.adapter.capabilities.supportsMutationTargetInSubquery)\n )\n return undefined;\n const key = Object.fromEntries(pins);\n const name = named ? `${id}` : this.#name(model, key);\n let row = this.#known?.get(name);\n if (!row) {\n const fields = schema.storedFields(model);\n const held: Row = { ...key };\n const partial: Row = new Proxy(held, {\n get: (target, field) => {\n if (\n typeof field === \"string\" &&\n fields.includes(field) &&\n !(field in target) &&\n this.#meta?.get(partial)?.partial\n ) {\n (this.#concrete ??= new Set()).add(id);\n this.#again = true;\n }\n return target[field as string];\n },\n });\n row = partial;\n if (named)\n for (const field of keys)\n if (!(field in held))\n held[field] = new Pending(\n partial,\n field,\n `@${++this.#made}`,\n this.#log.length,\n () => this.writer.located(question, field),\n true\n );\n (this.#known ??= new Map()).set(name, row);\n (this.#meta ??= new WeakMap()).set(row, {\n model,\n question,\n partial: true,\n named: named ? id : undefined,\n });\n }\n (this.#presumed ??= new Map()).set(id, {\n question,\n row,\n at: this.#log.length,\n });\n return [row];\n }\n /**\n * A question that names one row by values no other row has, of a row the\n * call knows by them: answered by what the call knows, where that says.\n * Where it does not say of a row the call wrote, only the database can,\n * once that is written: `true`.\n */\n #recalled(question: Question): Row[] | boolean {\n const { uniqueValues, facts } = this.writer.selector(question);\n // Named by a unique key alone, or by its own key beside what else is asked of it.\n const pins =\n uniqueValues ??\n (this.operation.schema\n .keys(question.model)\n .every((field) => facts.keys.has(field))\n ? facts.keys\n : undefined);\n if (!(question.unique && pins)) return false;\n for (const row of this.#known?.values() ?? []) {\n if (\n this.#about(row).model !== question.model ||\n ![...pins].every(\n ([field, value]) => field in row && same(row[field], value)\n )\n )\n continue;\n const answers = this.#holds(row, question, undefined);\n if (answers === undefined) return this.#changed(row);\n return answers ? [row] : [];\n }\n return false;\n }\n #changed(row: Row): boolean {\n const meta = this.#about(row);\n return Boolean(meta.made || meta.gone || meta.wrote);\n }\n /** Whether the database may hold, of the rows a question names, what the call does not know. */\n #spoiled(question: Question): boolean {\n const { model, member } = question;\n if (member && this.#meta?.get(member.of)?.moved) return true;\n const stale = this.#stale.get(model);\n if (stale === true) return true;\n const { facts } = this.writer.selector(question);\n return (\n (stale !== undefined &&\n (facts.reads.size > 0 ||\n [...stale].some((field) => facts.fields.has(field)) ||\n (member?.edge.kind === \"reference\" &&\n member.edge.pairs.some((pair) => stale.has(pair.target))))) ||\n // A filter that reads other rows reads what the call wrote of them.\n [...facts.reads].some(\n (read) => this.#touched.has(read) || this.#stale.has(read as AnyModel)\n )\n );\n }\n /** The database may hold what the call does not know of `model`: of `fields`, or of its rows whole. */\n #spoil(model: AnyModel, fields?: Iterable<string>): void {\n const stale = this.#stale.get(model);\n if (stale === true) return;\n if (!fields) this.#stale.set(model, true);\n else if (stale) for (const field of fields) stale.add(field);\n else this.#stale.set(model, new Set(fields));\n }\n /** Whether a question reads any of `fields` of the rows it names. */\n reads(question: Question, fields: readonly string[]): boolean {\n const { facts } = this.writer.selector(question);\n return fields.some((field) => facts.fields.has(field));\n }\n /** The rows a question names. */\n rows(question: Question): Row[] {\n this.writable(question);\n // The members of a row the call gave another key, where the database does not make them follow, are those it had under the key it had: asked as of then, ahead of what the call writes.\n const { member } = question;\n const stood = member && this.#meta?.get(member.of)?.stood;\n if (\n stood &&\n member.edge.kind === \"reference\" &&\n member.edge.owner === \"target\" &&\n member.edge.reference &&\n member.edge.reference.onUpdate !== \"cascade\"\n )\n return this.#rows(\n { ...question, member: { ...member, of: stood } },\n false\n );\n return this.#rows(question, this.#spoiled(question));\n }\n /** Whether the row a junction's members are members of says what its links hold of it: asked of the row, so a row known by its key alone is read. */\n #links(member: NonNullable<Question[\"member\"]>): boolean {\n const { edge, of } = member;\n return (\n edge.kind !== \"junction\" ||\n edge.sourceSide.members.every(\n (pair) => of[pair.referencedField] !== undefined\n )\n );\n }\n /** The keys the call moved a row away from: no row has one of them until the call makes one. */\n #left: Set<string> | undefined;\n #rows(question: Question, late: boolean): Row[] {\n const { model, member } = question;\n if (this.#left?.size && question.unique) {\n const pins = this.writer.selector(question).uniqueValues;\n const keys = this.operation.schema.keys(model);\n const name =\n pins &&\n keys.every((field) => pins.has(field)) &&\n this.#name(\n model,\n Object.fromEntries(keys.map((field) => [field, pins.get(field)]))\n );\n // Unless the call made a row under it since: the row that had it is known by its new key.\n const there = name ? this.#known?.get(name) : undefined;\n if (\n name &&\n this.#left?.has(name) &&\n !(there && this.#name(model, there) === name)\n )\n return [];\n }\n const fresh = member && this.#meta?.get(member.of)?.made;\n // What makes a row a member is read of the row it is a member of.\n if (member?.edge.kind === \"reference\" && !fresh)\n for (const pair of member.edge.pairs)\n if (member.of[pair.source] === undefined) return [];\n if (member && !this.#links(member)) return [];\n const after = late ? this.#log.length : 0;\n const id = text([\n nameOf(model),\n question.where,\n question.unique,\n member && [\n member.edge.name,\n this.#name(member.edge.source, member.of),\n // What makes a row a member, where the row it is a member of holds it.\n member.edge.kind === \"reference\" && [\n ...member.edge.pairs.map((pair) => String(member.of[pair.source])),\n member.edge.discriminator?.side === \"source\" &&\n member.of[member.edge.discriminator.field],\n ],\n ],\n question.intent,\n question.writes,\n question.through?.name,\n question.limit,\n question.except?.map((key) => this.#name(model, key)),\n after,\n question.joined && 1,\n ]);\n // The members of a row the call creates are the rows it made members itself.\n const answer =\n fresh && !late ? { question, rows: [] } : this.#answers?.get(id);\n if (!answer) {\n const recalled = !late && this.#recalled(question);\n if (recalled === true) return this.#rows(question, true);\n // What the call recalls of a row it only read is asked again where its writes are sent, where nothing held what it read.\n const read = Array.isArray(recalled)\n ? recalled.filter((row) => !this.#changed(row))\n : [];\n if (read.length > 0)\n (this.#used ??= new Map()).set(\n { question, rows: read },\n this.#log.length\n );\n const known = recalled || (!late && this.#presume(id, question));\n if (known) return known;\n // Asked of the row as it stands now, whatever the call writes of it next.\n (this.#missed ??= new Map()).set(id, {\n question: member\n ? { ...question, member: { ...member, of: this.#of(member) } }\n : question,\n after,\n });\n return [];\n }\n if (!(fresh || this.#used?.has(answer)))\n (this.#used ??= new Map()).set(answer, this.#log.length);\n const read = new Set(\n answer.rows.map((values) => {\n const row = this.#intern(model, values, question);\n const meta = this.#about(row);\n const raw = (this.#raw ??= new WeakMap());\n raw.set(row, raw.get(values)!);\n // A row taken to be there, now read: what the call wrote of it stands.\n if (meta.partial) {\n Object.assign(row, { ...values, ...row });\n meta.partial = undefined;\n }\n // As the database says it, once what the call wrote is sent.\n if (late) Object.assign(row, values);\n return row;\n })\n );\n const rows = [...read];\n if (late) return rows;\n // What the call wrote since may answer now, or no longer.\n for (const row of this.#known?.values() ?? []) {\n const meta = this.#about(row);\n if (meta.model !== model) continue;\n const linked =\n member?.edge.kind === \"junction\" &&\n this.#linked(member.edge, member.of, row) !== undefined;\n if (!(this.#changed(row) || linked)) continue;\n const answers = this.#holds(row, question, read.has(row));\n // Only the database can say: once what the call noted is sent.\n if (answers === undefined) return this.#rows(question, true);\n if (answers && !read.has(row)) rows.push(row);\n if (!answers && read.has(row)) rows.splice(rows.indexOf(row), 1);\n }\n return rows;\n }\n /** Whether rows of `model` the call deletes are kept, and marked. */\n keeps(model: AnyModel): boolean {\n return this.writer.marks(model) !== undefined;\n }\n /** The one row a question names, which must be there. */\n one(question: Question): Row {\n const missed = this.#missed?.size ?? 0;\n const [row] = this.rows({ ...question, must: true });\n // A question not answered yet says nothing: the verbs go on, on a row of which nothing is known.\n if (!row && (this.#missed?.size ?? 0) > missed) {\n const unknown: Row = {};\n (this.#meta ??= new WeakMap()).set(unknown, {\n model: question.model,\n question,\n });\n return unknown;\n }\n if (!row) throw this.#absent(question);\n return row;\n }\n /** What a row of `model` takes where it is created or updated, beside what the caller wrote of it. */\n values(\n model: AnyModel,\n kind: \"create\" | \"update\",\n admitted: Input,\n raw: Input = {}\n ): Input {\n return this.writer.values(model, kind, admitted, raw);\n }\n /** Notes a write, told what the database said of it where a run before this one sent it. */\n #note(entry: Entry): void {\n entry.attempt = this.#attempting;\n if (\"row\" in entry && entry.kind !== \"either\")\n this.#touched.add(this.#about(entry.row).model);\n else if (entry.kind === \"skipping\") this.#touched.add(entry.model);\n else if (\"edge\" in entry) this.#touched.add(entry.edge.table);\n const place = this.#log.push(entry) - 1;\n const heard = this.#heard?.get(place);\n if (heard) entry.take?.(heard);\n }\n /** A row created: what was admitted of what the caller wrote of it, and what it `takes` of the rows it references. */\n insert(\n model: AnyModel,\n admitted: Input,\n raw?: Input,\n relation?: string,\n takes?: Input\n ): Row {\n const row: Row = this.writer.values(model, \"create\", admitted, raw, takes);\n if (takes) Object.assign(row, takes);\n // What the database decides of the row is known once its statement is heard: a key it leaves out, a value computed where it is written.\n let computed: Input | undefined;\n for (const field in row)\n if (row[field] instanceof InsertValue)\n (computed ??= {})[field] = row[field];\n // Most rows are written with all the database would decide of them.\n let decided = NONE;\n for (const field of decidable(this.operation.schema, model))\n if (row[field] === undefined)\n (decided === NONE ? (decided = []) : decided).push(field);\n if (computed)\n for (const field in computed)\n (decided === NONE ? (decided = []) : decided).push(field);\n for (const field of decided)\n row[field] = new Pending(\n row,\n field,\n `@${++this.#made}`,\n this.#log.length\n );\n // A row created under a key another has is the database's to refuse.\n const name = this.#name(model, row);\n if (!this.#known?.has(name)) (this.#known ??= new Map()).set(name, row);\n const meta: Meta = {\n model,\n made: true,\n at: this.#log.length,\n born: computed,\n };\n (this.#meta ??= new WeakMap()).set(row, meta);\n this.#note({\n kind: \"insert\",\n row,\n relation,\n decided,\n take: ([sent]) => {\n meta.inserted = sent!.rowCount;\n // Where its statement said what the database decided of it.\n const [raw] = sent!.rows;\n const [said] =\n raw && decided.every((field) => field in raw)\n ? this.writer.told(model, decided, sent!.rows)\n : [];\n for (const field of decided)\n if (row[field] instanceof Pending && (said || sent!.insertId))\n row[field] = said?.[field] ?? sent!.insertId;\n },\n });\n if (relation !== undefined) this.#seen(row, \"create\");\n return row;\n }\n /**\n * A row the call writes through a relation is shown to what asked to see\n * such rows: read whole where the call's writes stand when this is said.\n */\n #seen(row: Row, kind: WriteKind): void {\n const { model } = this.#about(row);\n const name = nameOf(model);\n const { watch } = this;\n if (!watch?.wants(name, kind)) return;\n const q = this.operation.queries;\n const projection = q.prepareProjection(model, {});\n this.read(row, projection, (rows) =>\n watch.shows(name, kind, q.decodeProjection(projection.shape, rows))\n );\n }\n /** The question a write of one row the call knows is written under: what found it, and what the write is. */\n #writing(row: Row, write: Partial<Question>): Question {\n const { model, question } = this.#about(row);\n return {\n model,\n // What the row was found by: said again by its first write where nothing holds what the call read.\n where: question?.where,\n member: question?.member,\n through: question?.through,\n verb: question?.verb,\n ...write,\n };\n }\n /** The rows of other models the database changes with a row of `model` are its to say. */\n #cascades(model: AnyModel): void {\n for (const other of dependentsOf(this.operation.schema, model))\n this.#spoil(other);\n }\n /**\n * The rows the call knows that reference `row` by what it held `before`\n * hold what it holds now, where the database makes them follow: and so do\n * the rows that reference those.\n */\n #follow(row: Row, before: Row): void {\n const { schema } = this.operation;\n const { model } = this.#about(row);\n for (const edge of holders(schema, model)) {\n if (\n edge.reference?.onUpdate !== \"cascade\" ||\n // What the row does not hold, no write of the call gave it.\n edge.pairs.every(\n (pair) =>\n !Object.hasOwn(row, pair.source) ||\n before[pair.source] === row[pair.source]\n )\n )\n continue;\n for (const child of [...(this.#known?.values() ?? [])]) {\n const meta = this.#about(child);\n if (\n meta.model !== edge.target ||\n !edge.pairs.every(\n (pair) =>\n Object.hasOwn(child, pair.target) &&\n same(child[pair.target], before[pair.source])\n )\n )\n continue;\n const was = { ...child };\n for (const pair of edge.pairs) {\n child[pair.target] = row[pair.source];\n (meta.wrote ??= new Set()).add(pair.target);\n }\n if (schema.keys(meta.model).some((key) => was[key] !== child[key])) {\n (this.#known ??= new Map()).set(this.#name(meta.model, child), child);\n meta.moved = true;\n }\n this.#follow(child, was);\n }\n }\n }\n /**\n * A row takes `set`: `writes` says what the caller wrote of it, `joined` the\n * relation it is made a member of, or leaves, by this write, and `of` the\n * row it is made a member of.\n */\n update(\n row: Row,\n set: Input,\n writes?: readonly string[],\n joined?: Membership,\n removes = false,\n of?: Row\n ): void {\n if (Object.keys(set).length === 0) return;\n const meta = this.#about(row);\n const { model } = meta;\n const key = this.#key(row);\n const keys = this.operation.schema.keys(model);\n // A row named by what it holds is no longer named so once the call writes that, or its key: it is read.\n if (\n meta.named !== undefined &&\n Object.keys(set).some(\n (field) =>\n keys.includes(field) ||\n this.writer.selector(meta.question!).uniqueValues?.has(field)\n )\n ) {\n (this.#concrete ??= new Set()).add(meta.named);\n this.#again = true;\n }\n const hears: string[] = [];\n const before = { ...row };\n let computed = false;\n for (const field in set) {\n const value = set[field];\n const update =\n value instanceof Pending\n ? { kind: \"value\" as const, value }\n : readUpdate(value);\n (meta.wrote ??= new Set()).add(field);\n // What the database computes of a row is its to say; so is what a row written after it decides. A row the call creates is written first as it stood.\n const made = meta.at ?? Number.POSITIVE_INFINITY;\n const later =\n (update.kind === \"value\" &&\n update.value instanceof Pending &&\n update.value.at > made) ||\n // So is what it holds of a row the call creates after it: that row is not there when this one is inserted.\n (of !== undefined && (this.#meta?.get(of)?.at ?? -1) > made);\n if (update.kind !== \"value\" || later) {\n const stood = row[field];\n // Of a row the call creates only.\n if (\n meta.made &&\n !(\n (meta.born && field in meta.born) ||\n (stood instanceof Pending && stood.row === row)\n )\n )\n (meta.born ??= {})[field] = stood;\n computed = true;\n }\n if (update.kind === \"value\") row[field] = update.value;\n else {\n const stood = row[field];\n const q = this.operation.queries;\n row[field] = new Pending(\n row,\n field,\n `@${++this.#made}`,\n this.#log.length,\n stood === undefined || stood instanceof Pending\n ? undefined\n : () =>\n q.updateValue(\n model,\n field,\n value,\n q.fieldValue(model, field, stood)\n )\n );\n if (keys.includes(field)) hears.push(field);\n }\n }\n if (\n keys.some(\n (field) =>\n field in set &&\n (row[field] instanceof Pending || !same(row[field], before[field]))\n )\n )\n meta.stood ??= before;\n // A row is known by the key it has now: the key it had names no row the call knows of.\n if (keys.some((field) => field in set)) {\n (this.#left ??= new Set()).add(this.#name(model, before));\n (this.#known ??= new Map()).set(this.#name(model, row), row);\n meta.moved = true;\n this.#cascades(model);\n }\n this.#follow(row, before);\n // A row the call creates is inserted as it stands in the end.\n if (meta.made && !computed) return;\n this.#note({\n kind: \"update\",\n row,\n key,\n set,\n hears,\n question: this.#writing(\n row,\n joined\n ? { intent: \"join\", through: joined }\n : removes\n ? { intent: \"delete\" }\n : { intent: \"update\", writes }\n ),\n take: ([sent]) => {\n if (hears.length === 0) return;\n const [said] = this.writer.keys(model, sent!.rows);\n // A write that is to say the key it gave its row says it, or wrote no row.\n if (!said) throw this.#absent(meta.question ?? { model });\n for (const field of hears) row[field] = said[field];\n },\n });\n // A kept row that goes is seen as the update it is.\n if (meta.question?.verb) this.#seen(row, \"update\");\n }\n /** A row is removed: marked, where its model keeps the rows it deletes. */\n delete(row: Row): void {\n const meta = this.#about(row);\n const { model, question } = meta;\n const marks = this.writer.marks(model);\n // As it was before it goes.\n if (question?.verb && !marks) this.#seen(row, \"delete\");\n if (marks) {\n // A kept row leaves the rows that reference it in place: where the database would have refused its removal, the mark is refused too.\n const stops = this.writer.restriction(model);\n const through = question?.member;\n if (stops)\n this.none(\n {\n model,\n where: this.#key(row),\n unique: true,\n intent: \"delete\",\n referenced: this.writer.referenced(\n through,\n through && this.#key(through.of)\n ),\n },\n stops\n );\n this.update(row, marks, undefined, undefined, true);\n meta.gone = true;\n return;\n }\n meta.gone = true;\n const made = this.#log.findIndex(\n (entry) => entry.kind === \"insert\" && entry.row === row\n );\n // A row the call created and has not sent is not created.\n if (made >= this.#sent) {\n this.#log.splice(made, 1);\n return;\n }\n this.#note({\n kind: \"delete\",\n row,\n key: this.#key(row),\n question: this.#writing(row, { intent: \"delete\" }),\n });\n this.#cascades(meta.model);\n }\n /** Every row a question names takes `set`, or is removed where there is none: the call does not need to know them. */\n all(question: Question, set?: Input, projection?: PreparedProjection): Later {\n const { model } = question;\n if (question.member) this.#links(question.member);\n const q = this.operation.queries;\n const name = nameOf(model);\n const kind = set ? \"update\" : \"delete\";\n // Rows written through a relation are shown whole to what asked to see them.\n const watched =\n question.verb && this.watch?.wants(name, kind)\n ? q.prepareProjection(model, {})\n : undefined;\n const returns = projection ?? watched;\n const marks = set ? undefined : this.writer.marks(model);\n const stops = marks && this.writer.restriction(model);\n const later: Later = {};\n // Where no statement both writes rows and answers with them so, they are\n // read, then written by their keys; and so are rows that are kept where\n // one may be refused: the rows asked of are the rows written.\n const { member } = question;\n const referenced =\n stops && this.writer.referenced(member, member && this.#key(member.of));\n // Rows that need not be known are held, not read: nothing comes to reference them between what is asked and what is written. So it is in a unit handed over, which nothing comes between.\n const held =\n stops && !(this.#handed || member || question.limit !== undefined);\n if (\n marks\n ? watched || (stops && !(this.#handed || held))\n : returns &&\n !this.operation.answersInStatement(model, returns, kind, set)\n ) {\n // A value read from a table the write joins names the rows written: no other is asked for.\n const joined =\n set &&\n Object.values(set).find(\n (value): value is JoinedValue => value instanceof JoinedValue\n );\n const rows = this.rows(joined ? { ...question, joined } : question);\n const take = (read: Input[]) => {\n later.sent = { rows: read, rowCount: read.length };\n };\n const answer = () =>\n projection\n ? this.series(model, rows, projection, \"updateMany\", take)\n : take(rows);\n // Rows that go answer as they were; rows that are written or kept, as that leaves them.\n if (!(set || marks)) answer();\n if (stops && rows.length > 0)\n this.none(\n {\n model,\n only: rows.map((row) => this.#key(row)),\n intent: \"delete\",\n referenced,\n },\n stops\n );\n for (const row of rows)\n if (marks) {\n this.update(row, marks, undefined, undefined, true);\n this.#about(row).gone = true;\n } else if (set)\n this.update(\n row,\n set,\n question.writes,\n undefined,\n question.intent === \"delete\"\n );\n else this.delete(row);\n if (set || marks) answer();\n return later;\n }\n if (marks) {\n // Unless the rows are read ahead of their marks: they are held as they are read.\n if (\n held &&\n this.#transport.holds &&\n this.writer.adapter.capabilities.supportsRowLocks &&\n !(\n returns &&\n !this.operation.answersInStatement(model, returns, \"update\", marks)\n )\n )\n this.#note({\n kind: \"read\",\n model,\n rows: [],\n queries: () => [\n this.operation.scope!.rows.tombstones!.lock(\n q,\n this.writer.selector({ ...question, intent: \"delete\" })\n ),\n ],\n });\n if (stops)\n this.none(\n { ...question, must: undefined, intent: \"delete\", referenced },\n stops\n );\n return this.all(question, marks, projection);\n }\n this.writable(question);\n // A row that must be there is asked for where what the write says of it comes too late.\n if (question.must && this.#handed)\n (this.#presumed ??= new Map()).set(`all:${this.#log.length}`, {\n question,\n row: undefined,\n at: this.#log.length,\n });\n this.#note({\n kind: \"all\",\n question,\n set,\n projection: returns,\n take: ([sent]) => {\n later.sent = sent;\n if (watched)\n this.watch!.shows(\n name,\n kind,\n q.decodeProjection(watched.shape, sent!.rows)\n );\n },\n });\n this.#spoil(model, set && Object.keys(set));\n if (!set) this.#cascades(model);\n return later;\n }\n /**\n * The row a question names takes `set`; where there is none, a row is\n * created of what was `admitted`. None where no one statement says so.\n */\n either(\n question: Question,\n admitted: Input,\n raw: Input,\n set: Input,\n projection: PreparedProjection\n ): Later | undefined {\n const { model } = question;\n const q = this.operation.queries;\n const { capabilities } = this.writer.adapter;\n const selector = this.writer.selector(question);\n const pins = selector.uniqueValues;\n const row = this.values(model, \"create\", admitted, raw);\n const fields = Object.keys(set);\n if (\n !(\n capabilities.supportsTargetedUpsert &&\n capabilities.supportsReturning &&\n selector.uniqueKey &&\n pins\n ) ||\n selector.scoped ||\n q.domain?.judge?.produced(model) ||\n fields.length === 0 ||\n this.operation.schema.keys(model).some((key) => key in set) ||\n // The row created is the one the question would name.\n !selector.uniqueKey.fields.every(\n (field) =>\n (row[field] === null || typeof row[field] !== \"object\") &&\n Object.is(row[field], pins.get(field))\n ) ||\n !fields.every((field) => q.namesUpdate(model, field, set[field])) ||\n !this.operation.answersInStatement(model, projection, \"update\", set)\n )\n return undefined;\n const later: Later = {};\n // Which of the two it was is told to what asked: by the statement itself where the provider marks a row it created, else by asking for the row just before it.\n const name = nameOf(model);\n const asked =\n this.watch?.wants(name, \"create\") || this.watch?.wants(name, \"update\");\n const marker =\n asked && returningSafeProjection(projection)\n ? this.writer.adapter.mutations.upserted\n : undefined;\n let created: boolean | undefined;\n if (asked && !marker)\n this.#note({\n kind: \"read\",\n model,\n rows: [],\n queries: () => [this.writer.read([question], false)],\n take: ([sent]) => {\n created = sent!.rows.length === 0;\n },\n });\n this.#note({\n kind: \"either\",\n question,\n row,\n set,\n projection,\n marker,\n take: ([sent]) => {\n later.sent = sent;\n for (const said of marker ? sent!.rows : []) {\n created = said.__viborm_inserted === true;\n said.__viborm_inserted = undefined;\n }\n later.created = created;\n },\n });\n this.#spoil(model);\n return later;\n }\n /** `to` is made a member of `from`'s through a junction: `through` is what was written of the link itself. */\n link(edge: Junction, from: Row, to: Row, through?: Input): void {\n const source = this.#end(edge.sourceSide, from);\n const target = this.#end(edge.targetSide, to);\n // One column of a link holds one value: where both rows supply it, they supply the same, or the call is refused before anything is written.\n for (const pair of edge.sourceSide.members) {\n const other = edge.targetSide.members.find(\n (each) => each.junctionField === pair.junctionField\n );\n if (!other) continue;\n const a = source[pair.referencedField];\n const b = target[other.referencedField];\n const known = (value: unknown) =>\n !(value === undefined || value instanceof Pending);\n if (known(a) && known(b) && !same(a, b))\n throw new NestedWriteError(\n `Cannot link relation '${edge.name}': the two rows hold different values for '${pair.junctionField}'.`,\n edge.name,\n { meta: { field: pair.junctionField, relation: edge.name } }\n );\n }\n this.#note({\n kind: \"link\",\n edge,\n from,\n to,\n keys: [source, target],\n through,\n });\n }\n /**\n * What a link holds of the row at one of its ends: the fields the junction\n * references there, which are the row's key or values no other row has.\n * Asked of the row, so a row known by its key alone is read.\n */\n #end(side: Junction[\"sourceSide\"], row: Row): Input {\n return Object.fromEntries(\n side.members.map((pair) => [\n pair.referencedField,\n row[pair.referencedField],\n ])\n );\n }\n /** `from`'s links through a junction go: the one to `to`, or every one but those to the rows `kept`. */\n unlink(edge: Junction, from: Row, to?: Row, kept: readonly Row[] = []): void {\n this.#note({\n kind: \"unlink\",\n edge,\n from,\n to,\n kept,\n keys: [\n this.#end(edge.sourceSide, from),\n to && this.#end(edge.targetSide, to),\n kept.map((row) => this.#end(edge.targetSide, row)),\n ],\n });\n }\n /** Of a strict question, no row the call may see may be one it may not write so, when its writes reach here. */\n writable(question: Question): void {\n if (question.strict && this.writer.judges(question))\n this.#note({ kind: \"none\", question });\n }\n /** No row may answer the question when the call's writes reach here: `stops` refuses it. */\n none(question: Question, stops: PreparedGuardFailure): void {\n if (question.member) this.#links(question.member);\n this.#note({ kind: \"none\", question, stops });\n }\n /** The call goes on as no row answers the question: asked again where its writes are sent, where nothing held what it read. */\n absent(question: Question): void {\n if (!this.#transport.holds)\n this.#note({ kind: \"none\", question, believed: true });\n }\n /** A row read as `projection` says, where the call's writes stand when this is asked. */\n read(\n row: Row,\n projection: PreparedProjection,\n take: (rows: Input[]) => void\n ): void {\n const { model } = this.#about(row);\n const said = this.#told([row], projection);\n if (said) {\n take(said);\n return;\n }\n this.#note({\n kind: \"read\",\n model,\n rows: [row],\n projection,\n queries: () => [\n this.writer.one(model, this.#said(this.#key(row)), projection),\n ],\n take: ([sent]) => take(sent!.rows),\n });\n }\n /** What rows read whole have said of what is read of themselves alone, while the call has written nothing: a write of any row may change it where the database makes it follow. */\n #told(rows: readonly Row[], projection: PreparedProjection) {\n const said = rows.map((row) => this.#raw?.get(row));\n return said.every(Boolean) &&\n this.#log.every(\n (entry) => entry.kind === \"read\" || entry.kind === \"none\"\n ) &&\n projection.fields.every((field) => field.kind === \"scalar\")\n ? (said as Input[])\n : undefined;\n }\n /** Rows read by their keys as `projection` says, in their order, where the call's writes stand when this is asked. */\n series(\n model: AnyModel,\n rows: readonly Row[],\n projection: PreparedProjection,\n kind: \"createMany\" | \"updateMany\",\n take: (rows: Input[]) => void\n ): void {\n // A row the database passed by is no row of the call's.\n const there = rows.filter((row) => !this.#about(row).passed);\n const said = this.#told(there, projection);\n if (said) {\n take(said);\n return;\n }\n this.#note({\n kind: \"read\",\n model,\n rows: there,\n projection,\n queries: () =>\n this.operation.seriesQueries(\n projection,\n there.map((row) => this.#said(this.#key(row))),\n kind\n ),\n take: (sent, queries) => {\n // A read-back owes its write every row it names: fewer is the write's refusal.\n for (const [at, query] of (queries ?? []).entries()) {\n const expected = query.expectedRows;\n if (!expected || sent[at]!.rows.length >= expected.count) continue;\n // A row taken to be there, read before anything said it was: the read says it is not.\n for (const { question, row } of this.#presumed?.values() ?? [])\n if (row && there.includes(row))\n throw new Stopped({\n sql: query.sql,\n model,\n stops: this.writer.absent(question),\n believed: \"presumed\",\n });\n throw expected.missing;\n }\n take(sent.flatMap((each) => each.rows));\n },\n });\n }\n /** What the call says of a failure of its writes, where it knows more of it than the database says. */\n #says: ((failure: unknown) => unknown)[] = [];\n saying(say: (failure: unknown) => unknown): void {\n this.#says.push(say);\n }\n /** The keys rows were created under because the call found none there. */\n #absences: {\n model: AnyModel;\n key: NonNullable<ReturnType<Writer[\"selector\"]>[\"uniqueKey\"]>;\n }[] = [];\n /** A row is created under the key a question named, because none answered it. */\n created(question: Question): void {\n const key = this.writer.selector(question).uniqueKey;\n if (key) this.#absences.push({ model: question.model, key });\n }\n /** Whether a failure is the database refusing such a row for its key: another writer made it since. */\n raced(failure: unknown): boolean {\n return (\n failure instanceof UniqueConstraintError &&\n this.#absences.some(({ model, key }) =>\n this.writer.refusedFor(model, key, failure)\n )\n );\n }\n /** A row of the call's own rows begins: what is written until the next is its. */\n member(): void {\n this.#members.push(this.#log.length);\n }\n /** How many of the call's own rows are written, where what the call sent before it failed stands: of a call that writes one row, that row; `series` counts the rows of a call that writes several, and none of one that writes one. */\n members(series = false): number {\n if (series && this.#members.length === 0) return 0;\n const ends = [...this.#members.slice(1), this.#log.length];\n return ends.filter((end) => end <= this.#sent).length;\n }\n /** Refuses where no part of the call's unit can be undone alone. */\n attempts(rows: string): void {\n // A unit handed over hears nothing of its parts: it cannot be one unit.\n if (this.#handed) throw SEVERAL;\n if (!this.#transport.attempt)\n throw new UnsupportedOperationError(\n `skipDuplicates cannot skip ${rows} on driver '${this.operation.driver.driverName}' in this scope; a member savepoint is required.`,\n { meta: { operation: this.operation.operation } }\n );\n }\n /**\n * A row created, with what hangs on it, unless the database refuses the row\n * for holding what another row alone may hold: then nothing of it is\n * written, and the call goes on. Answers whether it was written.\n */\n attempt(work: () => Row, rows: string): boolean {\n this.attempts(rows);\n const from = this.#log.length;\n this.#attempting = from;\n let made: Row;\n try {\n made = work();\n } finally {\n this.#attempting = undefined;\n }\n const part = this.#log.slice(from);\n const root = part.find(\n (entry) => entry.kind === \"insert\" && entry.row === made\n );\n if (root) root.root = true;\n const written = this.#outcomes?.get(from);\n // Only the database can say: once the part is sent.\n if (written === undefined) {\n (this.#missed ??= new Map()).set(`attempt:${from}`, {\n after: this.#log.length,\n });\n return true;\n }\n if (!written)\n for (const entry of part) {\n if (entry.kind !== \"insert\") continue;\n const meta = this.#about(entry.row);\n Object.assign(meta, { gone: true, passed: true });\n // The row that has its key is the one the database holds.\n const name = this.#name(meta.model, entry.row);\n if (this.#known?.get(name) === entry.row) this.#known?.delete(name);\n }\n return written;\n }\n /** How many of the rows the call created the database said it wrote. */\n written(rows: readonly Row[]): number {\n let count = 0;\n for (const row of rows) count += this.#meta?.get(row)?.inserted ?? 0;\n return count;\n }\n /** The call's unit is handed over. */\n get handed(): boolean {\n return this.#handed;\n }\n /**\n * Rows created where no row holds what one of them alone may hold: the\n * others are passed by, and the call does not know which. Each is what was\n * admitted of it, what the caller wrote of it, and what it takes of the\n * rows it references.\n */\n skipping(\n model: AnyModel,\n rows: readonly (readonly [Input, Input, Input?])[],\n projection?: PreparedProjection,\n passes = true\n ): Later | undefined {\n // None where no one statement passes such rows by, or answers with those it wrote.\n if (\n (passes &&\n this.writer.adapter.mutations.skipDuplicatesStrategy !== \"sql\") ||\n (projection &&\n !this.operation.answersInStatement(model, projection, \"insert\"))\n )\n return undefined;\n const later: Later = {};\n this.#note({\n kind: \"skipping\",\n model,\n rows: rows.map(([admitted, raw, takes]) =>\n Object.assign(\n this.writer.values(model, \"create\", admitted, raw, takes),\n takes\n )\n ),\n projection,\n passes,\n take: (sent) => {\n const said = sent.flatMap((each) => each.rows);\n later.sent = {\n rows: said,\n rowCount: projection\n ? said.length\n : sent.reduce((count, each) => count + each.rowCount, 0),\n };\n },\n });\n this.#spoil(model);\n return later;\n }\n /** What one run makes of `make` is what every later run takes: a row's own copy of what the caller wrote. */\n copy<T>(name: string, make: () => T): T {\n const copies = (this.#copies ??= new Map());\n if (!copies.has(name)) copies.set(name, make());\n return copies.get(name) as T;\n }\n /**\n * The steps of a unit, up to what was noted before `to`: what the call\n * believed must still hold, then every write not sent yet, in order. Rows\n * written the same way side by side travel in one statement.\n */\n #steps(to: number): Step[] {\n const { writer } = this;\n const { schema } = this.operation;\n const { holds } = this.#transport;\n const steps: Step[] = [];\n /** The entry whose steps are being written: they are told apart as those of a part undone alone, and the write of its first row among them. */\n let current: Entry | undefined;\n const push = (step: Step) => {\n if (current) {\n step.attempt = current.attempt;\n step.root = current.root;\n step.writes = current.kind !== \"read\";\n }\n steps.push(step);\n };\n const log = this.#log;\n const last = to === log.length;\n /** Where this unit keeps the keys the database decides in it: it cannot hear them and go on. */\n let scratch: { id: string; model: AnyModel } | undefined;\n const span = log.slice(this.#sent, to);\n /** The rows of which other statements need what the database decides, and how many do. */\n const needed = new Map<Row, number>();\n const needs = (values: readonly (Input | undefined)[], own?: Row) => {\n let rows: Set<Row> | undefined;\n for (const each of values)\n if (each)\n for (const field in each) {\n const value = each[field];\n // What the database decides of a row is no need of the row's own write.\n if (value instanceof Pending && value.row !== own)\n (rows ??= new Set()).add(value.row);\n }\n if (rows)\n for (const row of rows) needed.set(row, (needed.get(row) ?? 0) + 1);\n };\n /** Whether a statement other than the read of a row needs what the database decides of it: its read needs it too where its key is the database's to say. */\n const wanted = (row: Row) =>\n (needed.get(row) ?? 0) >\n (Object.values(this.#key(row)).some((value) => value instanceof Pending)\n ? 1\n : 0);\n let writes = 0;\n // What is noted after this unit needs what the database decides in it too.\n for (let at = this.#sent; at < log.length; at++) {\n const entry = log[at]!;\n if (at < to && !(entry.kind === \"none\" || entry.kind === \"read\"))\n writes++;\n if (entry.kind === \"insert\") needs([entry.row], entry.row);\n else if (entry.kind === \"update\") needs([entry.key, entry.set]);\n else if (entry.kind === \"delete\") needs([entry.key]);\n else if (entry.kind === \"link\" || entry.kind === \"unlink\")\n needs([entry.keys[0], entry.keys[1], ...(entry.keys[2] ?? [])]);\n else if (entry.kind === \"read\")\n needs(entry.rows.map((row) => this.#key(row)));\n }\n // A unit after the first asks again of the rows the call has not written.\n const passed = (row: Row | undefined) =>\n this.#sent > 0 && row && this.#changed(row);\n /** The writes that say themselves whether the row they were taken to find is there. */\n const confirms = new Map<Entry, Question>();\n /** The rows taken to be there that one statement asks for: those sought the same way. */\n let asked: Map<string, [Question, (Input | Input[])?][]> | undefined;\n /** Adds a row to ask for to the statement that asks for those sought the same way. */\n const ask = (\n question: Question,\n own: string,\n believed: \"presumed\" | \"read\",\n key?: Input | Input[],\n place?: number,\n // In a unit that hears each answer, every row asked for is held; in one sent whole, the rows the unit gives another row a reference to.\n held = holds || question.intent === \"join\"\n ) => {\n const group = text([\n believed,\n nameOf(question.model),\n question.member ? own : question.through?.name,\n question.verb,\n question.intent,\n question.writes,\n place,\n held,\n ]);\n asked ??= new Map();\n if (!asked.has(group)) {\n const together: [Question, (Input | Input[])?][] = [];\n asked.set(group, together);\n push({\n write: () => [\n writer.asks(\n together.map(([each, key]) => [this.#asked(each), key]),\n believed,\n holds,\n held\n ),\n ],\n });\n }\n asked.get(group)!.push([question, key]);\n };\n /** The first write of each row, in the whole call. */\n let firsts: Map<Row, Entry> | undefined;\n const firstOf = (row: Row) => {\n if (!firsts) {\n firsts = new Map();\n for (const entry of log)\n if (\"row\" in entry && !firsts.has(entry.row))\n firsts.set(entry.row, entry);\n }\n return firsts.get(row);\n };\n /** The rows taken to be there after the unit began: each asked for at its place, in the order of their places. */\n const later: [number, () => void][] = [];\n /** Whether the unit writes, before a place, what may make a row the member a question says: the row it is a member of, or a link of its relation. */\n const made = (question: Question, at: number) =>\n question.member !== undefined &&\n log\n .slice(this.#sent, at)\n .some((entry) =>\n \"row\" in entry\n ? entry.row === question.member!.of\n : entry.kind === \"link\" &&\n question.member!.edge.kind === \"junction\" &&\n entry.edge.table === question.member!.edge.table\n );\n /** The rows taken to be there that this unit hears of, in the order the call took them. */\n const taken = [...(this.#presumed ?? [])].filter(\n ([id, { row, at }]) =>\n !(at > to || (holds ? this.#asserted?.has(id) : passed(row)))\n );\n // The first write of a row taken to be there says whether it is,\n // where nothing else is written if it is not.\n // A link of the row the call takes away before it writes the row is no longer there to say the row was a member.\n const says = taken.map(([, { row }]) => {\n const first = span.find(\n (entry) =>\n ((entry.kind === \"update\" || entry.kind === \"delete\") &&\n entry.row === row) ||\n (entry.kind === \"unlink\" && entry.to === row)\n );\n return first &&\n first.kind !== \"unlink\" &&\n writer.counts(first.kind) &&\n (holds || !(this.#handed || writes > 1))\n ? first\n : undefined;\n });\n // Where two rows the call took to be there are both missing, the first it took is the one said so: a row is asked for behind the write that says an earlier one is there. That write must be the unit's first, and take nothing of the row asked for; else the earlier row is asked for too.\n for (let place = says.length, asked = false, held = false; place-- > 0; ) {\n if (asked && (held || says[place] !== log[this.#sent]))\n says[place] = undefined;\n const { through } = taken[place]![1].question;\n asked ||= !says[place];\n held ||=\n !says[place] &&\n through?.kind === \"reference\" &&\n through.owner === \"source\";\n }\n let behind = 0;\n for (const [place, [id, { question, at }]] of taken.entries()) {\n (this.#asserted ??= new Set()).add(id);\n const first = says[place];\n if (first) {\n confirms.set(first, question);\n behind = this.#sent + 1;\n continue;\n }\n // A member is asked for behind what the unit writes that may make it one.\n const from = Math.max(made(question, at) ? at : 0, behind);\n if (from > 0)\n later.push([\n from,\n () => ask(question, id, \"presumed\", undefined, from),\n ]);\n else ask(question, id, \"presumed\");\n }\n /**\n * The question a write of rows by their keys is written under: rows the\n * call found were found members; a row it took to be there is still to\n * be one.\n */\n const under = (\n entry: Extract<Entry, { kind: \"update\" | \"delete\" }>,\n run: readonly Extract<Entry, { kind: \"update\" | \"delete\" }>[] = [entry]\n ) => ({\n ...this.#asked({\n ...entry.question,\n member: confirms.get(entry)?.member,\n }),\n through: entry.question.member?.edge ?? entry.question.through,\n // Where nothing holds what the call read, the first write of the rows it read says again what they were found by.\n again:\n !holds &&\n run.every(\n (each) =>\n each.question.where === entry.question.where &&\n firstOf(each.row) === each &&\n !this.#meta?.get(each.row)?.made\n ),\n });\n /**\n * Rows the call read and named again by what they were found by: where\n * the write took fewer, some stopped answering after the unit asked, and\n * the unit is made. The call says so, with what stands.\n */\n const consumed = (\n question: Question,\n rows: number,\n sent: Sent | undefined\n ) => {\n if (question.again && sent && writer.count(sent) < rows)\n throw new TransactionError(\n `${question.verb ?? this.operation.operation} selected-row cardinality changed during its locked mutation.`,\n {\n meta: {\n model: this.operation.modelName,\n operation: this.operation.operation,\n },\n }\n );\n };\n /** Whether a write is of a row the call names by what the question that found it says, its key being the database's to say. */\n const unkeyed = (entry: Entry) =>\n \"row\" in entry && this.#meta?.get(entry.row)?.named !== undefined;\n /** The keys a write of rows names them by; none where the question does. */\n const keyed = (run: readonly { row: Row; key: Input }[]) =>\n unkeyed(run[0] as Entry)\n ? undefined\n : run.map((next) => this.#said(next.key));\n /** Whether two writes of rows by their keys may be one statement: rows found, or rows taken to be members of the same row. */\n const mates = (entry: Entry, next: Entry) => {\n const [a, b] = [confirms.get(entry)?.member, confirms.get(next)?.member];\n return (\n confirms.has(entry) === confirms.has(next) &&\n a?.of === b?.of &&\n a?.edge === b?.edge &&\n !(own.has(next) || spare?.has(next) || spare?.has(entry)) &&\n !(unkeyed(entry) || unkeyed(next))\n );\n };\n /** Refuses where a write that says whether its rows are there found fewer. */\n let sizes: Map<Entry, number> | undefined;\n const confirmed = (entry: Entry, sent: Sent) => {\n const question = confirms.get(entry);\n if (question && writer.count(sent) < (sizes?.get(entry) ?? 1))\n throw this.#absent(question);\n };\n /**\n * The reads of one row its own write answers: the write just before it,\n * or an earlier one where the read asks only what the row itself holds\n * and nothing noted between them can change the row.\n */\n const own = new Map<\n Entry,\n { read: Extract<Entry, { kind: \"read\" }>; place: number }\n >();\n let told: Set<Entry> | undefined;\n /**\n * The reads of one row that find it gone are answered by what the row's\n * own write said of it: something noted between them may remove the row,\n * and the call answers with the row it wrote.\n */\n let spare: Map<Entry, Extract<Entry, { kind: \"read\" }>> | undefined;\n let spared: Map<Entry, Sent> | undefined;\n for (let place = this.#sent; place < to; place++) {\n const read = log[place]!;\n if (!(read.kind === \"read\" && read.projection && read.rows.length === 1))\n continue;\n const [row] = read.rows;\n const { model } = read;\n let changed = false;\n for (let at = place - 1; at >= this.#sent; at--) {\n const entry = log[at]!;\n if (\n (entry.kind === \"insert\" || entry.kind === \"update\") &&\n entry.row === row\n ) {\n if (\n !(own.has(entry) || spare?.has(entry)) &&\n (at === place - 1 || returningSafeProjection(read.projection)) &&\n (entry.kind === \"insert\" || entry.hears.length === 0) &&\n this.operation.answersInStatement(\n model,\n read.projection,\n entry.kind,\n entry.kind === \"update\" ? entry.set : undefined\n )\n ) {\n if (changed) {\n if (entry.kind === \"update\")\n (spare ??= new Map()).set(entry, read);\n } else {\n own.set(entry, { read, place });\n (told ??= new Set()).add(read);\n }\n }\n break;\n }\n // What may change the row between its write and its read.\n const touched =\n entry.kind === \"all\" || entry.kind === \"either\"\n ? entry.question.model\n : entry.kind === \"delete\" || entry.kind === \"update\"\n ? this.#about(entry.row).model\n : undefined;\n if (\n touched === model ||\n (touched && dependentsOf(schema, touched).has(model))\n )\n changed = true;\n }\n }\n /** The read of rows that follows `at`, where the statement that writes those rows may answer it. */\n const answered = (\n at: number,\n rows: readonly Row[],\n effect: \"insert\" | \"delete\"\n ) => {\n const next = log[at];\n return at < to &&\n next?.kind === \"read\" &&\n next.projection &&\n next.rows.length === rows.length &&\n next.rows.every((row, place) => row === rows[place]) &&\n this.operation.answersInStatement(next.model, next.projection, effect)\n ? next\n : undefined;\n };\n for (const [answer, at] of this.#used ?? []) {\n // Rows read where what is read is held are not asked again.\n if (holds) continue;\n {\n const { model, where } = answer.question;\n const keys = (at > to ? [] : answer.rows)\n .filter(\n (values) => !passed(this.#known?.get(this.#name(model, values)))\n )\n // By its key, and by every value of it no other row may have: what the call may have given another row to hold. A value it does not have names no row.\n .map((values) =>\n Object.fromEntries(\n [\n ...new Set([\n ...schema.keys(model),\n ...getModelKeyCatalog(model)\n .referenceableKeys.flat()\n .filter((field) => (values[field] ?? null) !== null),\n ]),\n ].map((field) => [field, values[field]])\n )\n );\n const key = keys.length === 1 ? keys[0] : keys;\n if (keys.length === 0) continue;\n // A unit that writes nothing but the rows it read, each once, says again in each write what the row was found by; any other holds the rows it read from where it asks for them.\n const held = !(\n writes === answer.rows.length &&\n answer.rows.every((values) => {\n const first = firstOf(\n this.#known?.get(this.#name(model, values)) as Row\n );\n return (\n (first?.kind === \"update\" || first?.kind === \"delete\") &&\n span.includes(first)\n );\n })\n );\n if (made(answer.question, at))\n later.push([\n at,\n () => ask(answer.question, text(where), \"read\", key, at, held),\n ]);\n else ask(answer.question, text(where), \"read\", key, undefined, held);\n }\n }\n later.sort(([a], [b]) => a - b);\n for (let at = this.#sent; at < to; at++) {\n const entry = log[at]!;\n const place = at;\n while (later.length > 0 && later[0]![0] <= at) later.shift()![1]();\n current = entry;\n /** The entries that follow `entry` and travel with it. */\n const beside = <T extends Entry>(same: (next: T) => boolean): T[] => {\n const run = [entry as T];\n while (\n at + 1 < to &&\n log[at + 1]!.attempt === entry.attempt &&\n // What is asked for at a place is asked before what is written there.\n !(later.length > 0 && later[0]![0] <= at + 1) &&\n same(log[at + 1] as T)\n )\n run.push(log[++at] as T);\n return run;\n };\n const take = (sent: Sent[], queries?: Query[]) => {\n (this.#heard ??= new Map()).set(place, sent);\n confirmed(entry, sent[0]!);\n entry.take?.(sent, queries);\n };\n /** Tells the read a write answered what the write said. */\n const tells =\n (read: Entry | undefined, from: number) => (sent: Sent[]) => {\n (this.#heard ??= new Map()).set(from, sent);\n confirmed(entry, sent[0]!);\n read?.take?.(sent);\n };\n if (entry.kind === \"insert\") {\n const { model } = this.#about(entry.row);\n const { decided } = entry;\n const settled = (row: Row): Input => {\n const computes = this.#about(row).born;\n /** What the statement does not write of the row: what it holds no value of, and what the database decides of it. */\n const left = (value: unknown) =>\n value === undefined ||\n (value instanceof Pending && value.row === row);\n // Most rows are written as they are.\n let whole = !computes;\n for (const field in row) whole &&= !left(row[field]);\n if (whole) return row;\n const values: Input = {};\n for (const field in row) {\n // What is computed where the row is written is written as what computes it.\n const value = computes?.[field] ?? row[field];\n if (!left(value)) values[field] = value;\n }\n return values;\n };\n const columns = Object.keys(settled(entry.row));\n const fits = (rows: Row[], next: Entry | undefined) =>\n next?.kind === \"insert\" &&\n this.#about(next.row).model === model &&\n next.relation === entry.relation &&\n writer.beside(model, columns, rows.length, settled(next.row));\n let rows = [entry.row];\n const mine = own.get(entry);\n // The rows written side by side that the read after them asks for, and nothing else of what the database decides of them: their statement answers it.\n let end = at + 1;\n while (!mine && end < to && fits(rows, log[end]))\n rows.push((log[end++] as typeof entry).row);\n let read = mine?.read ?? answered(end, rows, \"insert\");\n // Another statement needs what the database decides of the row: its statement says it beside the answer, where it can.\n const both = Boolean(mine) && wanted(entry.row);\n if (\n mine &&\n both &&\n !(holds && returningSafeProjection(mine.read.projection!))\n ) {\n told?.delete(mine.read);\n read = undefined;\n } else if (mine) rows = [entry.row];\n else if (read && !rows.some(wanted)) at = end;\n else {\n read = undefined;\n rows = [entry.row];\n // A row of which the database decides what another statement needs is written alone: its statement says it.\n beside<typeof entry>((next) => {\n const joins =\n fits(rows, next) &&\n !(needed.has(entry.row) || needed.has(next.row) || own.has(next));\n if (joins) rows.push(next.row);\n return joins;\n });\n }\n const hears = (both || !read) && needed.has(entry.row);\n // A provider whose writes say nothing says one thing of a row it creates: the number it gave it.\n if (hears && decided.length > 1 && !writer.says)\n throw new Error(\n \"Returning generated values requires RETURNING support or one generated increment field\"\n );\n if (hears && last && !holds)\n scratch ??= { id: crypto.randomUUID(), model };\n push({\n write: async () => {\n const insert = (returns?: PreparedProjection) =>\n writer.insert(\n model,\n rows.map((row) => this.#said(settled(row))),\n entry.relation,\n returns,\n read && hears ? decided : undefined,\n // Where an insert can pass a taken key by and say so, the first row of a part undone alone does: nothing fails, and nothing is undone.\n entry.root && writer.passes\n );\n const kept =\n scratch &&\n hears &&\n !read &&\n writer.kept(scratch.id, `${place}`, decided, await insert());\n if (!kept)\n return [\n await insert(\n read?.projection ??\n (hears ? writer.fields(model, decided) : undefined)\n ),\n ];\n entry.row[decided[0]!] = kept.value;\n return kept.statements;\n },\n take: (sent) => {\n if (entry.root && writer.passes && sent[0]!.rows.length === 0)\n throw PASSED;\n take(sent);\n if (read) tells(read, mine?.place ?? at)(sent);\n },\n });\n } else if (entry.kind === \"update\") {\n const { model } = entry.question;\n const { hears } = entry;\n const fields = Object.keys(entry.set);\n const run = beside<Extract<Entry, { kind: \"update\" }>>(\n (next) =>\n next.kind === \"update\" &&\n next.question.model === model &&\n // Rows that take the same values, written the same way.\n Object.keys(next.set).length === fields.length &&\n fields.every((field) =>\n Object.is(next.set[field], entry.set[field])\n ) &&\n next.question.intent === entry.question.intent &&\n next.question.through === entry.question.through &&\n next.question.verb === entry.question.verb &&\n hears.length === 0 &&\n mates(entry, next)\n );\n if (run.length > 1) (sizes ??= new Map()).set(entry, run.length);\n const mine = run.length === 1 ? own.get(entry) : undefined;\n if (!mine && own.has(entry)) told?.delete(own.get(entry)!.read);\n const read = mine?.read;\n const kept = hears.length === 0 ? spare?.get(entry) : undefined;\n let asked = false;\n let named: Question | undefined;\n push({\n confirms: confirms.has(entry),\n write: async () => {\n const set = this.#said(entry.set);\n const first =\n hears.length > 0 &&\n writer.computes(under(entry), this.#said(entry.key), set);\n asked = Boolean(first);\n named = under(entry, run);\n return [\n ...(first ? [first] : []),\n await writer.update(\n named,\n set,\n keyed(run),\n read?.projection ??\n kept?.projection ??\n (hears.length > 0 && !first ? writer.key(model) : undefined),\n // Counted where its count is what says the rows were there, or still answered.\n confirms.has(entry) || named.again\n ),\n ];\n },\n take: read\n ? tells(read, mine!.place)\n : (sent) => {\n if (kept) (spared ??= new Map()).set(kept, sent.at(-1)!);\n take(asked ? sent.slice(0, 1) : sent);\n if (writer.counts(\"update\"))\n consumed(named!, run.length, sent.at(-1));\n },\n });\n } else if (entry.kind === \"delete\") {\n const { model } = entry.question;\n const run = beside<Extract<Entry, { kind: \"delete\" }>>(\n (next) =>\n next.kind === \"delete\" &&\n next.question.model === model &&\n mates(entry, next)\n );\n if (run.length > 1) (sizes ??= new Map()).set(entry, run.length);\n const named = under(entry, run);\n push({\n confirms: confirms.has(entry),\n write: () => [\n writer.remove(\n named,\n keyed(run),\n undefined,\n confirms.has(entry) || named.again\n ),\n ],\n take: (sent) => {\n take(sent);\n consumed(named, run.length, sent[0]);\n },\n });\n } else if (\n entry.kind === \"all\" ||\n entry.kind === \"skipping\" ||\n entry.kind === \"either\"\n )\n push({ write: () => this.#whole(entry), take });\n else if (entry.kind === \"link\") {\n // Links of a junction that only joins two rows travel together.\n const plain = (link: typeof entry) =>\n !(link.through || link.edge.declared || link.edge.uniqueSide);\n const run = beside<typeof entry>(\n (next) =>\n next.kind === \"link\" &&\n next.edge === entry.edge &&\n plain(entry) &&\n plain(next)\n );\n push({\n write: () =>\n writer.link(\n entry.edge,\n run.map(\n (next) =>\n [this.#said(next.keys[0]), this.#said(next.keys[1])] as const\n ),\n entry.through\n ),\n });\n } else if (entry.kind === \"unlink\")\n push({\n write: () => [\n writer.unlink(\n entry.edge,\n this.#said(entry.keys[0]),\n entry.keys[1] && this.#said(entry.keys[1]),\n entry.keys[2].map((key) => this.#said(key))\n ),\n ],\n });\n else if (entry.kind === \"none\")\n push({\n write: () => [\n {\n ...writer.none(this.#asked(entry.question), entry.stops),\n ...(entry.believed && { believed: \"read\" as const }),\n },\n ],\n });\n else if (!told?.has(entry)) {\n // A row read as it goes is answered by the statement that removes it.\n const removal = log[at + 1];\n if (\n at + 1 < to &&\n removal?.kind === \"delete\" &&\n answered(at, [removal.row], \"delete\")\n ) {\n at++;\n push({\n write: () => [\n writer.remove(\n under(removal),\n [this.#said(removal.key)],\n entry.projection\n ),\n ],\n take: (sent) => {\n confirmed(removal, sent[0]!);\n take(sent);\n },\n });\n continue;\n }\n let queries: Query[];\n push({\n write: () => {\n queries = entry.queries();\n return queries.map((query) => ({\n sql: query.sql,\n model: entry.model,\n }));\n },\n take: (sent) =>\n take(\n spared?.has(entry) && sent.every((each) => each.rows.length === 0)\n ? [spared.get(entry)!]\n : sent,\n queries\n ),\n });\n }\n }\n // What is asked for behind the unit's last write.\n for (const [, run] of later) run();\n if (scratch) {\n const { open, close } = writer.scratch(scratch.id, scratch.model);\n steps.unshift({ write: () => open });\n steps.push({ write: () => [close] });\n }\n this.#sent = Math.max(this.#sent, to);\n return steps;\n }\n /** The statements of a write that names its rows itself. */\n #whole(\n entry: Extract<Entry, { kind: \"all\" | \"skipping\" | \"either\" }>\n ): Statement[] | Promise<Statement[]> {\n const { writer } = this;\n if (entry.kind === \"all\")\n return after(\n entry.set\n ? writer.update(\n this.#asked(entry.question),\n this.#said(entry.set),\n undefined,\n entry.projection\n )\n : writer.remove(\n this.#asked(entry.question),\n undefined,\n entry.projection\n ),\n (statement) => [statement]\n );\n if (entry.kind === \"either\")\n return after(\n writer.either(\n entry.question,\n this.#said(entry.row),\n this.#said(entry.set),\n entry.projection,\n entry.marker\n ),\n (statement) => [statement]\n );\n // As many statements as the rows' shapes and the provider's bound on one statement ask.\n const chunks: Input[][] = [];\n let columns: string[] = [];\n for (const row of entry.rows) {\n const chunk = chunks.at(-1);\n if (chunk && writer.beside(entry.model, columns, chunk.length, row))\n chunk.push(row);\n else {\n chunks.push([row]);\n columns = Object.keys(row);\n }\n }\n const written = chunks.map((chunk) =>\n writer.insert(\n entry.model,\n chunk.map((row) => this.#said(row)),\n undefined,\n entry.projection,\n undefined,\n entry.passes\n )\n );\n return written.some((statement) => statement instanceof Promise)\n ? Promise.all(written)\n : (written as Statement[]);\n }\n /**\n * Sends the steps of a unit. A statement that needs a value the database\n * has not said yet is written once what stands before it is sent and\n * heard.\n */\n async #deliver(\n steps: Step[],\n last: boolean,\n within?: Transport[\"send\"]\n ): Promise<void> {\n const send = within ?? this.#transport.send;\n let waiting: { statements: Statement[]; step: Step }[] = [];\n const flush = async (end: boolean) => {\n const told = waiting;\n waiting = [];\n // One step's statements are sent as they are, and its answers taken so.\n const one = told.length === 1;\n const statements = one\n ? told[0]!.statements\n : told.flatMap((written) => written.statements);\n const sent = statements.length > 0 ? await send(statements, end) : [];\n this.said ||= end && !within;\n let at = 0;\n const parts = told.map(({ statements: own }) =>\n one ? sent : sent.slice(at, (at += own.length))\n );\n // What was written outside a unit the call can undo is made, where a row was written.\n if (\n !within &&\n this.#transport.loose &&\n told.some(\n ({ step }, place) =>\n step.writes &&\n parts[place]!.some(\n (each) => each.rowCount > 0 || each.rows.length > 0\n )\n )\n )\n this.segments++;\n for (let place = 0; place < told.length; place++)\n told[place]!.step.take?.(parts[place]!);\n };\n // What a statement asks while it is written is asked once what stands before it is sent.\n const outer = this.#hear;\n // Named before it is stored: a function written where it is assigned to a field is kept past the next collection, with all it holds.\n const hear = async (statement: Statement) => {\n await flush(false);\n return (await send([statement], false))[0]!.rows;\n };\n this.#hear = hear;\n try {\n for (let at = 0; at < steps.length; at++) {\n const step = steps[at]!;\n // A part undone alone is sent alone: whether it was written is noted.\n if (!within && step.attempt !== undefined) {\n await flush(false);\n const part = [step];\n while (steps[at + 1]?.attempt === step.attempt)\n part.push(steps[++at]!);\n const written = await this.#attempted(part);\n (this.#outcomes ??= new Map()).set(step.attempt, written);\n continue;\n }\n let statements: Statement[];\n try {\n statements = await step.write();\n } catch (error) {\n if (error !== UNHEARD) throw error;\n await flush(false);\n // What the database decided of a row is asked for again where a unit made after it writes it into other rows: on a transport that holds nothing, another writer may have changed the row since.\n const waited = this.#waited;\n this.#waited = undefined;\n if (waited && !(within || this.#transport.holds))\n waiting.push({\n statements: [\n this.writer.still(this.#about(waited.row).model, {\n ...this.#key(waited.row),\n [waited.field]: waited.row[waited.field],\n }),\n ],\n step: STILL,\n });\n statements = await step.write();\n }\n waiting.push({ statements, step });\n // Where each statement is heard as it is sent, what says whether a row is there is taken before the next is written: a row that is not there refuses the call before anything under it does.\n if (\n within\n ? step.root && this.writer.passes\n : this.#transport.holds && step.confirms\n )\n await flush(last && at === steps.length - 1);\n }\n await flush(last);\n } finally {\n this.#hear = outer;\n }\n }\n /** Sends a part of the unit that is undone alone where the database refuses its first row as one too many: whether it was written. */\n async #attempted(part: Step[]): Promise<boolean> {\n let first: Statement | undefined;\n const told = part.map((step) =>\n step.root\n ? {\n ...step,\n write: async () => {\n const statements = await step.write();\n [first] = statements;\n return statements;\n },\n }\n : step\n );\n try {\n await this.#transport.attempt!((send) =>\n this.#deliver(told, false, send)\n );\n return true;\n } catch (error) {\n if (\n error === PASSED ||\n (error instanceof UniqueConstraintError &&\n first &&\n refusedBy.get(error) === first)\n )\n return false;\n throw error;\n }\n }\n}\n","/**\n * What the verbs mean, and nothing else: written as if the store were the\n * database itself and answered at once. No transport, no provider, no row\n * scope, no word about what is known when.\n */\nimport {\n NestedWriteError,\n NotFoundError,\n UniqueConstraintError,\n} from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport { getModelKeyCatalog } from \"@schema/model/keys\";\nimport type { WriteKind } from \"../../write-sinks\";\nimport { Stored } from \"../shared/insert-value\";\nimport { readUpdate } from \"../shared/query\";\nimport { parseStamped } from \"../shared/row-scope\";\nimport type { Arguments, Input } from \"../shared/schema\";\nimport { type Membership, sideFields } from \"../shared/storage\";\nimport { engineFault, nameOf, same, unsupported } from \"../shared/terms\";\nimport type { Question } from \"./statements\";\nimport type { Row, Store } from \"./store\";\n\n/** Whether a value is an object written as one: no instance of a class. */\nconst plainObject = (value: unknown): value is Input => {\n if (typeof value !== \"object\" || value === null) return false;\n const kind = Object.getPrototypeOf(value);\n return kind === Object.prototype || kind === null;\n};\nconst list = (value: unknown): unknown[] => {\n if (value === undefined || value === false) return [];\n return Array.isArray(value) ? value : [value];\n};\n\nexport class Verbs {\n readonly #store: Store;\n readonly #operation;\n readonly #schema;\n\n readonly #q;\n\n /** What the caller wrote of each node of what was admitted of it. One entry is written as itself, or as the list of one. */\n readonly #said = new WeakMap<object, unknown>();\n\n /** The rows the call makes. Of those a `create` makes (`true`), the caller said everything they hold. */\n #made: WeakMap<Row, boolean> | undefined;\n\n /** How many rows the call's own verb writes, where it writes several. */\n #several = 1;\n\n /** The fields a row took of a relation it holds, in this call, and the verb that gave them. */\n #slots:\n | WeakMap<Row, Map<string, { relation: string; verb: string }>>\n | undefined;\n constructor(store: Store) {\n this.#store = store;\n this.#operation = this.#store.operation;\n this.#schema = this.#operation.schema;\n this.#q = this.#operation.queries;\n }\n\n /** A relation's verbs where it reaches many rows: in the order they take effect. */\n static #nested: Record<\n string,\n (\n this: Verbs,\n parent: Row,\n edge: Membership,\n entry: Input,\n arm?: boolean,\n through?: Input\n ) => void\n > = {\n disconnect(parent, edge, where) {\n this.#leave(\n parent,\n edge,\n this.#store.one({\n ...this.#within(parent, edge, where),\n unique: true,\n intent: \"join\",\n verb: \"disconnect\",\n })\n );\n },\n delete(parent, edge, where) {\n const row = this.#store.one({\n ...this.#within(parent, edge, where),\n unique: true,\n intent: \"delete\",\n verb: \"delete\",\n });\n // The link to the row it is deleted through goes first, where the database would not take it with the row: the links other rows hold are what may still refuse.\n const kept =\n edge.kind === \"junction\" &&\n (edge.targetSide.onDelete ?? \"cascade\") !== \"cascade\";\n if (kept && !this.#store.writer.marks(edge.target))\n this.#store.unlink(edge, parent, row);\n this.#store.delete(row);\n },\n updateMany(parent, edge, { where, data }) {\n const values = this.#paired(data as Input, this.#stated(data as Input));\n const ask = {\n intent: \"update\" as const,\n writes: this.#writes(edge.target, values),\n verb: \"updateMany\",\n };\n const set = this.#store.values(\n edge.target,\n \"update\",\n values,\n this.#stated(values)\n );\n // Rows that take the same fields are written at once; rows of which a relation or a key is written are each written as an update writes its row.\n if (this.#plain(edge.target, values, set))\n this.#store.all(\n {\n ...this.#within(parent, edge, where),\n ...ask,\n },\n set\n );\n else {\n const rows = this.#members(parent, edge, where as Input, ask);\n const outer = this.#several;\n this.#several = rows.length;\n for (const [at, row] of rows.entries())\n this.#write(\n edge.target,\n row,\n // Each row is written of its own copy of what the caller wrote: what a default fills is that row's own.\n at === 0\n ? values\n : this.#store.copy(\n `${edge.name} ${Object.values(this.#schema.identity(edge.target, row)).join()}`,\n () =>\n this.#paired(\n parseStamped(\n this.#operation.scope?.rows.stamps ?? new Map(),\n () =>\n this.#schema.update(edge.target, this.#stated(values))\n ),\n this.#stated(values)\n )\n )\n );\n this.#several = outer;\n }\n },\n deleteMany(parent, edge, where) {\n this.#store.all({\n ...this.#within(parent, edge, where),\n intent: \"delete\",\n verb: \"deleteMany\",\n });\n },\n update(parent, edge, { where, data }) {\n const values = data as Input;\n this.#write(\n edge.target,\n this.#store.one({\n ...this.#within(parent, edge, where),\n unique: true,\n intent: \"update\",\n writes: this.#writes(edge.target, values),\n verb: \"update\",\n }),\n values\n );\n },\n upsert(parent, edge, { where, create, update }) {\n const named: Question = {\n model: edge.target,\n where: where as Input,\n unique: true,\n intent: \"update\",\n writes: this.#writes(edge.target, update as Input),\n verb: \"upsert\",\n };\n // The row the filter names, whose ever it is: one that is another row's is not taken, nor made again.\n const [found] = this.#store.rows({\n ...named,\n through: edge,\n makes: true,\n });\n if (!found)\n Verbs.#nested.create!.call(this, parent, edge, create as Input, true);\n // A row the call creates has no member yet: the row its upsert finds becomes one.\n else if (this.#made?.has(parent)) {\n this.#write(\n edge.target,\n found,\n update as Input,\n true,\n this.#born(parent, edge),\n edge.name\n );\n if (edge.kind === \"junction\") this.#store.link(edge, parent, found);\n } else {\n const row = this.#store.one({ ...named, member: { edge, of: parent } });\n // An update that says nothing writes nothing: the row is only asked to be there.\n if (Object.keys(this.#stated(update as Input)).length > 0)\n this.#write(edge.target, row, update as Input);\n }\n },\n connectOrCreate(parent, edge, { where, create, $through }) {\n const asked: Question = {\n model: edge.target,\n where: where as Input,\n unique: true,\n through: edge,\n intent: \"join\",\n verb: \"connectOrCreate\",\n makes: true,\n };\n const [row] = this.#store.rows(asked);\n if (row)\n this.#join(parent, edge, row, \"connectOrCreate\", $through as Input);\n else {\n // A row created because none was found is created while none is there: its own key says so, or the call asks again.\n if (this.#keyed(asked, create as Input)) this.#store.created(asked);\n else this.#store.absent(asked);\n Verbs.#nested.create!.call(\n this,\n parent,\n edge,\n create as Input,\n true,\n $through as Input\n );\n }\n },\n connect(parent, edge, { $through, ...where }) {\n this.#join(\n parent,\n edge,\n this.#store.one({\n model: edge.target,\n where,\n unique: true,\n through: edge,\n intent: \"join\",\n verb: \"connect\",\n }),\n \"connect\",\n $through as Input\n );\n },\n create(parent, edge, data, arm = false, through = data.$through as Input) {\n const row = this.#make(\n edge.target,\n data,\n this.#born(parent, edge),\n edge.name,\n arm\n );\n if (edge.kind === \"junction\")\n this.#store.link(edge, parent, row, through);\n },\n createMany(parent, edge, { data, skipDuplicates }) {\n const rows = list(data) as Input[];\n if (!skipDuplicates) {\n for (const entry of rows)\n Verbs.#nested.create!.call(this, parent, edge, entry);\n return;\n }\n const bare = (row: Input) =>\n this.#relationsOf(edge.target, row).length === 0;\n // Under another write, duplicates are passed by only where a part of the unit can be undone alone.\n this.#store.attempts(\"nested createMany rows\");\n // Rows that hold their own membership, and nothing but themselves, are written at once.\n if (\n edge.kind === \"reference\" &&\n rows.every(bare) &&\n this.#store.skipping(\n edge.target,\n rows.map((row) => [row, this.#stated(row), this.#born(parent, edge)])\n )\n )\n return;\n for (const row of rows) {\n let made: Row | undefined;\n const written = this.#store.attempt(() => {\n made = this.#make(\n edge.target,\n row,\n this.#born(parent, edge),\n edge.name\n );\n return made;\n }, \"nested createMany rows\");\n if (edge.kind !== \"junction\") continue;\n // A row passed by is not a membership passed by: the row it names is made a member, where it names one and asks nothing else. A member one row alone may have stays whose it is.\n const named =\n !(written || edge.uniqueSide) &&\n bare(row) &&\n this.#spelled(edge.target, this.#stated(row));\n const member = written\n ? made\n : named &&\n this.#store.rows({\n model: edge.target,\n where: named,\n through: edge,\n intent: \"join\",\n verb: \"createMany\",\n })[0];\n if (member)\n this.#store.link(edge, parent, member, row.$through as Input);\n }\n },\n };\n\n #paired<T>(admitted: T, raw: unknown): T {\n if (Array.isArray(admitted)) {\n this.#said.set(admitted, raw);\n for (let at = 0; at < admitted.length; at++) {\n const child = admitted[at];\n if (typeof child !== \"object\" || child === null) continue;\n const next = (raw as unknown[] | undefined)?.[at];\n this.#paired(child, next === undefined && at === 0 ? raw : next);\n }\n // A value is no node of the payload: what a blob or a date holds is not walked.\n } else if (plainObject(admitted)) {\n this.#said.set(admitted, raw);\n // An update of the one row a relation reaches is written as its data alone.\n let whole = true;\n for (const key in admitted) whole &&= key === \"data\" || key === \"where\";\n for (const key in admitted) {\n const child = admitted[key];\n if (typeof child !== \"object\" || child === null) continue;\n const next = (raw as Input | undefined)?.[key];\n this.#paired(\n child,\n next === undefined && (key === \"0\" || (key === \"data\" && whole))\n ? raw\n : next\n );\n }\n }\n return admitted;\n }\n\n #stated(admitted: Input): Input {\n return (this.#said.get(admitted) ?? {}) as Input;\n }\n\n /** A field of a row is decided once: by what was written of the row, or by one relation. */\n #once(\n kind: \"create\" | \"update\",\n model: AnyModel,\n own: Input,\n takes: Input,\n relation: string,\n owned = false\n ) {\n for (const [field, value] of Object.entries(takes)) {\n const written = own[field] as Input | undefined;\n if (written === undefined) continue;\n // The same value said twice is said once.\n const plain =\n written !== null && typeof written === \"object\" && \"set\" in written\n ? written.set\n : written;\n if (\n (value instanceof Date || typeof value !== \"object\") &&\n same(plain, value)\n )\n continue;\n unsupported(\n owned\n ? `Relation '${relation}' owns '${Object.keys(takes).join(\", \")}'; omit it from nested create and update data.`\n : `${kind} assigns conflicting values to column '${this.#q.columnName(model, field)}' through relation '${relation}'.`\n );\n }\n return takes;\n }\n\n /** Whether what was written of a field leaves it another value than it holds. */\n #moves(held: unknown, written: unknown): boolean {\n if (written === undefined) return false;\n if (written === null || typeof written !== \"object\")\n return !same(written, held);\n const { set, increment, decrement, multiply, divide } = written as Input;\n if (set !== undefined) return !same(set, held);\n return !(\n [increment ?? 0, decrement ?? 0].every((by) => Number(by) === 0) &&\n [multiply ?? 1, divide ?? 1].every((by) => Number(by) === 1)\n );\n }\n\n /**\n * The row what was written of a row names: by its whole key, or by the one\n * other set of fields no two rows may share that it states whole. None\n * where it names none, or more than one.\n */\n #spelled(model: AnyModel, own: Input): Input | undefined {\n const whole = (fields: readonly string[]) =>\n fields.every((field) => (own[field] ?? null) !== null)\n ? Object.fromEntries(fields.map((field) => [field, own[field]]))\n : undefined;\n const named = getModelKeyCatalog(model)\n .addressableKeys.filter((key) => key.kind !== \"primary\")\n .map((key) => whole(key.fields))\n .filter((values) => values !== undefined);\n return (\n whole(this.#schema.keys(model)) ??\n (named.length === 1 ? named[0] : undefined)\n );\n }\n\n /** The relations `data` names of a row of `model`, each with what it asks. */\n #relationsOf(model: AnyModel, data: Input) {\n return model[\"~\"].relationNames.some((name) => data[name] !== undefined)\n ? this.#relationsIn(model, data)\n : [];\n }\n\n #relationsIn(model: AnyModel, data: Input) {\n return model[\"~\"].relationNames.flatMap((name) => {\n const payload = data[name] as Input | undefined;\n if (payload === undefined) return [];\n const resolved = this.#schema.index.get(model)!.get(name)!;\n // A relation of variants is one relation per variant, each with the\n // entries that name it: `true` asks it of whichever holds, and a set\n // empties every one.\n const arms: [string | undefined, Input][] =\n \"members\" in resolved.edge && !resolved.member\n ? resolved.edge.members.map(({ variant }) => [\n variant,\n Object.fromEntries(\n Object.entries(payload).flatMap(([verb, given]) => {\n const mine = list(given)\n .filter(\n (entry) =>\n entry === true || (entry as Input).type === variant\n )\n .map((entry) => {\n if (entry === true) return entry;\n const { type, ...named } = entry as Input;\n if (verb === \"create\") return named.data;\n return named.data || named.create ? named : named.where;\n });\n return mine.length > 0 || (verb === \"set\" && given)\n ? [[verb, mine]]\n : [];\n })\n ),\n ])\n : [[undefined, payload]];\n return arms\n .filter(([, mine]) => Object.keys(mine).length > 0)\n .map(([variant, mine]) => ({\n name,\n edge: this.#schema.membership(model, name, variant),\n payload: mine,\n }));\n });\n }\n\n /** The row a relation is asked of holds the key of the row it reaches. */\n #holds(edge: Membership) {\n return edge.kind === \"reference\" && edge.owner === \"source\";\n }\n\n /** What a row holds to reference another: what the other holds of each field it is referenced by, which names no row where it is null. */\n #referencing(edge: Membership, row: Row, held: \"source\" | \"target\"): Input {\n if (edge.kind !== \"reference\") return {};\n const referenced = held === \"source\" ? \"target\" : \"source\";\n const { discriminator } = edge;\n return Object.fromEntries([\n // With which of the variants it references, where it may reference several.\n ...(discriminator?.side === held\n ? [[discriminator.field, discriminator.value]]\n : []),\n ...edge.pairs.map((pair) => {\n const field = pair[referenced];\n // A row the call creates holds what it was given, or nothing.\n if (this.#made?.get(row) === true && (row[field] ?? null) === null)\n unsupported(\n `Cannot create relation '${edge.name}': referenced field '${field}' must be supplied by the parent record or generated by the database.`\n );\n if (row[field] === null)\n throw new NestedWriteError(\n `Cannot connect relation '${edge.name}': the located target's referenced field '${field}' is null.`,\n edge.name\n );\n return [pair[held], row[field]];\n }),\n ]);\n }\n\n /** What a row born a member of `parent`'s holds: nothing where the membership is not the row's to hold. */\n #born(parent: Row, edge: Membership): Input {\n return this.#referencing(edge, parent, \"target\");\n }\n\n /** What the row that holds a relation's key takes of the row it reaches. */\n #reaching(edge: Membership, row: Row): Input {\n return this.#referencing(edge, row, \"source\");\n }\n\n /**\n * What a row the call found takes when its membership is written: that,\n * and what its model gives every update, admitted once for the call. Not\n * what is written of a row a caller updates: a membership is no update of\n * the row's own.\n */\n #moved(row: Row, edge: Membership, takes: Input): Input {\n if (this.#made?.get(row) === true) return takes;\n const model = edge.target;\n return {\n ...this.#schema.scalars(\n model,\n this.#store.copy(`moved ${nameOf(model)}`, () =>\n this.#schema.update(model, {})\n )\n ),\n ...takes,\n };\n }\n\n /** What empties a relation on the row that holds it. */\n #cleared(edge: Membership): Input {\n return Object.fromEntries(\n (edge.clearability as { fields?: string[] }).fields!.map((field) => [\n field,\n null,\n ])\n );\n }\n\n /** The members of `parent` through a relation, among those `where` names: what every question about them starts from. */\n #within(parent: Row, edge: Membership, where?: unknown) {\n return {\n model: edge.target,\n where: where as Input | undefined,\n member: { edge, of: parent },\n };\n }\n\n #members(\n parent: Row,\n edge: Membership,\n where: Input | undefined,\n ask: Partial<Question>\n ): Row[] {\n return this.#store.rows({\n ...this.#within(parent, edge, where),\n ...ask,\n });\n }\n\n /** What a write of `data` writes of its row, as the caller stated it: none where it writes nothing of it. */\n /** Whether a row created with `data` holds the values a question names its one row by: the key then refuses a row that came since. */\n #keyed(question: Question, data: Input): boolean {\n const { uniqueKey, uniqueValues } = this.#store.writer.selector(question);\n return (\n uniqueKey?.fields.every((field) => {\n const proposed = data[field];\n const named = uniqueValues?.get(field);\n return proposed !== undefined && same(proposed, named);\n }) === true\n );\n }\n\n #writes(model: AnyModel, data: Input, set?: Input): string[] | undefined {\n const own = this.#stated(data);\n // A field kept as stored is no field the write writes.\n const fields = Object.keys(this.#schema.scalars(model, own)).filter(\n (field) => !(own[field] instanceof Stored)\n );\n const relations = this.#relationsOf(model, data).flatMap(\n ({ name, edge, payload }) =>\n // A relation whose verbs change which row this one holds, or its links, writes this row.\n Object.keys(payload).some(\n (verb) =>\n payload[verb] !== undefined &&\n verb !== \"update\" &&\n (this.#holds(edge) ||\n (edge.kind === \"junction\" && verb !== \"updateMany\"))\n )\n ? [\n name,\n // The columns of a relation of variants are no field of their own.\n ...(edge.kind === \"reference\" &&\n this.#holds(edge) &&\n !edge.discriminator\n ? edge.pairs.map((pair) => pair.source)\n : []),\n ]\n : []\n );\n const written =\n Object.keys(set ?? this.#store.values(model, \"update\", data, own))\n .length > 0;\n return written || relations.length > 0\n ? [...fields, ...relations]\n : undefined;\n }\n\n /** Makes a row that is there a member of `parent`'s: `through` is what was written of the link itself. */\n #join(\n parent: Row,\n edge: Membership,\n row: Row,\n verb: string,\n through?: Input\n ) {\n // A row whose membership is stored once is the member of one row.\n if (\n this.#several > 1 &&\n (edge.kind === \"reference\" || edge.uniqueSide === \"target\")\n )\n unsupported(\n `updateMany matched ${this.#several} rows, so it cannot apply '${verb}' to relation '${edge.name.split(\".\")[0]}': ${\n edge.kind === \"junction\"\n ? \"that target's member-junction slot can belong to only one of them\"\n : \"that membership is stored on the target row, which can belong to only one of them\"\n } — the last row updated would take it from the others. Narrow the filter (or add 'limit: 1') so exactly one row matches, or write this relation in a separate call.`\n );\n if (edge.kind === \"junction\") {\n this.#store.link(edge, parent, row, through);\n return;\n }\n const takes = this.#born(parent, edge);\n // What the row holds of a relation is decided once: by the relation it holds, or by the row that takes it as a member.\n const mine = this.#slots?.get(row);\n for (const field of Object.keys(takes)) {\n const by = mine?.get(field);\n if (by)\n throw new NestedWriteError(\n `Nested operation '${by.verb}' on relation '${by.relation}' depends on an earlier '${verb}' membership write in the same nested write. Split these operations into separate queries.`,\n by.relation,\n { meta: { operation: by.verb, conflictsWith: verb } }\n );\n }\n this.#store.update(\n row,\n this.#moved(row, edge, takes),\n undefined,\n edge,\n false,\n parent\n );\n }\n\n /** The one link a relation that reaches one row holds is every link of the row that holds it. */\n #leave(parent: Row, edge: Membership, row: Row) {\n return edge.kind === \"junction\"\n ? this.#store.unlink(edge, parent, edge.many ? row : undefined)\n : this.#store.update(\n row,\n this.#moved(row, edge, this.#cleared(edge)),\n undefined,\n edge\n );\n }\n\n #make(\n model: AnyModel,\n data: Input,\n given: Input,\n relation?: string,\n arm = false\n ): Row {\n const relations = this.#relationsOf(model, data);\n // A row that is nothing but itself is written as it is.\n if (relations.length === 0 && relation === undefined) {\n const row = this.#store.insert(\n model,\n data,\n this.#stated(data),\n relation,\n given\n );\n (this.#made ??= new WeakMap()).set(row, !arm);\n return row;\n }\n const said = this.#schema.scalars(model, this.#stated(data));\n // The rows whose key this one holds are there before it.\n const held = relations\n .filter(({ edge }) => this.#holds(edge))\n .map(({ edge, payload }) => ({\n edge,\n ...this.#single(undefined, model, edge, payload, said),\n }));\n // What the relation it is created through gives the row, a relation it holds does not give it another value of.\n const takes = Object.assign(\n {},\n relation === undefined\n ? given\n : this.#once(\"create\", model, said, given, relation, true),\n ...held.map((own) =>\n this.#once(\"create\", model, given, own.takes, own.edge.name)\n )\n );\n const row = this.#store.insert(\n model,\n data,\n this.#stated(data),\n relation,\n takes\n );\n (this.#made ??= new WeakMap()).set(row, !arm);\n this.#after(row, model, relations, held, said);\n return row;\n }\n\n /** What follows a row's own write: what the relations it holds left for then, and the relations whose rows hold its key. */\n #after(\n row: Row,\n model: AnyModel,\n relations: readonly { name: string; edge: Membership; payload: Input }[],\n held: readonly { then: (() => void)[] }[],\n said: Input\n ) {\n for (const own of held) for (const next of own.then) next();\n for (const { edge, payload } of relations)\n if (!this.#holds(edge))\n if (edge.many) this.#relate(row, edge, payload);\n else this.#single(row, model, edge, payload, said);\n }\n\n /** A key a relation is held by is given a value: what the database would compute of it names no row the relation could be asked of. */\n #computed(source: string, edge: Membership) {\n return new NestedWriteError(\n `Cannot update relation key field '${source}' with a non-literal operation while mutating relation '${edge.name}'. Use a literal value or '{ set: ... }'.`,\n edge.name,\n { meta: { operation: \"update\", field: source, relation: edge.name } }\n );\n }\n\n /** A row that is there takes what `data` states, then what its relations ask of the rows they reach. */\n #write(\n model: AnyModel,\n row: Row,\n data: Input,\n portable = true,\n given?: Input,\n relation?: string\n ): void {\n // What a key may be rewritten with is the key's rule, wherever it is asked.\n const refused = portable && this.#schema.keyPortabilityRefusal(model, data);\n if (refused) throw refused;\n const relations = this.#relationsOf(model, data);\n const said = this.#schema.scalars(model, this.#stated(data));\n /** No row may still be a member through a relation whose key the row leaves, unless the database makes its members follow. */\n const vacant = (edge: Extract<Membership, { kind: \"reference\" }>) => {\n if (\n edge.reference &&\n edge.reference.onUpdate !== \"cascade\" &&\n !edge.pairs.some((pair) => row[pair.source] === null)\n )\n this.#store.none(\n {\n model: edge.target,\n // By what its members hold of it now: asked of the row, so a row known by its key alone is read.\n member: {\n edge,\n of: {\n ...row,\n ...Object.fromEntries(\n edge.pairs.map((pair) => [pair.source, row[pair.source]])\n ),\n },\n },\n },\n {\n kind: \"nestedWrite\",\n relation: edge.name,\n message: `Cannot update relation '${edge.name}' with onUpdate('${edge.reference.onUpdate ?? \"restrict\"}') while the current relation is occupied.`,\n raceable: false,\n }\n );\n };\n // A row that takes another key, and writes a relation whose members hold that key: no member may be left behind, unless the database makes them follow.\n const keys = this.#schema.keys(model);\n for (const { edge } of relations) {\n if (edge.kind !== \"reference\" || edge.owner !== \"target\") continue;\n // What the database computes of a field that is not the row's key is not told to the rows that take it.\n for (const { source } of edge.pairs)\n if (\n said[source] !== undefined &&\n !keys.includes(source) &&\n readUpdate(said[source]).kind !== \"value\"\n )\n throw this.#computed(source, edge);\n const moved = edge.pairs.filter((pair) =>\n this.#moves(row[pair.source], said[pair.source])\n );\n for (const { source } of moved)\n if (this.#moves(null, said[source]) === false)\n throw new NestedWriteError(\n `Cannot update relation key field '${source}' to null while mutating relation '${edge.name}'. A null reference names no row for that relation to point at.`,\n edge.name,\n { meta: { operation: \"update\", field: source } }\n );\n if (moved.length > 0) vacant(edge);\n }\n const own = relations.filter(({ edge }) => this.#holds(edge));\n const singles = own.map(({ edge, payload }) =>\n this.#single(row, model, edge, payload, said)\n );\n for (const [at, { edge, payload }] of own.entries()) {\n const verb = [\n \"upsert\",\n \"connectOrCreate\",\n \"connect\",\n \"create\",\n \"delete\",\n \"disconnect\",\n ].find((each) => payload[each] !== undefined)!;\n const fields = this.#slots?.get(row) ?? new Map();\n for (const field of Object.keys(singles[at]!.takes))\n fields.set(field, { relation: edge.name.split(\".\")[0]!, verb });\n (this.#slots ??= new WeakMap()).set(row, fields);\n }\n const takes = Object.assign(\n {},\n given && this.#once(\"update\", model, said, given, relation!, true),\n ...singles.map((each, at) =>\n given\n ? this.#once(\"update\", model, given, each.takes, own[at]!.edge.name)\n : each.takes\n )\n );\n // A key the row takes of a relation it holds is as much another key as one the caller wrote.\n for (const { edge } of relations)\n if (\n edge.kind === \"reference\" &&\n edge.owner === \"target\" &&\n edge.pairs.some((pair) => {\n const next = takes[pair.source];\n return (\n next !== undefined &&\n ((typeof next === \"object\" &&\n next !== null &&\n !(next instanceof Date)) ||\n this.#moves(row[pair.source], next))\n );\n })\n )\n vacant(edge);\n // A relation the caller wrote decides the fields the row holds it by: nothing else writes them.\n const decided = Object.fromEntries(\n own.flatMap(({ edge }) =>\n (edge as Extract<Membership, { kind: \"reference\" }>).pairs.map(\n (pair) => [pair.source, true]\n )\n )\n );\n this.#store.update(\n row,\n {\n ...this.#store.values(model, \"update\", data, {\n ...decided,\n ...this.#stated(data),\n ...takes,\n }),\n ...takes,\n },\n this.#writes(model, data)\n );\n this.#after(row, model, relations, singles, said);\n }\n\n /**\n * A relation that reaches one row: the row it reaches goes, another is\n * supplied, and the row supplied, or the one there, is updated — in that\n * order, however they were written. Where the row the relation is asked of\n * holds the key, it answers what that row takes and what follows its own\n * write; the row is not there yet where it is being created.\n */\n #single(\n row: Row | undefined,\n model: AnyModel,\n edge: Membership,\n payload: Input,\n said: Input\n ): { takes: Input; then: (() => void)[] } {\n const held = this.#holds(edge);\n const then: (() => void)[] = [];\n const { target } = edge;\n const kind = row ? \"update\" : \"create\";\n /** What the row takes of the relation: nothing the caller wrote of the row itself. */\n const takes: Input = {};\n const take = (more: Input) =>\n Object.assign(takes, this.#once(kind, model, said, more, edge.name));\n const first = (verb: string) =>\n list(payload[verb])[0] as Input | true | undefined;\n // The relation reaches the row the row's key names once its own write is made: what the caller wrote of that key is where it ends.\n const final =\n held && edge.kind === \"reference\"\n ? edge.pairs.filter((pair) => said[pair.source] !== undefined)\n : [];\n // A key the relation is held by is given a value: what the database would compute of it names no row the relation could be asked of.\n const stated = (field: string) => readUpdate(said[field]);\n for (const { source } of final)\n if (stated(source).kind !== \"value\") throw this.#computed(source, edge);\n const of =\n row && final.length > 0\n ? new Proxy(row, {\n get: (known, field: string) =>\n said[field] === undefined\n ? known[field]\n : (stated(field) as { value: unknown }).value,\n })\n : row;\n /** The row the relation reaches now. */\n const current = (ask: Partial<Question>, entry?: Input | true) =>\n of\n ? this.#members(of, edge, entry === true ? undefined : entry, {\n ...ask,\n strict: entry === true,\n })[0]\n : undefined;\n const disconnect = first(\"disconnect\");\n // Nothing is read of the row a slot of the row itself gives up.\n if (disconnect === true && held) take(this.#cleared(edge));\n else if (disconnect) {\n const old = current({ intent: \"join\", verb: \"disconnect\" }, disconnect);\n if (old && held) take(this.#cleared(edge));\n else if (old) this.#leave(row!, edge, old);\n }\n const remove = first(\"delete\");\n // The row a delete names is whichever the row's own key reaches: not told apart from the row a connect names, which the same key would name next.\n const reads = remove && held && first(\"connect\") && \"connect\";\n if (reads)\n throw new NestedWriteError(\n `Nested operation '${reads}' on relation '${edge.name}' depends on an earlier 'delete' target write in the same nested write. Split these operations into separate queries.`,\n edge.name,\n { meta: { operation: reads, conflictsWith: \"delete\" } }\n );\n const removal = { intent: \"delete\", verb: \"delete\" } as const;\n const old =\n remove &&\n // The row's own key names a member: one the call cannot delete is a refusal, seen or not.\n (held &&\n of &&\n edge.kind === \"reference\" &&\n edge.pairs.every((pair) => (of[pair.source] ?? null) !== null)\n ? this.#store.one({\n model: target,\n where: remove === true ? undefined : remove,\n member: { edge, of },\n ...removal,\n })\n : current(removal, remove));\n if (old) {\n // A row the row itself references goes once the row no longer does; a row that is kept is still referenced.\n if (held) {\n if (!this.#store.keeps(target)) take(this.#cleared(edge));\n then.push(() => this.#store.delete(old));\n } else this.#store.delete(old);\n }\n // A relation held by fields of which one is null reaches no row: nothing goes, and the row gives up what it still holds of it.\n else if (\n remove === true &&\n held &&\n of &&\n edge.kind === \"reference\" &&\n edge.pairs.some((pair) => (of[pair.source] ?? null) !== null)\n )\n take(this.#cleared(edge));\n const create = (\n data: Input | true | undefined,\n arm = true,\n through = (data as Input).$through as Input | undefined\n ) => {\n const made = this.#make(\n target,\n data as Input,\n held ? {} : this.#born(row!, edge),\n edge.name,\n arm\n );\n if (edge.kind === \"junction\") this.#store.link(edge, row!, made, through);\n return made;\n };\n const adopt = (found: Row, verb: string, through?: Input) => {\n if (!held) this.#join(row!, edge, found, verb, through);\n return found;\n };\n /** An entry that names a row, and what it writes of the link to it. */\n const named = (entry: unknown) => {\n const { $through, ...where } = entry as Input;\n return [where, $through as Input | undefined] as const;\n };\n const sought = (where: unknown, verb: string): Question => ({\n model: target,\n where: where as Input,\n unique: true,\n through: edge,\n intent: \"join\",\n verb,\n });\n let supplied: Row | undefined;\n if (first(\"create\")) supplied = create(first(\"create\"), false);\n if (first(\"connect\")) {\n const [where, through] = named(first(\"connect\"));\n const question = sought(where, \"connect\");\n const found = this.#store.one(question);\n // The row itself is found as its own data leaves it, and its own data takes the key it would be found for: neither comes first.\n if (found === row && this.#store.reads(question, Object.keys(said)))\n throw new NestedWriteError(\n `Nested operation 'connect' on relation '${edge.name}' depends on an earlier 'update' target write in the same nested write. Split these operations into separate queries.`,\n edge.name,\n { meta: { operation: \"connect\", conflictsWith: \"update\" } }\n );\n supplied = adopt(found, \"connect\", through);\n }\n const either = first(\"connectOrCreate\") as Input | undefined;\n if (either) {\n const asked = { ...sought(either.where, \"connectOrCreate\"), makes: true };\n const [found] = this.#store.rows(asked);\n const through = either.$through as Input | undefined;\n // A row created because none was found is created while none is there: its own key says so, or the call asks again.\n if (!found)\n if (this.#keyed(asked, either.create as Input))\n this.#store.created(asked);\n else this.#store.absent(asked);\n supplied = found\n ? adopt(found, \"connectOrCreate\", through)\n : create(either.create as Input, true, through);\n }\n const upsert = first(\"upsert\") as Input | undefined;\n if (upsert) {\n const found = current(\n {\n intent: \"update\",\n writes: this.#writes(target, upsert.update as Input),\n verb: \"upsert\",\n makes: true,\n },\n upsert.where as Input | undefined\n );\n if (found)\n then.push(() => this.#write(target, found, upsert.update as Input));\n else supplied = create(upsert.create as Input);\n }\n if (supplied && held) take(this.#reaching(edge, supplied));\n const update = first(\"update\") as Input | undefined;\n if (update) {\n const data = update.data as Input;\n // The row the relation was just given is the one updated, where nothing more is asked of it; else the one it reaches once the row's own write is made.\n then.push(() =>\n this.#write(\n target,\n supplied && !update.where\n ? supplied\n : this.#store.one({\n model: target,\n where: update.where as Input | undefined,\n member: { edge, of: of! },\n intent: \"update\",\n writes: this.#writes(target, data),\n verb: \"update\",\n }),\n data\n )\n );\n }\n if (held) return { takes, then };\n for (const next of then) next();\n return { takes, then: [] };\n }\n\n /** A set: the rows it names are the relation's members, and no other. */\n #set(parent: Row, edge: Membership, entries: Input[]): void {\n const through: (Input | undefined)[] = [];\n const kept = entries.map(({ $through, ...where }) => {\n through.push($through as Input | undefined);\n return this.#store.one({\n model: edge.target,\n where,\n unique: true,\n through: edge,\n intent: \"join\",\n verb: \"set\",\n });\n });\n const others: Question = {\n ...this.#within(parent, edge),\n except: kept.map((row) => this.#schema.identity(edge.target, row)),\n intent: \"join\",\n verb: \"set\",\n strict: `Cannot clear relation '${edge.name}': a connected record may not be disconnected by this call.`,\n };\n if (edge.kind === \"junction\") {\n this.#store.writable(others);\n this.#store.unlink(edge, parent, undefined, kept);\n } else if (edge.clearability.kind === \"none\") {\n // A member that cannot give its key up cannot be taken out.\n if (this.#store.rows(others).length > 0)\n throw new NestedWriteError(\n `Cannot set relation '${edge.name}' because foreign key field(s) ${sideFields(\n edge,\n \"target\"\n ).join(\n \", \"\n )} are required: rows removed from the set cannot be disconnected. Delete them instead.`,\n edge.name\n );\n } else this.#store.all(others, this.#cleared(edge));\n for (const [at, row] of kept.entries())\n this.#join(parent, edge, row, \"set\", through[at]);\n }\n\n #relate(parent: Row, edge: Membership, payload: Input): void {\n // In the order the verbs take effect, whatever order they were written in.\n for (const verb of [\"disconnect\", \"delete\"])\n for (const entry of list(payload[verb]))\n Verbs.#nested[verb]!.call(this, parent, edge, entry as Input);\n if (payload.set !== undefined)\n this.#set(parent, edge, list(payload.set) as Input[]);\n for (const verb of Object.keys(Verbs.#nested).slice(2)) {\n const entries = list(payload[verb]) as Input[];\n // A row a list of connects names twice is named once: joining it may give it another key, by which the second would not find it.\n const once =\n verb === \"connect\"\n ? new Map(\n entries.map((entry) => {\n const { $through: _, ...where } = entry;\n return [\n JSON.stringify(where, (_key, value) =>\n typeof value === \"bigint\" ? `${value}n` : value\n ),\n entry,\n ];\n })\n ).values()\n : entries;\n for (const entry of once)\n Verbs.#nested[verb]!.call(this, parent, edge, entry);\n }\n }\n\n /** One row as the caller asked for it: none is no row of the call's. `kinds`: what the call may do to it. */\n #one(model: AnyModel, args: Arguments, kinds: WriteKind[]) {\n const shows = this.#store.watch?.own(this.#q, model, args, kinds);\n const projection =\n shows?.projection ?? this.#q.prepareProjection(model, args);\n const said = (rows: Input[], kind = kinds[0]) => {\n if (rows.length === 0)\n throw new NotFoundError(nameOf(model), this.#operation.operation);\n const read = this.#q.decodeResult(\n rows,\n this.#operation.operation,\n (raw) => this.#q.decodeProjection(projection.shape, raw)\n );\n return (shows?.cut(read, kind) ?? read)[0];\n };\n return { projection, said };\n }\n\n /** The call's row, read as the caller asked once the writes before this are sent. */\n #answering(\n model: AnyModel,\n row: Row,\n args: Arguments,\n kind?: WriteKind,\n { projection, said } = this.#one(model, args, kind ? [kind] : [])\n ) {\n let value: unknown;\n this.#store.read(row, projection, (rows) => {\n value = said(rows);\n });\n return () => value;\n }\n\n /** Whether a write of rows of `model` writes nothing but what `set` says of them, and no key: one statement names the rows itself. */\n #plain(model: AnyModel, data: Input, set: Input) {\n return (\n this.#relationsOf(model, data).length === 0 &&\n Object.keys(set).length > 0 &&\n !this.#schema.keys(model).some((key) => set[key] !== undefined)\n );\n }\n\n /** What a delete does to a row of `model`: a row its model keeps is updated. */\n #removes(model: AnyModel): WriteKind {\n return this.#operation.scope?.rows.tombstones?.has(nameOf(model))\n ? \"update\"\n : \"delete\";\n }\n\n /** A verb over many rows answers with them as the caller selected them, or with their number. */\n #many(model: AnyModel, args: Arguments, kind: WriteKind) {\n const select = args.select as Input | undefined;\n const shows = this.#store.watch?.own(this.#q, model, args, [kind]);\n const projection =\n shows?.projection ??\n (select && this.#q.prepareProjection(model, { select }));\n const decoded = (rows: Input[]) => {\n const read = this.#q.decodeResult(\n rows,\n this.#operation.operation,\n (raw) => this.#q.decodeProjection(projection!.shape, raw)\n );\n if (!shows) return read;\n shows.cut(read, kind);\n // Rows read only to be shown are answered as their number.\n return select ? read : { count: read.length };\n };\n /** The rows written by their keys, read again once every one is written. */\n const again = (rows: Row[], verb: \"createMany\" | \"updateMany\") => {\n const returned: Input[] = [];\n if (projection && rows.length > 0)\n this.#store.series(model, rows, projection, verb, (read) =>\n returned.push(...read)\n );\n return () =>\n projection\n ? decoded(returned)\n : {\n // Of rows created, as many as the database said it wrote.\n count:\n verb === \"createMany\" ? this.#store.written(rows) : rows.length,\n };\n };\n /** What a verb told to write no row answers. */\n const none = () => (select ? [] : { count: 0 });\n return { projection, decoded, again, none };\n }\n\n create(model: AnyModel, args: Arguments, raw: Input) {\n const data = this.#paired(args.data as Input, raw.data);\n const shown = this.#one(model, args, [\"create\"]);\n // A row that is nothing but itself is written at once, where its statement says what the call answers.\n const later =\n this.#relationsOf(model, data).length === 0 &&\n this.#store.skipping(\n model,\n [[data, this.#stated(data)]],\n shown.projection,\n false\n );\n if (later) return () => shown.said(later.sent!.rows);\n return this.#answering(\n model,\n this.#make(model, data, {}),\n args,\n \"create\",\n shown\n );\n }\n\n createMany(model: AnyModel, args: Arguments, raw: Input) {\n const entries = this.#paired(list(args.data) as Input[], list(raw.data));\n const { projection, decoded, again } = this.#many(model, args, \"create\");\n // A unit handed over that writes nothing is no unit.\n if (entries.length === 0 && this.#store.handed)\n engineFault(\"No data to insert for createMany.\");\n const bearing = entries.some(\n (data) => this.#relationsOf(model, data).length > 0\n );\n // Rows that are nothing but themselves are written at once, where one statement says what the call answers: and passes duplicates by, where it is asked to.\n const later = bearing\n ? undefined\n : this.#store.skipping(\n model,\n entries.map((data) => [data, this.#stated(data)]),\n projection,\n args.skipDuplicates === true\n );\n if (later) {\n // Each is one of the call's own rows, written where their statement is: of rows passed by, none is known to be.\n if (!args.skipDuplicates) for (const _ of entries) this.#store.member();\n return () =>\n projection\n ? decoded(later.sent!.rows)\n : { count: later.sent!.rowCount };\n }\n if (args.skipDuplicates) {\n // Else each row, with what hangs on it, is undone alone where it is one too many.\n const rows: Row[] = [];\n for (const data of entries)\n this.#store.attempt(\n () => {\n const row = this.#make(model, data, {});\n rows.push(row);\n return row;\n },\n bearing ? \"rows involving nested writes\" : \"duplicate rows\"\n );\n return again(rows, \"createMany\");\n }\n return again(\n entries.map((data) => {\n this.#store.member();\n return this.#make(model, data, {});\n }),\n \"createMany\"\n );\n }\n\n update(model: AnyModel, args: Arguments, raw: Input) {\n const data = this.#paired(args.data as Input, raw.data);\n const set = this.#store.values(model, \"update\", data, this.#stated(data));\n const question: Question = {\n model,\n where: args.where as Input,\n unique: true,\n intent: \"update\",\n writes: this.#writes(model, data, set),\n };\n if (this.#plain(model, data, set)) {\n const { projection, said } = this.#one(model, args, [\"update\"]);\n const later = this.#store.all(\n { ...question, must: true },\n set,\n projection\n );\n return () => said(later.sent!.rows);\n }\n const row = this.#store.one(question);\n this.#write(model, row, data, false);\n return this.#answering(model, row, args, \"update\");\n }\n\n updateMany(model: AnyModel, args: Arguments, raw: Input) {\n const data = this.#paired(args.data as Input, raw.data);\n const { projection, decoded, again, none } = this.#many(\n model,\n args,\n \"update\"\n );\n if (args.limit === 0) return none;\n const relations = this.#relationsOf(model, data);\n const set = this.#store.values(model, \"update\", data, this.#stated(data));\n const question: Question = {\n model,\n where: args.where as Input | undefined,\n limit: args.limit as number | undefined,\n intent: \"update\",\n writes: this.#writes(model, data, set),\n };\n const beside = !relations.some(({ edge }) => this.#holds(edge));\n if (this.#plain(model, data, set)) {\n const later = this.#store.all(question, set, projection);\n return () =>\n projection\n ? decoded(later.sent!.rows)\n : { count: this.#store.writer.count(later.sent!) };\n }\n const rows = this.#store.rows(question);\n this.#several = rows.length;\n // Rows that take the same values are written side by side, before what their relations ask.\n if (beside)\n for (const row of rows) this.#store.update(row, set, question.writes);\n for (const [at, row] of rows.entries()) {\n this.#store.member();\n // Each row is written of its own copy of what the caller wrote: what a default fills is that row's own.\n const own =\n at === 0\n ? data\n : this.#store.copy(`${at}`, () =>\n this.#paired(\n parseStamped(\n this.#operation.scope?.rows.stamps ?? new Map(),\n () => this.#schema.update(model, raw.data as Input)\n ),\n raw.data\n )\n );\n if (beside)\n for (const { edge, payload } of this.#relationsOf(model, own))\n this.#relate(row, edge, payload);\n else this.#write(model, row, own);\n }\n return again(rows, \"updateMany\");\n }\n\n upsert(model: AnyModel, args: Arguments, raw: Input) {\n const update = this.#paired(args.update as Input, raw.update);\n const guards = [args.targetWhere, args.setWhere].filter(Boolean);\n const create = this.#paired(args.create as Input, raw.create);\n const question: Question = {\n model,\n where: args.where as Input,\n unique: true,\n intent: \"update\",\n writes: this.#writes(model, update),\n };\n const followed = this.#relationsOf(model, update);\n const related = this.#relationsOf(model, create).length + followed.length;\n // An update that says nothing writes nothing: no statement that would write what every update takes.\n if (\n related + guards.length === 0 &&\n Object.keys(this.#stated(update)).length > 0\n ) {\n const { projection, said } = this.#one(model, args, [\"create\", \"update\"]);\n const later = this.#store.either(\n question,\n create,\n this.#stated(create),\n this.#store.values(model, \"update\", update, this.#stated(update)),\n projection\n );\n if (later)\n return () =>\n said(later.sent!.rows, later.created ? \"create\" : \"update\");\n }\n const [found] = this.#store.rows({ ...question, makes: true });\n // Updated where found, and where it holds what the call asks of it besides.\n const where = args.where as Input;\n const asked = {\n ...question,\n where: { ...where, AND: [...list(where.AND), ...guards] },\n };\n const matched =\n !found || guards.length === 0 || this.#store.rows(asked).length > 0;\n if (!matched) this.#store.absent(asked);\n if (!found && this.#keyed(question, create)) this.#store.created(question);\n // A row created because none was found may be refused for the key the call named: what declares the rows says what that means.\n const key = this.#store.writer.selector(question).uniqueKey;\n const refuses =\n !found &&\n key &&\n this.#keyed(question, create) &&\n this.#operation.queries.domain?.judge?.located(model);\n if (refuses)\n this.#store.saying((failure) =>\n failure instanceof UniqueConstraintError &&\n this.#store.writer.refusedFor(model, key, failure)\n ? refuses(failure)\n : failure\n );\n // An update that says nothing asks nothing of the row found.\n const updates =\n found && matched && Object.keys(this.#stated(update)).length > 0;\n // What its key may be rewritten with is asked where rows written beside it must follow that key.\n if (updates) this.#write(model, found, update, followed.length > 0);\n // The row is shown as created or as updated: as neither where the call wrote nothing of it.\n return this.#answering(\n model,\n found ?? this.#make(model, create, {}),\n args,\n found ? (updates ? \"update\" : undefined) : \"create\"\n );\n }\n\n delete(model: AnyModel, args: Arguments) {\n const { projection, said } = this.#one(model, args, [this.#removes(model)]);\n const later = this.#store.all(\n {\n model,\n where: args.where as Input,\n unique: true,\n intent: \"delete\",\n must: true,\n },\n undefined,\n projection\n );\n return () => said(later.sent!.rows);\n }\n\n deleteMany(model: AnyModel, args: Arguments) {\n const { projection, decoded, none } = this.#many(\n model,\n args,\n this.#removes(model)\n );\n if (args.limit === 0) return none;\n const later = this.#store.all(\n {\n model,\n where: args.where as Input | undefined,\n limit: args.limit as number | undefined,\n intent: \"delete\",\n },\n undefined,\n projection\n );\n return () =>\n projection\n ? decoded(later.sent!.rows)\n : { count: this.#store.writer.count(later.sent!) };\n }\n}\n","/**\n * The new write path's entry: one call, sent by itself, inside the\n * transaction its caller lends it, or handed over as one unit.\n */\nimport type { AnyDriver } from \"@drivers\";\nimport { attachCommitCertainty } from \"@drivers/driver-error-context\";\nimport { bindExecutionTransactionPhases } from \"@drivers/execution-context\";\nimport {\n attachRecordSeriesProgress,\n isVibORMError,\n TransactionError,\n UniqueConstraintError,\n} from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport { sql } from \"@sql\";\nimport type { PreparedBatchOperation } from \"../../types\";\nimport type { Arguments, Input } from \"../shared/schema\";\nimport type {\n ExecutionBinding,\n SqlOperationContext,\n} from \"../shared/sql-operation-context\";\nimport { nameOf } from \"../shared/terms\";\nimport {\n batches,\n contextOf,\n dialogue,\n prepared,\n type Transport,\n unproven,\n unsaid,\n} from \"./send\";\nimport { Lost, SEVERAL, Store } from \"./store\";\nimport { Verbs } from \"./verbs\";\n\n/** The verbs of one call, run on a store: made once, however many times the call runs them. */\nconst call = (\n store: Store,\n model: AnyModel,\n args: Arguments,\n raw: unknown\n): (() => () => unknown) => {\n let made: Verbs | undefined;\n return () => {\n made ??= new Verbs(store);\n return made[store.operation.operation as \"create\"](\n model,\n args,\n raw as Input\n );\n };\n};\n\n/** A call sent by itself, or inside the transaction its caller lends it; made again where its backend says a unit of its own that was undone is. */\nexport async function writeCall(\n operation: SqlOperationContext,\n driver: AnyDriver,\n model: AnyModel,\n args: Arguments,\n raw: unknown,\n binding?: ExecutionBinding\n): Promise<unknown> {\n for (let attempt = 1; ; attempt++)\n try {\n return await sent(operation, driver, model, args, raw, binding);\n } catch (error) {\n if (\n binding?.kind === \"borrowed-transaction\" ||\n !(await operation.again(error, attempt))\n )\n throw error;\n }\n}\n\nasync function sent(\n operation: SqlOperationContext,\n driver: AnyDriver,\n model: AnyModel,\n args: Arguments,\n raw: unknown,\n binding?: ExecutionBinding\n): Promise<unknown> {\n const seam = binding?.writeOutcome;\n // The transaction says how far its commit went; the seam hears it once.\n let phase: \"pending\" | \"ready\" | \"committed\" = \"pending\";\n const at = contextOf(operation, model);\n const lent =\n binding?.kind === \"borrowed-transaction\"\n ? binding.operationRegion\n : undefined;\n /** The unit the call is sent in: one of its own, or the one its caller lends it. */\n const open = (): Transport => {\n if (binding?.kind === \"borrowed-transaction\")\n return dialogue(\n operation,\n binding.driver,\n lent && ((body) => lent(body, at)),\n binding.memberRollback\n );\n if (!driver.supportsTransactions) return batches(operation, driver);\n return dialogue(\n operation,\n driver,\n (body) =>\n driver.withTransaction(\n body,\n undefined,\n seam\n ? bindExecutionTransactionPhases(at, {\n readyToCommit: () => {\n phase = \"ready\";\n },\n committed: () => {\n phase = \"committed\";\n },\n })\n : at\n ),\n undefined,\n true\n );\n };\n let transport = open();\n let answer: unknown;\n let store = new Store(operation, transport);\n try {\n for (let again = false; ; again = true)\n try {\n answer = await store.run(call(store, model, args, raw));\n break;\n } catch (error) {\n // A row created because none was there, refused because another writer made it meanwhile; a row read without holding it, gone since: where the unit that failed can be undone whole, the call is made again, once.\n const failure = error instanceof Lost ? error.failure : error;\n if (\n again ||\n !(failure !== error || store.raced(error)) ||\n store.segments > 0 ||\n (binding?.kind === \"borrowed-transaction\" && !lent)\n )\n throw failure;\n await transport.end(failure)?.catch(() => undefined);\n phase = \"pending\";\n transport = open();\n store = new Store(operation, transport);\n }\n } catch (error) {\n await transport.end(error);\n const loose = unproven.has(error as object);\n let failure = operation.failure(error);\n // What stands of a call that failed after a part of it was made is said with its failure; and so that its one unit may have been made.\n const made = store.segments > 0;\n if (\n (made ||\n (unsaid.has(error as object) &&\n !(error instanceof UniqueConstraintError))) &&\n !transport.holds\n )\n failure = attachRecordSeriesProgress(failure, {\n atomicity: \"segment\",\n phase: store.said ? \"result\" : \"member\",\n committedSegments: store.segments,\n // Of a unit that may have been made, nothing is known to be.\n completedMembers: made ? store.members(true) : 0,\n committedWriteMembers: made ? store.members() : 0,\n ...(loose && { mayHaveCommittedSegment: true as const }),\n });\n // What the call sent outside a transaction of its own and cannot prove undone may be there: a key already taken proves it.\n if (binding?.kind !== \"borrowed-transaction\")\n if (store.segments > 0)\n await operation.stateWriteOutcome(seam?.committedSegment, failure);\n else if (loose && !(error instanceof UniqueConstraintError))\n await operation.stateWriteOutcome(seam?.mayBeVisible, failure);\n throw failure;\n }\n store.watch?.done();\n try {\n // No tick is spent on a unit that was never opened.\n const ended = transport.end();\n if (ended) await ended;\n } catch (error) {\n if (phase === \"pending\") throw error;\n const durable = phase === \"committed\";\n const primary = isVibORMError(error)\n ? attachCommitCertainty(\n error,\n durable ? \"committed\" : \"may-have-committed\"\n )\n : error;\n await operation.stateWriteOutcome(\n durable ? seam?.committedSegment : seam?.mayBeVisible,\n primary\n );\n throw primary;\n }\n if (seam?.committedSegment)\n await operation.stateWriteOutcome(seam.committedSegment);\n return answer;\n}\n\n/**\n * A call as one unit its caller sends, among other calls' units: its\n * statements are handed over, each with what it reports where it stops the\n * unit. None where the call must hear the database to go on: what it would\n * read now, a call sent before it in the same unit may change.\n */\nexport async function prepareCall(\n operation: SqlOperationContext,\n driver: AnyDriver,\n model: AnyModel,\n args: Arguments,\n raw: unknown\n): Promise<PreparedBatchOperation<unknown> | undefined> {\n const store = new Store(operation, {\n holds: false,\n // What the call may ask before its unit is asked outside it.\n send: (statements) =>\n Promise.all(\n statements.map((statement) =>\n driver._execute<Input>(\n statement.sql,\n contextOf(operation, statement.model)\n )\n )\n ),\n end: () => undefined,\n });\n try {\n const { statements, answer } = await store.prepare(\n call(store, model, args, raw)\n );\n const guards = statements.flatMap((statement, queryIndex) =>\n statement.stops\n ? [\n {\n queryIndex,\n premise: statement.premise ?? (\"exists\" as const),\n // A statement that judges its own rows is pointed at by its place.\n probe: statement.premise\n ? statement.probe!\n : operation.driver.adapter.clauses.select(sql`1`),\n failure: statement.stops,\n model: nameOf(statement.model),\n operation: operation.operation,\n },\n ]\n : []\n );\n return {\n queries: statements.map((statement) =>\n prepared(operation, driver, statement)\n ),\n // A unit nothing can stop names no guard.\n ...(guards.length > 0 && { guards }),\n parseResult: (results) => {\n // A unit answered short is its driver's failure, said as such.\n for (let at = 0; at < statements.length; at++)\n if (!results[at])\n throw new TransactionError(\n `Driver '${driver.driverName}' omitted the prepared result for operation '${operation.operation}'.`,\n {\n meta: {\n model: operation.modelName,\n operation: operation.operation,\n },\n }\n );\n try {\n const value = answer(results as never);\n store.watch?.done();\n return value;\n } catch (error) {\n throw operation.failure(error);\n }\n },\n };\n } catch (error) {\n if (error !== SEVERAL) throw error;\n return undefined;\n }\n}\n","import { adapterPinnedTable } from \"@adapters/adapter-internals\";\nimport type { Operations } from \"@client/types\";\nimport type { AnyDriver } from \"@drivers/driver\";\nimport type { QueryExecutionContext } from \"@drivers/types\";\nimport { NotFoundError } from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { Sql } from \"@sql\";\nimport { baseOperation } from \"../../routed-operations\";\nimport type { PreparedBatchOperation } from \"../../types\";\nimport { renderers } from \"../shared/insert-value\";\nimport type { Leaf, ProjectionShape, Queries, Read } from \"../shared/query\";\nimport { engineBackend } from \"../shared/query-backend\";\nimport {\n type CallRows,\n type CallScope,\n parseStamped,\n} from \"../shared/row-scope\";\nimport {\n type Arguments,\n type EngineConfig,\n EngineSchema,\n isReadOperation,\n type Operation,\n} from \"../shared/schema\";\nimport {\n type ExecutionBinding,\n type MemberRollback,\n SqlOperationContext,\n} from \"../shared/sql-operation-context\";\nimport { SqlQueries } from \"../shared/sql-queries\";\nimport { nameOf, unsupported } from \"../shared/terms\";\nimport { prepareCall, writeCall } from \"../write\";\n\n/**\n * What a prepared read publishes before it runs.\n *\n * These are not a second statement of the read owner's decision — they are read\n * FROM it, by asking the prepared `Read` what it publishes for zero rows, so the\n * two cannot disagree for any verb.\n */\nexport interface PreparedRead {\n /**\n * The shape of the ROW the prepared statement decodes. For every verb whose\n * public value is the row (or the rows), this is the public value's shape too;\n * `count` and `exist` publish a value DERIVED from that row (`_count`), and\n * {@link PreparedRead.empty} is what tells a consumer which it is looking at.\n */\n readonly shape: ProjectionShape;\n /**\n * The PUBLIC value's own shape, which is not always the row shape: `count`\n * publishes a number and `exist` a boolean, and `findMany`/`groupBy` publish\n * a collection of rows.\n */\n readonly value: ProjectionShape | Leaf;\n /**\n * Does this read publish ONE row-like value rather than the row set? True for\n * `findUnique`, `findFirst`, `aggregate` and a selected `count`; false for\n * `findMany`, `groupBy`, a plain `count` (a number) and `exist` (a boolean).\n */\n readonly single: boolean;\n /**\n * The read owner's own publication for zero rows: `null` (a row), `[]` (the\n * set), `{}` (an aggregate record), `0` (`count`), `false` (`exist`). A\n * result codec reads the public value's kind here instead of assuming the row\n * shape is the value's shape — `count` publishes `3`, never `{_count: 3}`.\n */\n readonly empty: unknown;\n /**\n * The ONE statement this read compiles to, as the prepared `Read` built it.\n * It is the `Sql` the execution runs, read from the same construction, so\n * `buildStatement()` and the run cannot describe different queries.\n */\n readonly statement: Sql;\n}\n\n/**\n * The published facts, forwarded from the prepared `Read` itself. The read owner\n * STATES the cardinality and the public value's shape beside the statement it\n * decodes (`Queries.read`), so nothing here re-derives either from behavior.\n */\nfunction publishedFacts(value: Read): PreparedRead {\n return {\n shape: value.query.shape,\n value: value.value,\n single: value.single,\n empty: value.result([]),\n statement: value.query.sql,\n };\n}\n\n/** What the client's lifecycle knows when it runs an operation. */\nexport interface RoutedOperationExecution {\n /** This operation's immutable attribution, created with the operation. */\n readonly context: QueryExecutionContext;\n /** The driver of the engine this operation was created on. */\n readonly engineDriver: AnyDriver;\n /** A driver an existing transaction/array owner supplies for this run. */\n readonly driverOverride: AnyDriver | undefined;\n /** The existing read/write classification of the requested verb. */\n readonly isWrite: boolean;\n readonly committedWriteSegment: (() => Promise<void>) | undefined;\n readonly writeMayBeVisible: (() => Promise<void>) | undefined;\n}\n\n/**\n * One operation, before any execution.\n *\n * The client lifecycle is admission-first by construction — a stored answer must key\n * before it can look up, and an interceptor must see the payload before it calls\n * `proceed()` — so admission, the prepared read shape and the cardinality are\n * published here, exactly once, and execution consumes that same construction\n * (g4/unit03/note.md B-1). Admission itself stays lazy, because the client's own\n * `PendingOperation` is lazy (LX-01).\n */\nexport interface PreparedOperation {\n /**\n * The ONE admission of this input: the same object the statements are built\n * from, so an interceptor's `input` and the key of the call describe the\n * query that runs.\n */\n readonly args: Arguments;\n /** Present for read verbs: the one prepared read's published facts. */\n readonly read: PreparedRead | undefined;\n /** The model and the verb the caller asked for, `…OrThrow` included. */\n readonly requested: { readonly model: string; readonly operation: string };\n /**\n * Told the rows the driver returned for a read's one statement, before\n * they are decoded, on every run while it is set: what stores an answer as\n * those rows (`codec`) sets it, and decodes them later with\n * {@link PreparedOperation.prepareSingle}'s parser. A run it is set on is\n * sent alone and reads object rows.\n */\n seen?: (rows: readonly unknown[]) => void;\n execute(\n binding?: ExecutionBinding,\n attribution?: QueryExecutionContext\n ): Promise<unknown>;\n /**\n * Runs it on the driver its owner selected.\n *\n * - root: no binding; the call owns its standalone envelope.\n * - an array owner's sequential fallback (`driverOverride`): the exact\n * borrowed driver and NO grant — the array owner's transaction is the unit,\n * so the call opens no scope and a failing statement poisons the array's.\n * - inside `$transaction(callback)` (the engine is bound to a transaction\n * driver): the caller opened no scope for this operation, so the right to\n * open one is TRANSFERRED. The call then applies the same envelope rule it\n * applies everywhere — a statement-atomic write runs directly on the\n * caller's transaction driver, a multi-statement one opens exactly one\n * nested region and rolls back only its own work. The second grant is\n * member isolation inside whichever of those two scopes is current.\n *\n * What a write left durable is a transport fact: the transport states it,\n * where it learns it, through the two notifications of the execution.\n */\n run(execution: RoutedOperationExecution): Promise<unknown>;\n prepareBatch(\n attribution?: QueryExecutionContext\n ): Promise<PreparedBatchOperation<unknown> | undefined>;\n /**\n * The same package as {@link PreparedOperation.prepareBatch}, for the verbs\n * whose preparation reaches no driver and therefore completes synchronously:\n * a read, which queues its one statement and states its parser in one call.\n * Every other verb needs the asynchronous fold and answers `undefined`.\n */\n prepareSingle(\n attribution?: QueryExecutionContext\n ): PreparedBatchOperation<unknown> | undefined;\n}\n\n/** A class, not a closure: one is made per call, and its methods are made once. */\nclass PreparedCommand implements PreparedOperation {\n declare seen?: (rows: readonly unknown[]) => void;\n readonly #config: EngineConfig;\n readonly #queries: Queries;\n readonly #modelName: string;\n readonly #requested: Operations;\n readonly #operation: Operation;\n readonly #rawArgs: unknown;\n readonly #scope: CallScope | undefined;\n #admitted: Arguments | undefined;\n #prepared: Read | undefined;\n #facts: PreparedRead | undefined;\n\n constructor(\n config: EngineConfig,\n queries: Queries,\n modelName: string,\n requested: Operations,\n rawArgs: unknown,\n rows?: CallRows\n ) {\n // The call's one instant lives with the prepared call, so a replan and\n // every occurrence it re-admits share it.\n let instant: Date | undefined;\n this.#scope = rows?.prepare(queries, () => (instant ??= new Date()));\n this.#config = config;\n this.#queries = queries;\n this.#modelName = modelName;\n this.#requested = requested;\n this.#operation = baseOperation(requested);\n this.#rawArgs = rawArgs;\n }\n\n get #model(): AnyModel {\n return this.#config.schema[this.#modelName]!;\n }\n\n get requested(): { readonly model: string; readonly operation: string } {\n return { model: this.#modelName, operation: this.#requested };\n }\n\n /** What a verb that must find its row fails with where there is none. */\n get #missing(): (() => NotFoundError) | undefined {\n return this.#requested === this.#operation\n ? undefined\n : () =>\n new NotFoundError(nameOf(this.#model) ?? \"unknown\", this.#requested);\n }\n\n /**\n * Admitted where a required field the call's stamps write may be left out,\n * with the projection keys its domain declares kept beside the schema's.\n */\n get args(): Arguments {\n if (this.#admitted) return this.#admitted;\n const { schema } = this.#queries;\n const stamps = this.#scope?.rows.stamps;\n const admit = () =>\n this.#scope?.domain.project?.admit(\n schema,\n this.#model,\n this.#operation,\n this.#rawArgs\n ) ?? schema.admit(this.#model, this.#operation, this.#rawArgs);\n return (this.#admitted =\n stamps === undefined ? admit() : parseStamped(stamps, admit));\n }\n\n #read(): Read | undefined {\n if (!isReadOperation(this.#operation)) return undefined;\n return (this.#prepared ??= (\n this.#scope?.domain.reads(this.#scope) ?? this.#queries\n ).read(this.#model, this.#operation, this.args));\n }\n\n get read(): PreparedRead | undefined {\n const value = this.#read();\n return value && (this.#facts ??= publishedFacts(value));\n }\n\n /** This call's context; only the binding, preparation and attribution vary. */\n #context(\n preparing: boolean,\n attribution?: QueryExecutionContext,\n binding?: ExecutionBinding\n ): SqlOperationContext {\n const { driver } = this.#config;\n return new (\n driver.backend\n ? engineBackend(driver.backend).context\n : SqlOperationContext\n )(\n this.#queries.schema,\n driver,\n this.#modelName,\n this.#operation,\n binding,\n preparing,\n attribution,\n this.#scope\n );\n }\n\n // Not `async`: the promise is handed back as it is. An async function\n // adopts a returned promise a microtask later, so a refusal thrown before\n // any I/O (V8003) sat rejected with no handler in between, which workerd\n // under nodejs_compat reports as an unhandled rejection.\n execute(\n binding?: ExecutionBinding,\n attribution?: QueryExecutionContext\n ): Promise<unknown> {\n try {\n const context = this.#context(false, attribution, binding);\n const value = this.#read();\n return value\n ? context.run(() => context.publish(value, this.#missing, this.seen))\n : writeCall(\n context,\n this.#config.driver,\n this.#model,\n this.args,\n this.#rawArgs,\n binding\n );\n } catch (error) {\n return Promise.reject(error);\n }\n }\n\n run(execution: RoutedOperationExecution): Promise<unknown> {\n const { driverOverride, engineDriver } = execution;\n const writeOutcome =\n execution.isWrite &&\n (execution.committedWriteSegment || execution.writeMayBeVisible)\n ? {\n committedSegment: execution.committedWriteSegment,\n mayBeVisible: execution.writeMayBeVisible,\n }\n : undefined;\n if (driverOverride)\n return this.execute(\n { driver: driverOverride, kind: \"borrowed-transaction\", writeOutcome },\n execution.context\n );\n if (engineDriver === this.#config.driver)\n return this.execute(\n writeOutcome && { kind: \"standalone\", writeOutcome },\n execution.context\n );\n const region: MemberRollback = (execute, scoped) =>\n engineDriver.withTransaction(execute, undefined, scoped);\n return this.execute(\n {\n driver: engineDriver,\n kind: \"borrowed-transaction\",\n memberRollback: region,\n operationRegion: region,\n writeOutcome,\n },\n execution.context\n );\n }\n\n prepareSingle(\n attribution?: QueryExecutionContext\n ): PreparedBatchOperation<unknown> | undefined {\n // Preparing admits the input whatever the verb compiles to: an operation\n // that publishes no single query still answers for the payload it was\n // handed, exactly as `prepareBatch` does.\n this.args;\n // A write is prepared by asking: its owner asks for the package.\n const value = this.#read();\n if (!value) return undefined;\n const context = this.#context(true, attribution);\n context.publishPrepared(value, this.#missing);\n return context.preparedBatch();\n }\n\n async prepareBatch(\n attribution?: QueryExecutionContext\n ): Promise<PreparedBatchOperation<unknown> | undefined> {\n return this.#read()\n ? this.prepareSingle(attribution)\n : prepareCall(\n this.#context(true, attribution),\n this.#config.driver,\n this.#model,\n this.args,\n this.#rawArgs\n );\n }\n}\n\n/**\n * Prepared queries per driver result parser. Weak: a schema and adapter can\n * outlive every client, and a transient driver's parser (with whatever it\n * captures) must be released with it. A driver without a parser has one slot.\n */\ninterface QueriesByResult {\n readonly parsers: WeakMap<object, Queries>;\n none?: Queries;\n}\n\n/**\n * Engines over the same resolved registry share one schema view and, per\n * adapter and result parser, one query owner: both derive only from those\n * inputs, so a client created per request reuses the warm per-model views\n * instead of rebuilding them.\n */\nconst sharedEngines = new WeakMap<\n object,\n {\n schema: EngineSchema;\n queries: WeakMap<object, QueriesByResult>;\n }\n>();\n\nfunction sharedQueries(config: EngineConfig): Queries {\n const { adapter, result, backend } = config.driver;\n const createQueries = (\n ...args: ConstructorParameters<typeof SqlQueries>\n ): Queries =>\n backend\n ? new (engineBackend(backend).queries)(...args)\n : new SqlQueries(...args);\n const key = config.resolved?.registry;\n let shared = key && sharedEngines.get(key);\n if (!shared) {\n shared = {\n schema: new EngineSchema(config.schema, config.resolved),\n queries: new WeakMap(),\n };\n if (key) sharedEngines.set(key, shared);\n }\n let byResult = shared.queries.get(adapter);\n if (!byResult)\n shared.queries.set(adapter, (byResult = { parsers: new WeakMap() }));\n if (!result) {\n return (byResult.none ??= createQueries(shared.schema, adapter, result));\n }\n let queries = byResult.parsers.get(result);\n if (!queries) {\n queries = createQueries(shared.schema, adapter, result);\n byResult.parsers.set(result, queries);\n }\n return queries;\n}\n\n/** The one operation owner of a client lineage: what its engines consult. */\nexport type CommandEngine = ReturnType<typeof createCommandEngine>;\n\n/**\n * The engine of one client lineage, bound to that client's root driver.\n * `config.resolved` is the client's own already-composed topology index and\n * schema registry, handed over by identity: nothing is hydrated, validated or\n * registered a second time (note.md B-3).\n */\nexport function createCommandEngine(config: EngineConfig) {\n // One query owner for the prepared read. The adapter is pinned by identity\n // across transaction scoping (`TransactionBoundDriver` copies\n // `baseDriver.adapter`), so the statement and shape prepared here are valid for\n // every binding of this driver's lineage.\n const queries = sharedQueries(config);\n let byAdapter = renderers.get(config.schema);\n if (!byAdapter) renderers.set(config.schema, (byAdapter = new WeakMap()));\n byAdapter.set(config.driver.adapter, queries);\n const { driver } = config;\n const prepare = (\n modelName: string,\n requested: Operations,\n rawArgs: unknown,\n rows?: CallRows\n ): PreparedOperation =>\n new PreparedCommand(config, queries, modelName, requested, rawArgs, rows);\n /**\n * `$rows`: `model`'s rows a root read under the chain's rules takes, as a raw read's\n * `FROM` item named `alias`. A model whose layers gate a field's reads is\n * refused: `SELECT *` would disclose it to every row.\n */\n const rowsOf = (\n model: AnyModel,\n alias: string,\n rows: CallRows | undefined,\n instant: () => Date\n ): Sql => {\n if (driver.backend) unsupported(\"$rows() needs an SQL driver\");\n if (adapterPinnedTable(queries.adapter) === undefined)\n unsupported(\n \"$rows() needs a driver bound to its database (a MySQL namespace): a caller's CTE could otherwise stand for a table its rows read\"\n );\n const scope = rows?.prepare(queries, instant);\n scope?.domain.project?.refuseGatedRows(model);\n const view = (scope ? scope.domain.reads(scope) : queries) as SqlQueries;\n return view.rowsOf(model, alias);\n };\n /**\n * `driver` is the root driver the engine is bound to: an operation run on\n * any other driver runs in a scope its owner opened.\n */\n return { driver, prepare, rowsOf };\n}\n","/**\n * CLIENT-LEVEL `omit` — `defaultOmit()({ user: { passwordHash: true } })`.\n *\n * A per-client DEFAULT, not a schema rule. It is applied by rewriting the\n * payload before validation: every node that will produce a row of a configured\n * model gains the configured `omit`, unless the caller already spoke about that\n * node's projection. From there it is an ordinary query-level `omit` and travels\n * the one path that exists (`withOmitProjection` desugars it into `select`).\n *\n * Why rewrite the ARGS instead of teaching the engine a second default? Because\n * the schemas are shared: two clients over the same models must accept exactly\n * the same payloads, and a per-client default that changed what VALIDATES would\n * break that. Rewriting args keeps the client option where it belongs — a\n * default for what a query did not say — and leaves one implementation of the\n * projection itself.\n *\n * PRECEDENCE, in the order the rules fire:\n * 1. an explicit `select` on the node overrides the CLIENT default: nothing\n * global is injected there, while a query-level `omit` still subtracts;\n * 2. the node's own `omit` wins per FIELD: `{ passwordHash: false }` re-includes\n * a globally omitted column, `{ other: true }` adds to the default;\n * 3. otherwise the client default applies as written.\n *\n * Model-level `.omit()` is above all three and is not represented here at all —\n * those fields have no `omit` key to name (see\n * `src/validation/model/core/projection.ts`).\n *\n * COST. A client without the official extension never builds a resolver or\n * calls `applyClientOmit`. With the extension, one shallow walk of the\n * `select`/`include` tree runs per query, copying only the nodes it changes.\n */\n\nimport { VibORMError, VibORMErrorCode } from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport type {\n ResolvedRelationIndex,\n ResolvedSlot,\n ResolvedVariantEdge,\n} from \"@schema/validation/relation-resolution\";\nimport { projectableScalarNames } from \"@validation/model/core/projection\";\nimport { junctionModelOf } from \"@validation/relations/helpers\";\nimport { isRecord as isPlainRecord } from \"@validation/value-guards\";\nimport type { Operations } from \"./types\";\n\n/** Fields a client hides by default, per model key of the schema. */\nexport type ClientOmitConfig<S extends Record<string, AnyModel>> = {\n [K in keyof S]?: ClientModelOmit<S[K]>;\n};\n\n/**\n * The scalars of `M` a client may hide — every scalar except the ones the\n * MODEL already hides for good (naming one of those has no `omit` key to name;\n * see `@validation/model/core/projection`).\n *\n * The `any` arm is not decoration. A schema-generic extension sees\n * `Model<any>`, whose `scalars` is `any` — and the subtraction above would then\n * cancel to `never`, leaving `Partial<Record<never, true>>`, a config object\n * with no known properties. Answering `string` preserves the contextual\n * literal `true` until a concrete schema binds the official extension.\n */\ntype ProjectableKeysOf<M extends AnyModel> = 0 extends 1 &\n M[\"~\"][\"state\"][\"scalars\"]\n ? string\n : Extract<\n Exclude<\n keyof M[\"~\"][\"state\"][\"scalars\"],\n M[\"~\"][\"state\"][\"omit\"] extends Record<string, true>\n ? keyof M[\"~\"][\"state\"][\"omit\"]\n : never\n >,\n string\n >;\n\n/**\n * The fields one model hides by default, each flagged `true`.\n *\n * `true` only — not `boolean`. Two reasons, and they are the same reason:\n * - a `false` here would be a key that does nothing (the resolver only ever\n * acts on `=== true`), and a config key that silently does nothing is the\n * shape this codebase refuses; per-field re-inclusion belongs on the QUERY\n * (`omit: { passwordHash: false }`), which is where it can be undone;\n * - `boolean` as the contextual type widens the `true` a caller writes, and a\n * widened flag is a flag the RESULT TYPE cannot resolve — it would render\n * `passwordHash?: string` on a client that hides the column outright.\n */\nexport type ClientModelOmit<M extends AnyModel> = Partial<\n Record<ProjectableKeysOf<M>, true>\n>;\n\ntype ClientOmitKeys<Value> = Value extends unknown ? keyof Value : never;\n\ntype ClientOmitEntry<\n Given,\n ModelName extends PropertyKey,\n> = Given extends unknown\n ? ModelName extends keyof Given\n ? Given[ModelName]\n : never\n : never;\n\n/** Structural exactness for a direct client-default omit configuration. */\nexport type ExactClientOmitConfig<\n Given,\n S extends Record<string, AnyModel>,\n> = Record<Exclude<ClientOmitKeys<Given>, keyof S>, never> & {\n [ModelName in Extract<ClientOmitKeys<Given>, keyof S>]?: Record<\n Exclude<\n ClientOmitKeys<ClientOmitEntry<Given, ModelName>>,\n keyof ClientModelOmit<S[ModelName]>\n >,\n never\n >;\n};\n\n/**\n * Resolves a model to the fields this client hides by default, and carries the\n * one resolved topology index the recursion walks.\n *\n * The index travels WITH the resolver because the two are used together at every\n * node and are settled together when the official extension is applied: the\n * resolver answers \"which columns\", the index answers \"which model is on the\n * other side of this key\" — without invoking a target getter (§11.4.11).\n */\nexport interface ClientOmitResolver {\n /** The fields this client hides by default for one model. */\n readonly omit: (model: AnyModel) => Record<string, boolean> | undefined;\n readonly relations: ResolvedRelationIndex;\n}\n\n/**\n * Build the model → default-omit lookup from the fields `defaults` hides.\n * Keyed by model IDENTITY so a nested relation resolves through its\n * `ResolvedSlot` target without a name round-trip.\n */\nexport const createClientOmitResolver = <S extends Record<string, AnyModel>>(\n schema: S,\n config: ClientOmitConfig<S>,\n relations: ResolvedRelationIndex\n): ClientOmitResolver => {\n const byModel = new Map<AnyModel, Record<string, boolean>>();\n for (const key of Object.keys(config)) {\n // `defaults` wrote the config, naming only models of this schema.\n const model = schema[key]!;\n const entry = config[key as keyof ClientOmitConfig<S>];\n if (!isPlainRecord(entry)) continue;\n const projectable = new Set(projectableScalarNames(model));\n const flags: Record<string, boolean> = {};\n for (const field of Object.keys(entry)) {\n if (!projectable.has(field)) {\n throw new VibORMError(\n `Client 'omit' names field '${field}' on model '${key}', which is not a readable scalar of that model.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model: key, field } }\n );\n }\n // `omitted` writes each field it hides as true, and nothing else.\n flags[field] = true;\n }\n byModel.set(model, flags);\n }\n return { omit: (model: AnyModel) => byModel.get(model), relations };\n};\n\n/**\n * The operations whose top-level payload is a model row (or rows). A bulk write\n * is NOT here: it answers `{ count }` unless the CALLER asked for a projection,\n * and a client default must never be what flips a return shape. Its nested\n * nodes are covered anyway — a bulk write projects scalars only.\n */\nexport const PROJECTING_OPERATIONS: ReadonlySet<string> = new Set([\n \"findFirst\",\n \"findFirstOrThrow\",\n \"findMany\",\n \"findUnique\",\n \"findUniqueOrThrow\",\n \"create\",\n \"update\",\n \"upsert\",\n \"delete\",\n]);\n\n/** A bulk write already carrying a projection: the caller opted into rows. */\nconst bulkWriteProjects = (\n operation: string,\n args: Record<string, unknown>\n): boolean =>\n (operation === \"createMany\" ||\n operation === \"updateMany\" ||\n operation === \"deleteMany\") &&\n args.omit !== undefined;\n\n/**\n * Rewrite one payload so every projecting node carries the client defaults.\n * Returns the SAME object when nothing changed, so an unaffected query is not\n * copied.\n */\nexport const applyClientOmit = (\n model: AnyModel,\n operation: Operations | string,\n args: Record<string, unknown>,\n resolve: ClientOmitResolver\n): Record<string, unknown> => {\n const projects =\n PROJECTING_OPERATIONS.has(operation) || bulkWriteProjects(operation, args);\n if (!projects) return args;\n return rewriteNode(model, args, resolve);\n};\n\n/**\n * One node of the projection tree. `select` present means the caller stated the\n * projection, so the client default is not injected. The node's own `omit`\n * remains for validation to subtract, and relation children are still visited.\n */\nconst rewriteNode = (\n model: AnyModel,\n node: Record<string, unknown>,\n resolve: ClientOmitResolver\n): Record<string, unknown> => {\n const selectValue = node.select;\n const includeValue = node.include;\n const hasSelect = isPlainRecord(selectValue);\n\n const nextSelect = hasSelect\n ? rewriteRelationMap(model, selectValue, resolve)\n : selectValue;\n const nextInclude = isPlainRecord(includeValue)\n ? rewriteRelationMap(model, includeValue, resolve)\n : includeValue;\n\n const defaults = hasSelect ? undefined : resolve.omit(model);\n const nextOmit = defaults ? mergeOmit(defaults, node.omit) : node.omit;\n\n if (\n nextSelect === selectValue &&\n nextInclude === includeValue &&\n nextOmit === node.omit\n ) {\n return node;\n }\n\n const next: Record<string, unknown> = { ...node };\n if (nextSelect !== selectValue) next.select = nextSelect;\n if (nextInclude !== includeValue) next.include = nextInclude;\n if (nextOmit !== node.omit) next.omit = nextOmit;\n return next;\n};\n\n/**\n * The client defaults with the caller's own `omit` layered on top, per field —\n * so `{ passwordHash: false }` re-includes exactly one globally hidden column\n * and leaves the rest hidden. Returns the caller's value untouched when it\n * already overrides every default (nothing to add).\n */\nconst mergeOmit = (\n defaults: Record<string, boolean>,\n local: unknown\n): Record<string, unknown> => {\n if (!isPlainRecord(local)) return { ...defaults };\n const merged: Record<string, unknown> = { ...defaults };\n for (const field of Object.keys(local)) merged[field] = local[field];\n return merged;\n};\n\n/**\n * `$through: true` is the junction model's default row, so the junction model's\n * client default applies to it as to any read of that model. An explicit\n * `{ select }` states its columns, and stands as a stated `select` does.\n */\nconst rewriteLinkRow = (\n resolved: ResolvedSlot,\n node: Record<string, unknown>,\n resolve: ClientOmitResolver\n): Record<string, unknown> => {\n const model = junctionModelOf(resolved);\n const defaults = model && resolve.omit(model);\n if (!defaults) return node;\n const omitted = (map: unknown) => {\n if (!isPlainRecord(map) || map.$through !== true) return map;\n return {\n ...map,\n $through: {\n select: Object.fromEntries(\n projectableScalarNames(model)\n .filter((field) => defaults[field] !== true)\n .map((field) => [field, true])\n ),\n },\n };\n };\n const select = omitted(node.select);\n const include = omitted(node.include);\n return select === node.select && include === node.include\n ? node\n : { ...node, select, include };\n};\n\n/**\n * Visit the relation entries of a `select`/`include` map. A bare `true` is\n * promoted to `{ omit: … }` only when the target model has defaults — otherwise\n * the shorthand is left exactly as written, which keeps the payload (and its\n * cache key) identical for the models nobody configured.\n */\nconst rewriteRelationMap = (\n model: AnyModel,\n map: Record<string, unknown>,\n resolve: ClientOmitResolver\n): Record<string, unknown> => {\n const slots = resolve.relations.get(model);\n let changed = false;\n const next: Record<string, unknown> = { ...map };\n\n for (const key of Object.keys(map)) {\n const resolved = slots?.get(key);\n if (!resolved) continue;\n const value = map[key];\n\n // ONE index, split here by the settled EDGE: a direct variant carrier spans\n // several targets and projects a tagged envelope; every other slot — an\n // ordinary pair, or a bound inverse view of one carrier member — reaches\n // exactly one model.\n const carrier = directVariantCarrier(resolved);\n if (carrier) {\n const rewritten = rewriteVariantCarrier(carrier, value, resolve);\n if (rewritten !== value) {\n next[key] = rewritten;\n changed = true;\n }\n continue;\n }\n\n const target = slotTarget(resolved, model);\n\n if (value === true) {\n const defaults = resolve.omit(target);\n if (!defaults) continue;\n next[key] = { omit: { ...defaults } };\n changed = true;\n continue;\n }\n if (!isPlainRecord(value)) continue;\n\n const rewritten = rewriteLinkRow(\n resolved,\n rewriteNode(target, value, resolve),\n resolve\n );\n if (rewritten !== value) {\n next[key] = rewritten;\n changed = true;\n }\n }\n\n return changed ? next : map;\n};\n\n/** The direct carrier edge of a variant slot — never a bound inverse's view. */\nexport const directVariantCarrier = (\n resolved: ResolvedSlot\n): ResolvedVariantEdge | undefined => {\n if (resolved.member) return undefined;\n const edge = resolved.edge;\n return edge.kind === \"variantRowCarrier\" ||\n edge.kind === \"variantJunctionCarrier\"\n ? edge\n : undefined;\n};\n\n/**\n * The SETTLED model on the other side of one slot.\n *\n * Every model here came out of the gate's own registration, so no getter is\n * invoked and no `targetEntries()` is walked: the edge already names both\n * endpoints, and a bound inverse names the carrier that holds the storage.\n */\nexport const slotTarget = (\n resolved: ResolvedSlot,\n source: AnyModel\n): AnyModel => {\n const edge = resolved.edge;\n if (edge.kind === \"foreignKey\" || edge.kind === \"junction\") {\n const [first, second] = edge.endpoints;\n return first.source === source && first.field === resolved.slot.field\n ? second.source\n : first.source;\n }\n return edge.carrier.source;\n};\n\n/**\n * WHERE a polymorphic arm lives depends on the slot's CARDINALITY, and getting\n * that wrong is not a missed default — it is a thrown query.\n *\n * A to-one slot's projection IS the discriminator map, so an arm is written at\n * the projection's top level. A collection's projection is an envelope whose\n * top level holds exactly two keys, `only` and `variants`; an arm written\n * beside them is an unknown key the strict envelope refuses. Since this rewrite\n * runs BEFORE validation, a top-level arm would make\n * `include: { items: true }` throw on any client that configures an `omit` for\n * a variant's target model — a client-option-shaped failure in a query that\n * never mentioned the option.\n */\nconst rewriteVariantCarrier = (\n edge: ResolvedVariantEdge,\n value: unknown,\n resolve: ClientOmitResolver\n): unknown =>\n edge.kind === \"variantJunctionCarrier\"\n ? rewritePolymorphicCollection(edge, value, resolve)\n : rewritePolymorphicSlot(edge, value, resolve);\n\n/**\n * The arm a client default produces for one target, or `undefined` when that\n * target is unconfigured (leave the caller's payload — and its cache key —\n * exactly as written).\n */\nconst defaultedArm = (\n target: AnyModel,\n variant: unknown,\n resolve: ClientOmitResolver\n): unknown => {\n if (isPlainRecord(variant)) {\n const rewritten = rewriteNode(target, variant, resolve);\n return rewritten === variant ? undefined : rewritten;\n }\n if (variant !== true && variant !== undefined) return undefined;\n const defaults = resolve.omit(target);\n return defaults ? { omit: { ...defaults } } : undefined;\n};\n\n/**\n * A to-one polymorphic projection object overrides individual variants; absent\n * keys still project that target's default scalars. Visit every configured\n * target so client defaults apply to both explicit and defaulted variants.\n */\nconst rewritePolymorphicSlot = (\n edge: Extract<ResolvedVariantEdge, { kind: \"variantRowCarrier\" }>,\n value: unknown,\n resolve: ClientOmitResolver\n): unknown => {\n if (value !== true && !isPlainRecord(value)) return value;\n\n const projection: Record<string, unknown> =\n value === true ? {} : { ...value };\n let changed = false;\n\n for (const member of edge.members) {\n const variant = value === true ? undefined : value[member.variant];\n const arm = defaultedArm(member.targetModel, variant, resolve);\n if (arm === undefined) continue;\n projection[member.variant] = arm;\n changed = true;\n }\n\n return changed ? projection : value;\n};\n\n/**\n * A collection projection: arms go UNDER `variants`, and an allow-list is\n * obeyed rather than worked around.\n *\n * Synthesizing an arm for a variant `only` excludes would fabricate the exact\n * \"Variant 'x' is not in 'only'\" refusal the envelope raises — a client option\n * producing a parse error about a key the caller never wrote.\n */\nconst rewritePolymorphicCollection = (\n edge: Extract<ResolvedVariantEdge, { kind: \"variantJunctionCarrier\" }>,\n value: unknown,\n resolve: ClientOmitResolver\n): unknown => {\n if (value !== true && !isPlainRecord(value)) return value;\n\n const envelope = value === true ? undefined : value;\n const only = envelope?.only;\n const existing = envelope?.variants;\n // A malformed envelope is left ALONE: validation owns the message, and a\n // rewrite here would only add keys to a payload that is already failing.\n if (only !== undefined && !Array.isArray(only)) return value;\n if (existing !== undefined && !isPlainRecord(existing)) return value;\n const allowed = Array.isArray(only) ? new Set<unknown>(only) : undefined;\n\n const variants: Record<string, unknown> = { ...existing };\n let changed = false;\n\n for (const member of edge.members) {\n if (allowed && !allowed.has(member.variant)) continue;\n const arm = defaultedArm(\n member.topology.target.model,\n existing?.[member.variant],\n resolve\n );\n if (arm === undefined) continue;\n variants[member.variant] = arm;\n changed = true;\n }\n\n if (!changed) return value;\n return { ...envelope, variants };\n};\n","import { ValidationError } from \"@errors\";\nimport { baseOperation } from \"@query-engine/routed-operations\";\nimport type { Operation as ValidationOperation } from \"@query-engine/types\";\nimport { isRecord } from \"@validation/value-guards\";\nimport type { Operations } from \"./types\";\n\n/** The unique-selector verbs; an `…OrThrow` verb is refused as its base. */\nconst UNIQUE_SELECTOR_OPERATIONS: ReadonlySet<string> =\n new Set<ValidationOperation>([\"findUnique\", \"update\", \"delete\", \"upsert\"]);\n\nexport function assertNonEmptyUniqueWhere(\n model: string,\n operation: Operations,\n args: unknown\n): void {\n const validationOperation = baseOperation(operation);\n if (!UNIQUE_SELECTOR_OPERATIONS.has(validationOperation)) return;\n if (!isRecord(args)) return;\n const where = args.where;\n if (!isRecord(where)) return;\n\n const hasDiscriminator = Object.keys(where).some(\n (key) => where[key] !== undefined\n );\n if (hasDiscriminator) return;\n\n throw new ValidationError(\n validationOperation,\n [\n {\n path: \"where\",\n message: \"whereUnique requires at least one unique discriminator.\",\n },\n ],\n { meta: { model } }\n );\n}\n","import { ASYNC_DISPOSE, type AsyncDisposeMember } from \"@drivers/async-dispose\";\nimport { CLIENT_DIAGNOSTICS } from \"@drivers/execution-context\";\nimport type { AnyDriver } from \"@drivers/exports\";\nimport type {\n BatchTransactionOptions,\n TransactionOptions,\n} from \"@drivers/shared/transaction-options\";\nimport { ClientInitializationError, isVibORMError } from \"@errors\";\nimport type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type {\n AnyFacts,\n ConfiguredBy,\n EmptyFacts,\n Extension,\n Facts,\n StampedFields,\n Target,\n} from \"@extensions/contract\";\nimport { transact } from \"@extensions/coordination\";\nimport { isAppliedExtension } from \"@extensions/extension\";\nimport type {\n AddedExtensionState,\n ChainedExtensionState,\n DelegateState,\n EmptyClientExtensionState,\n ExtensionMethods,\n ExtensionModelClient,\n ExtensionStateConstraint,\n MergeModelMethods,\n} from \"@extensions/methods\";\nimport { SCOPE } from \"@extensions/origin\";\nimport { createOperationExecutionContext } from \"@query-engine/execution-context\";\nimport { enableFindUniqueBatching } from \"@query-engine/find-unique-batch\";\nimport type {\n PendingOperation,\n PrepareOperationInput,\n PrepareWriteOutcomeRegistration,\n} from \"@query-engine/pending-operation\";\nimport { QueryEngine } from \"@query-engine/query-engine\";\nimport { createCommandEngine } from \"@query-engine/raptor3/commands\";\nimport { renderers } from \"@query-engine/raptor3/shared/insert-value\";\nimport {\n isWriteOperation,\n ROUTED_OPERATIONS,\n} from \"@query-engine/routed-operations\";\nimport type { TransactionOperation } from \"@query-engine/transaction-operation\";\nimport { hydrateSchemaNames } from \"@schema/hydration\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport {\n describeDecimalProviderLimitRefusal,\n findDecimalProviderLimitRefusal,\n} from \"@schema/scalars/decimal/provider-limits\";\nimport type { ResolvedRelationIndex } from \"@schema/validation/relation-resolution\";\nimport {\n resolveCheckedSchemaOrThrow,\n resolveSchemaOrThrow,\n} from \"@schema/validation/validator\";\nimport { createResolvedSchemaRegistry } from \"@validation/builder\";\nimport { executeArrayTransaction } from \"./array-transaction\";\nimport {\n applyClientOmit,\n type ClientOmitResolver,\n createClientOmitResolver,\n} from \"./omit\";\nimport type {\n DeclaresEvidence,\n DelegateCallArgs,\n DelegateProjectedArgs,\n DelegateProjectedResult,\n GatedConfig,\n ProjectedModelOperations,\n} from \"./projected-types\";\nimport {\n createRawSurface,\n createRowsFragment,\n RAW_METHOD_NAMES,\n type RawOperation,\n type RawSurface,\n} from \"./raw\";\nimport type { ClientSchema, LinkedClientConfig } from \"./schema-links\";\nimport type {\n CachedClient,\n Client,\n ClientRowsContext,\n ComputedOperation,\n ComputedResultContext,\n ContextualOperationResult,\n OperationPayload,\n Operations,\n Schema,\n WithComputedResult,\n} from \"./types\";\n\nexport type {\n ClientSchema,\n FlatSchema,\n Linked,\n LinkedClientConfig,\n Links,\n RelationLinks,\n} from \"./schema-links\";\n\nimport { assertNonEmptyUniqueWhere } from \"./unique-where-guard\";\n\n/** The schema-bind refusal for an adapter with no physical GeoPoint protocol. */\nfunction refuseGeoPointFields(schema: Schema): void {\n for (const [modelName, model] of Object.entries(schema)) {\n const scalars: Record<string, Scalar> = model[\"~\"].state.scalars;\n for (const [fieldName, scalar] of Object.entries(scalars)) {\n if (scalar[\"~\"].state.type !== \"point\") continue;\n throw new ClientInitializationError(\n `GeoPoint field '${modelName}.${fieldName}' cannot be stored by this driver because its adapter has no GeoPoint protocol.`\n );\n }\n }\n}\n\n/**\n * Create a recursive proxy for model operations\n * Operations return the result of createOperation (PendingOperation or Promise)\n */\nfunction createModelProxy<S extends Schema, R>(\n schema: S,\n createOperation: (opts: {\n modelName: keyof S;\n operation: Operations;\n args: unknown;\n }) => R,\n modelMethods?: ExtensionMethods[\"model\"],\n /** A model's core members beside its operations: `$rows(alias)`, and `$sql` where no alias is given. */\n rowsOf?: (model: keyof S, alias?: unknown) => unknown,\n path: string[] = []\n): unknown {\n // A model's own methods, read (and their factories invoked) only once the\n // model itself is.\n const methods = path.length === 1 ? modelMethods?.(path[0]!) : undefined;\n const members = new Set(\n path.length === 0\n ? Object.keys(schema)\n : path.length === 1\n ? [\n ...ROUTED_OPERATIONS,\n ...(rowsOf ? [\"$rows\", \"$sql\"] : []),\n ...Object.keys(methods ?? {}),\n ]\n : []\n );\n const children = new Map<string, unknown>();\n const readMember = (key: string | symbol): unknown => {\n if (typeof key !== \"string\" || key === \"then\" || !members.has(key))\n return undefined;\n if (methods !== undefined && Object.hasOwn(methods, key)) {\n return methods[key];\n }\n if (key === \"$sql\" && rowsOf) return rowsOf(path[0]!);\n let child = children.get(key);\n if (child === undefined) {\n child =\n key === \"$rows\" && rowsOf\n ? (alias: unknown) => rowsOf(path[0]!, alias)\n : createModelProxy(schema, createOperation, modelMethods, rowsOf, [\n ...path,\n key,\n ]);\n children.set(key, child);\n }\n return child;\n };\n return new Proxy(path.length === 2 ? () => undefined : {}, {\n get: (target, key) =>\n Object.hasOwn(target, key) ? Reflect.get(target, key) : readMember(key),\n has: (target, key) =>\n Object.hasOwn(target, key) ||\n (typeof key === \"string\" && members.has(key)),\n ownKeys: (target) => [...new Set([...Reflect.ownKeys(target), ...members])],\n getOwnPropertyDescriptor: (target, key) =>\n Reflect.getOwnPropertyDescriptor(target, key) ??\n (typeof key === \"string\" && members.has(key)\n ? {\n configurable: true,\n enumerable: true,\n writable: true,\n value: readMember(key),\n }\n : undefined),\n apply(_target, _thisArg, [args]) {\n const modelName = path[0] as keyof S;\n const operation = path[1] as Operations;\n return createOperation({ modelName, operation, args });\n },\n });\n}\n\ntype BatchTransactionOperation<T = unknown> =\n | PendingOperation<T>\n | RawOperation<T>;\n\n/** What any view's `$transaction` accepts: a callback or an operation array. */\ntype TransactionInput<C extends VibORMConfig> =\n | ((\n tx: TransactionClient<C, ExtensionStateConstraint>\n ) => PromiseLike<unknown>)\n | TransactionOperation<unknown>[];\n\n/** The four raw methods the client and its transaction clients answer. */\nfunction isRawMethodName(prop: string | symbol): prop is keyof RawSurface {\n return typeof prop === \"string\" && Object.hasOwn(RAW_METHOD_NAMES, prop);\n}\n\n/**\n * VibORM Configuration\n */\nexport interface VibORMConfig<S extends Schema = Schema> {\n schema: S;\n driver: AnyDriver;\n /**\n * Skip the schema checks every client otherwise runs when it is created, for\n * a schema `viborm check` validates (in a build or CI step). The client still\n * resolves relations, which it needs to run queries; it trusts identifiers,\n * table and selector names, and the absence of required-relation cycles.\n */\n skipSchemaValidation?: boolean;\n /**\n * Answer the `findUnique` calls issued in the same tick with one read over\n * their keys (Prisma's dataloader), instead of one read each. Off by\n * default: the shared read runs in the first call's async context, so a\n * driver that picks its database by `AsyncLocalStorage`, or a trace per\n * request, sees that call's context for every call of the batch.\n */\n findUniqueBatching?: boolean;\n}\n\nexport interface DriverConfig<S extends Schema = Schema>\n extends Omit<VibORMConfig<S>, \"driver\"> {}\n\n/**\n * A contribution whose model slot also carries the projected overloads of a\n * declared key (K5), typed against the client as this step leaves it.\n */\nexport interface AddedProjectedState<\n Added extends ExtensionStateConstraint,\n Projected extends object,\n> extends ExtensionStateConstraint {\n readonly client: Added[\"client\"];\n readonly models: MergeModelMethods<Added[\"models\"], Projected>;\n readonly resultConsumer: Added[\"resultConsumer\"];\n readonly args: Added[\"args\"];\n readonly filtered: Added[\"filtered\"];\n readonly defaults: Added[\"defaults\"];\n readonly fields: Added[\"fields\"];\n}\n\n/**\n * What a rule's `gate` and `facts` add, in the form the projected types read\n * a definition: nothing when it adds neither.\n */\ntype ProjectedDefinition<F extends AnyFacts> = [keyof F[\"projected\"]] extends [\n never,\n]\n ? unknown\n : { readonly projected: F[\"projected\"] };\n\n/** An extension's facts as the chain's state accumulates them. */\ntype AddedStateOf<F extends AnyFacts> = AddedExtensionState<\n F[\"client\"],\n F[\"models\"],\n F[\"args\"],\n F[\"filtered\"],\n F[\"defaults\"],\n F[\"consumer\"] extends true ? \"result-consuming\" : \"result-independent\",\n F[\"fields\"]\n>;\n\n/** The config a client has once an extension with facts `F` is applied. */\nexport type AppliedClientConfig<\n C extends VibORMConfig,\n F extends AnyFacts,\n> = GatedConfig<ConfiguredBy<C, F>, ProjectedDefinition<F>>;\n\ntype ProjectedStateOf<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n F extends AnyFacts,\n Added extends ExtensionStateConstraint = AddedStateOf<F>,\n> = DeclaresEvidence<C, ProjectedDefinition<F>> extends false\n ? Added\n : AddedProjectedState<\n Added,\n ProjectedModelOperations<\n AppliedClientConfig<C, F>,\n ClientRowsContext<\n AppliedClientConfig<C, F>,\n X[\"filtered\"] | Added[\"filtered\"]\n >,\n X[\"args\"] & Added[\"args\"],\n ProjectedDefinition<F>\n >\n >;\n\n/** The extension state a client has once an extension with facts `F` is applied. */\nexport type AppliedExtensionState<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n F extends AnyFacts,\n> = NoFacts<F> extends true\n ? // Nothing contributed (hooks, units, a plain call): the client's own\n // state, so the client keeps its very type.\n X\n : ChainedExtensionState<X, ProjectedStateOf<C, X, F>>;\n\n/**\n * The order rule: after a part typed against a result, a rule that hides\n * rows or a default that omits a field would make that type lie. And a\n * client method keeps the name it was added under, which `$extends` refuses\n * at runtime too: a part typed against this client is refused at the key\n * (`methods`), and this reads an extension whose facts were not (an\n * official one, one written apart: a second cache's `$withCache`). A\n * constraint on the facts, not a conditional beside the extension: a\n * parameter type that depends on the facts being inferred gives the parts\n * no client to be typed against. `object &` keeps the method names a type\n * with members, not a weak type every unrelated object would be refused by.\n */\ntype AdmittedFacts<X extends ExtensionStateConstraint> = Facts<\n object & { readonly [Name in keyof X[\"client\"]]?: never },\n object,\n object,\n [X[\"resultConsumer\"]] extends [undefined] ? string : never,\n unknown,\n object,\n [X[\"resultConsumer\"]] extends [undefined]\n ? object\n : { readonly [model: string]: never },\n boolean,\n object\n>;\n\ntype DataModels<D> = D extends StampedFields<infer M, PropertyKey> ? M : never;\n\n/** Literal model names only: `string` is every model, or names the types cannot read. */\ntype Literal<K> = K extends string ? (string extends K ? never : K) : never;\n\n/**\n * Every model an extension's facts name. Rows hidden, methods, omissions,\n * projections and computed fields on `string` concern every model (a policy\n * governs them all) or names only the runtime can check: none is named. A\n * field written on create is the exception: written on `string`, it would be\n * optional on every model, so `string` is named, and refused.\n */\ntype NamedModels<F extends AnyFacts> =\n | Literal<\n | F[\"filtered\"]\n | keyof F[\"omit\"]\n | keyof F[\"models\"]\n | keyof F[\"projected\"]\n | Exclude<keyof F[\"fields\"], \"$allModels\">\n >\n | DataModels<F[\"defaults\"]>;\n\n/**\n * The models the extension names that this client does not have. A part\n * typed against the client refuses one where it is written; one written\n * apart from any client (a recipe taking model names, `tenancy([\"post\"])`)\n * is checked here, where it meets the client. A list of names the types\n * cannot read (a `string[]`) names `string`, which no schema has.\n */\ntype KnownModels<Models, F extends AnyFacts> = [\n Exclude<NamedModels<F>, Models>,\n] extends [never]\n ? unknown\n : {\n readonly \"names models this client does not have\": Exclude<\n NamedModels<F>,\n Models\n >;\n };\n\n/**\n * The keys a proposed config names that the surface does not have: the typos.\n *\n * `createClient` infers `Config` FROM the literal, so the literal's own keys are\n * by construction \"known\" to the parameter type and excess-property checking has\n * nothing to complain about — `decimel: \"number\"` recorded a setting nobody reads\n * and compiled. (Excess-property checking would not have been enough anyway: it\n * needs a fresh object literal, so a config held in a variable — the shape every\n * \"share one config across two clients\" snippet uses — sails through it.)\n *\n * Demanding `never` for the unknown keys refuses structurally instead, whatever\n * the argument's freshness, and a `never` the caller cannot produce is a compile\n * error at the offending key. Same instrument as the model builder's\n * `UnknownOmitKeys`.\n */\nexport type NoExtraConfigKeys<Given, Allowed> = Record<\n Exclude<keyof Given, keyof Allowed>,\n never\n>;\n\n/**\n * The driver-package flavour: a wrapper's literal may also carry that driver's\n * own options (`dataDir`, `pool`, `authToken`, …), so the accepted set is the\n * union of those and the shared client config.\n */\nexport type NoExtraDriverConfigKeys<Given, Options, S extends Schema> = Record<\n Exclude<keyof Given, keyof Options | keyof DriverConfig<S>>,\n never\n>;\n\n/**\n * The client an interactive `$transaction(async (tx) => ...)` callback gets:\n * every model operation, the raw SQL surface bound to the OPEN transaction,\n * and nested `$transaction` (savepoints).\n */\nexport type TransactionClient<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint = EmptyClientExtensionState,\n> = ExtensionModelClient<C, X> &\n RawSurface & {\n readonly $schema: ClientSchema<C>;\n $transaction: TransactionMethod<C, X>;\n } & X[\"client\"];\n\n/**\n * The read-only view of `Client` a cache serves (`$withCache()`): its read\n * operations answering promises, typed as `Client`'s own delegates type them,\n * and its client methods. `Client` is a client `createClient`, `$extends` or\n * a view such as `$as(actor)` returned; `never` for a transaction client or\n * a cached view, which carry no client state.\n */\nexport type CachedClientOf<Client> = typeof clientTypeState extends keyof Client\n ? Client extends ClientTypeState<\n infer C,\n infer X extends ExtensionStateConstraint\n >\n ? CachedClient<\n C,\n ClientRowsContext<C, X[\"filtered\"]>,\n X[\"args\"],\n X[\"models\"]\n > &\n X[\"client\"]\n : never\n : never;\n\n/**\n * The interactive transaction client of `Client`, a client `createClient`,\n * `$extends` or a view such as `$as(actor)` returned: what code that takes\n * \"a client or a transaction\" names for its transaction half.\n *\n * @example\n * ```ts\n * type Tx = TransactionClientOf<typeof db>;\n * const rename = (tx: typeof db | Tx, id: string) =>\n * tx.page.update({ where: { id }, data: { title: \"x\" } });\n * ```\n */\nexport type TransactionClientOf<Client> =\n typeof clientTypeState extends keyof Client\n ? Client extends ClientTypeState<\n infer C,\n infer X extends ExtensionStateConstraint\n >\n ? TransactionClient<C, X>\n : never\n : never;\n\n/** `$transaction`'s two forms: an interactive callback, or a batch array. */\ntype TransactionMethod<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = {\n // Overload 1: Dynamic transaction (callback)\n <T>(\n fn: (tx: TransactionClient<C, X>) => PromiseLike<T>,\n options?: TransactionOptions\n ): Promise<T>;\n // Overload 2: Batch of independent operations (Prisma-style)\n <T extends BatchTransactionOperation<unknown>[]>(\n operations: [...T],\n options?: BatchTransactionOptions\n ): Promise<{ [K in keyof T]: Awaited<T[K]> }>;\n};\n\ndeclare const clientTypeState: unique symbol;\n\n/**\n * Declaration-only inference metadata; no property is installed at runtime.\n * The optional opaque arm preserves structural client assignability. The\n * conditional exposes the tuple for inference without making C or X invariant.\n * Result helpers check key presence and the full client surface: this metadata\n * guides inference, but does not prove that a client has the declared methods.\n */\nexport type ClientTypeState<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = [C] extends [unknown] ? ClientTypeStateMember<C, X> : never;\n\n/**\n * The metadata's one member. An interface, so an inferred client's\n * declaration names it rather than spelling its symbol-keyed member, which a\n * declaration file cannot name.\n */\nexport interface ClientTypeStateMember<C, X> {\n readonly [clientTypeState]?: readonly [C, X] | object;\n}\n\n/**\n * Extended client type with utility methods\n */\nexport type VibORMClient<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint = EmptyClientExtensionState,\n> = ClientTypeState<C, X> &\n ExtensionModelClient<C, X> &\n RawSurface &\n X[\"client\"] &\n // `await using client = createClient({ ... })` disposes through the same\n // close path as `$disconnect()`. Carried by `AsyncDisposeMember` so it is the\n // empty object — not a compile error — for a consumer whose `lib`/`@types`\n // never declared `Symbol.asyncDispose`. The interactive `tx` client is\n // deliberately NOT disposable: `$transaction` owns that driver's lifetime.\n AsyncDisposeMember &\n VibORMClientMembers<C, X>;\n\n/** The client members no extension state removes. */\nexport interface VibORMClientMembers<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> {\n /** Access the underlying driver */\n $driver: AnyDriver;\n /** Access the schema (models) */\n $schema: ClientSchema<C>;\n /**\n * Run operations in a transaction or batch\n *\n * @example Dynamic transaction (callback) - operations can depend on each other\n * ```ts\n * await client.$transaction(async (tx) => {\n * const user = await tx.user.create({ data: { name: \"Alice\" } });\n * await tx.post.create({ data: { title: \"Hello\", authorId: user.id } });\n * });\n * ```\n *\n * @example Batch (array) - independent operations, atomic execution\n * ```ts\n * const [users, posts] = await client.$transaction([\n * client.user.findMany(),\n * client.post.findMany(),\n * ]);\n * ```\n *\n * @example Options - honored or refused, never ignored\n * ```ts\n * await client.$transaction(async (tx) => { ... }, {\n * isolationLevel: \"Serializable\",\n * timeout: 10_000,\n * maxWait: 2000,\n * });\n * ```\n *\n * Each option is honored where the driver can honor it and rejected with\n * a typed `UnsupportedOperationError` (V8003) where it cannot — see\n * [Transactions](/docs/client/transactions) for the per-driver contract.\n * The array form takes `isolationLevel` only: a preplanned array has no\n * interactive window for `timeout` or `maxWait` to bound.\n */\n $transaction: TransactionMethod<C, X>;\n /** Connect to the database */\n $connect: () => Promise<void>;\n /** Disconnect from the database */\n $disconnect: () => Promise<void>;\n /**\n * Apply an extension: `client.$extends(extension(name, ...parts))`, or an\n * official one (`client.$extends(softDelete({ … }))`). Each handler of the\n * extension is typed against this client. The extension is appended to an\n * immutable chain; this client is unchanged.\n */\n $extends<F extends AdmittedFacts<X>>(\n // The check reads the model names only: two clients of one schema and\n // different drivers stay assignable.\n extension: Extension<Target<LinkedConfigOf<C>, X, EmptyFacts>, F> &\n KnownModels<keyof C[\"schema\"], F>\n ): VibORMClient<AppliedClientConfig<C, F>, AppliedExtensionState<C, X, F>>;\n}\n\n/**\n * The config a client's parts are typed against: the linked snapshot\n * `createClient` makes. A client type written with its plain config\n * (`VibORMClient<{ schema: S; driver: D }>`) reads the same target as the\n * client `createClient` returned, so the two stay assignable.\n */\nexport type LinkedConfigOf<C extends VibORMConfig> = AnyDriverOf<\n \" vibLinks\" extends keyof C ? C : LinkedClientConfig<C>\n>;\n\n/**\n * The driver is no part's concern: two clients of one schema on two drivers\n * read one target, so a client type names either.\n */\ntype AnyDriverOf<C> = {\n [K in keyof C]: K extends \"driver\" ? AnyDriver : C[K];\n};\n\n/**\n * Whether `F` contributes nothing. Both ways: an empty fact (`never` rows,\n * `{}` methods) is assignable to any fact of its kind, and any methods\n * object to `{}`.\n */\ntype NoFacts<F extends AnyFacts> = [F] extends [EmptyFacts]\n ? [EmptyFacts] extends [F]\n ? true\n : false\n : false;\n\ntype FactsOf<E> = E extends Extension<never, infer F> ? F : never;\n\ntype ApplyClientExtensions<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n Extensions extends readonly unknown[],\n> = Extensions extends readonly []\n ? VibORMClient<C, X>\n : Extensions extends readonly [infer First, ...infer Rest]\n ? FactsOf<First> extends infer F extends AdmittedFacts<X>\n ? unknown extends KnownModels<keyof C[\"schema\"], F>\n ? ApplyClientExtensions<\n AppliedClientConfig<C, F>,\n AppliedExtensionState<C, X, F>,\n Rest\n >\n : never\n : never\n : never;\n\n/**\n * The exact client surface produced by applying an ordered tuple of\n * extension values.\n *\n * @example\n * ```ts\n * type AppClient = ExtendedClient<\n * typeof db,\n * readonly [typeof tenancy, typeof cached, typeof tools]\n * >;\n * ```\n */\nexport type ExtendedClient<\n Base,\n Extensions extends readonly unknown[],\n> = number extends Extensions[\"length\"]\n ? never\n : typeof clientTypeState extends keyof Base\n ? Base extends ClientTypeState<infer C, infer X>\n ? Base extends VibORMClient<C, X>\n ? ApplyClientExtensions<C, X, Extensions>\n : never\n : never\n : never;\n\n/**\n * One operation's result on a derived client, as that client's own delegate\n * types it: its `defaultOmit` applied to `Args`, and a to-one relation whose\n * target a rule of the chain can hide typed `| null`. Index the client with\n * `M[K & keyof M]` in a plugin generic over it.\n */\nexport type ExtendedOperationResult<\n Client,\n ModelName,\n O extends Operations,\n Args,\n> = typeof clientTypeState extends keyof Client\n ? Client extends ClientTypeState<infer C, infer X>\n ? Client extends VibORMClient<C, X>\n ? ContextualOperationResult<\n C,\n ModelName & keyof ClientSchema<C>,\n O,\n Args,\n ClientRowsContext<C, X[\"filtered\"]>\n >\n : never\n : never\n : never;\n\n/**\n * The config of the client the model delegate `Delegate` belongs to: what a\n * model method written apart from any client reads its model from, so its\n * arguments are that client's, not its extension's own target's. `Fallback`\n * where the delegate carries no chain.\n */\nexport type DelegateConfig<\n Delegate,\n Fallback extends VibORMConfig = never,\n> = Delegate extends DelegateState<\n infer C extends VibORMConfig,\n unknown,\n unknown,\n unknown\n>\n ? C\n : Fallback;\n\n/**\n * One operation's own arguments on the model delegate `Delegate`, read from\n * the client that delegate belongs to: what a model method written apart\n * from any client (an official extension's, its target unknown) takes.\n * `Fallback` where the delegate carries no chain.\n */\nexport type DelegateOperationPayload<\n Delegate,\n O extends Operations,\n Fallback = never,\n> = Delegate extends DelegateState<\n infer C extends VibORMConfig,\n unknown,\n unknown,\n infer K\n>\n ? OperationPayload<O, ClientSchema<C>[K & keyof ClientSchema<C>]>\n : Fallback;\n\n/**\n * One operation's arguments on the model delegate `Delegate` it would run on:\n * `Payload`, whose `select` and `include` admit the keys that delegate's chain\n * projects (`$access`), as the operation's own projected overloads admit\n * them. A model method constrains its arguments with it beside\n * `DelegateOperationResult`: `restore<Self, A extends\n * DelegateOperationArgs<Self, RestoreArgs>>(this: Self, args: A)`.\n */\nexport type DelegateOperationArgs<Delegate, Payload> =\n Delegate extends DelegateState<unknown, unknown, unknown, infer K>\n ? DelegateProjectedArgs<Delegate, Payload, K>\n : Payload;\n\n/**\n * One operation's result on the model delegate `Delegate` it would run on,\n * as `ExtendedOperationResult` types it for that delegate's client. A model\n * method declared with a `this` parameter types its result with it, so the\n * result follows every extension applied after the method's own:\n * `restore<Self, A>(this: Self, args: A): PendingOperation<\n * DelegateOperationResult<Self, \"update\", A>>`.\n */\nexport type DelegateOperationResult<\n Delegate,\n O extends Operations,\n Args,\n> = Delegate extends DelegateState<\n infer C extends VibORMConfig,\n infer Rows extends string,\n infer Result extends object,\n infer K\n>\n ? // A key the chain projects (`$access`) reads as the operation's own\n // projected overload reads it.\n DelegateProjectedResult<\n Delegate,\n O,\n K,\n Args,\n DelegateComputedRow<\n C,\n Rows,\n Result,\n K,\n O,\n DelegateCallArgs<Delegate, Args>\n >\n >\n : // Called off a delegate (a destructured method): nothing to read the\n // result from, and `unknown` makes using it a type error.\n unknown;\ntype DelegateComputedRow<\n C extends VibORMConfig,\n Rows extends string,\n Result extends object,\n K,\n O extends Operations,\n Args,\n> = [keyof Result] extends [never]\n ? DelegateRow<C, Rows, K & keyof ClientSchema<C>, O, Args>\n : // Computed fields reach the rows an operation returns, nothing else.\n O extends Exclude<Operations, ComputedOperation>\n ? DelegateRow<C, Rows, K & keyof ClientSchema<C>, O, Args>\n : WithComputedResult<\n DelegateRow<C, Rows, K & keyof ClientSchema<C>, O, Args>,\n ClientSchema<C>[K & keyof ClientSchema<C>],\n Args,\n ComputedResultContext<Result, ClientSchema<C>, K>\n >;\ntype DelegateRow<\n C extends VibORMConfig,\n Rows extends string,\n K extends keyof ClientSchema<C>,\n O extends Operations,\n Args,\n> = ContextualOperationResult<C, K, O, Args, ClientRowsContext<C, Rows>>;\n\n/**\n * VibORM Client\n */\nexport class VibORM<C extends VibORMConfig> {\n readonly #schema: ClientSchema<C>;\n readonly #engine: QueryEngine;\n readonly #relations: ResolvedRelationIndex;\n /** The schema's validation schemas, which also admit rule predicates. */\n readonly #registry: PreparedSchema[\"schemaRegistry\"];\n /** One resolved omission per chain's `omit` state on this client. */\n #extensionOmitResolvers:\n | WeakMap<object, Readonly<{ resolver: ClientOmitResolver | undefined }>>\n | undefined;\n\n /**\n * @param prepared - the ONE resolved topology index the static factory's\n * gate produced, and the registries over it, passed in by identity. The\n * registry, an official default-omit resolver, and every query scope share\n * this exact object; nothing here resolves a second time and nothing\n * copies it (§10E.10, §11.4.10).\n */\n constructor(config: C, { relations, schemaRegistry }: PreparedSchema) {\n this.#schema = config.schema as ClientSchema<C>;\n this.#relations = relations;\n this.#registry = schemaRegistry;\n\n // The Raptor 3 route is the ONE operation owner (C-01). The two resolved\n // views above travel to it by identity, so the route's engine hydrates,\n // validates and registers nothing a second time (B-3).\n this.#engine = new QueryEngine(\n config.driver,\n createCommandEngine({\n schema: this.#schema,\n driver: config.driver,\n resolved: { index: relations, registry: schemaRegistry },\n })\n );\n if (config.findUniqueBatching === true)\n enableFindUniqueBatching(this.#engine.route);\n }\n\n /**\n * Create the client with model proxies and utility methods\n * Model operations return PendingOperation for deferred execution\n */\n #createClient(\n engine: QueryEngine,\n modelMethods: ExtensionMethods[\"model\"] | undefined,\n clientOmit: ClientOmitResolver | undefined\n ): Client<C> {\n return createModelProxy(\n this.#schema,\n ({ modelName, operation, args }) =>\n this.#prepareModelOperation(\n engine,\n modelName,\n operation,\n args,\n clientOmit\n ),\n modelMethods,\n (modelName, ...alias) =>\n alias.length === 0\n ? renderers\n .get(this.#schema)!\n .get(engine.driver.adapter)!\n .spelling(this.#schema[modelName]!, engine.driver.dialect)\n : createRowsFragment(engine, this.#schema[modelName]!, alias[0])\n ) as Client<C>;\n }\n\n /** Build one model operation through the common lazy client preparation path. */\n #prepareModelOperation(\n engine: QueryEngine,\n modelName: keyof ClientSchema<C>,\n operation: Operations,\n args: unknown,\n clientOmit: ClientOmitResolver | undefined\n ): PendingOperation<unknown> {\n const modelNameStr = String(modelName);\n const model = this.#schema[modelName];\n if (!model) {\n throw new ClientInitializationError(\n `Model \"${modelNameStr}\" not found in schema`,\n { meta: { model: modelNameStr, operation: String(operation) } }\n );\n }\n\n const rawArgs = (args ?? {}) as Record<string, unknown>;\n const isWrite = isWriteOperation(operation);\n const chain = engine.extensionChain;\n\n const request = chain?.call;\n const requestHandlers = request?.handlers(modelNameStr, operation);\n const hasOperationObservers = chain?.observation !== undefined;\n const hasPlacedArguments =\n (chain?.args?.placed(modelNameStr, operation).length ?? 0) > 0;\n let operationArgs: Record<string, unknown> = rawArgs;\n let prepareInput: PrepareOperationInput | undefined;\n const resultFields = chain?.fields;\n let finishResult: ((value: unknown) => unknown) | undefined;\n const written = isWrite ? chain?.watch : undefined;\n /** The call's arguments as what watches its writes is told them. */\n let callArgs: Record<string, unknown> | undefined;\n /** What watches the call's writes is told late that they settled: the call's value runs it and waits. */\n let settle: (() => Promise<void>) | undefined;\n // Apply the client omit, then refuse an empty unique where, then plan\n // the chain's computed fields.\n const finish = (requestArgs: Record<string, unknown>) => {\n const omittedArgs = clientOmit\n ? applyClientOmit(model, operation, requestArgs, clientOmit)\n : requestArgs;\n assertNonEmptyUniqueWhere(modelNameStr, operation, omittedArgs);\n callArgs = omittedArgs;\n if (resultFields === undefined) return omittedArgs;\n const fields = resultFields.plan(\n this.#relations,\n model,\n operation,\n omittedArgs\n );\n finishResult = fields?.finish;\n return fields?.args ?? omittedArgs;\n };\n\n if (\n requestHandlers === undefined &&\n !hasPlacedArguments &&\n !hasOperationObservers\n ) {\n operationArgs = finish(rawArgs);\n } else {\n // Request code stays behind PendingOperation's first preparation\n // boundary. That boundary memoizes both this callback's value and its\n // failure when several lifecycle entry points observe the same\n // operation, and hands it the arguments with their arguments removed.\n prepareInput = (strippedArgs, values, call) => {\n const transformed =\n request === undefined || requestHandlers === undefined\n ? strippedArgs\n : request.apply(\n operation,\n strippedArgs,\n requestHandlers,\n call,\n modelNameStr,\n chain?.args,\n values\n );\n return finish(transformed);\n };\n }\n\n const prepareWriteOutcomeRegistration:\n | PrepareWriteOutcomeRegistration\n | undefined =\n written === undefined\n ? undefined\n : (context, values, call) =>\n written.watch(\n { model: modelNameStr, operation, args: callArgs!, call },\n values,\n context,\n (late) => {\n settle = late;\n }\n );\n\n // Engine handles OrThrow suffix internally. Routing to the V2 operation is\n // decided lazily — before any I/O — for the whole payload.\n return engine.prepare(\n model,\n operation,\n operationArgs,\n resultFields === undefined && written === undefined\n ? undefined\n : {\n finishResult(value) {\n const finished =\n finishResult === undefined ? value : finishResult(value);\n const late = settle;\n settle = undefined;\n return late ? late().then(() => finished) : finished;\n },\n },\n prepareInput,\n prepareWriteOutcomeRegistration\n );\n }\n\n /** Resolve a chain's omission once for this client's schema. */\n #resolveClientOmit(\n chain: ResolvedExtensionChain\n ): ClientOmitResolver | undefined {\n const capability = chain.omit;\n if (capability === undefined) return undefined;\n const resolvers =\n this.#extensionOmitResolvers ??\n (this.#extensionOmitResolvers = new WeakMap());\n const existing = resolvers.get(capability);\n if (existing !== undefined) return existing.resolver;\n const resolver = createClientOmitResolver(\n this.#schema,\n capability.config,\n this.#relations\n );\n resolvers.set(capability, Object.freeze({ resolver }));\n return resolver;\n }\n\n /**\n * The one get-trap ladder of every concrete view: the root client, an\n * interactive transaction's `tx`, and the scope each extension factory sees.\n * Every utility member is `$`-named or a symbol and a model name never is, so\n * model access is answered first. `extra` adds the root-only utilities, or\n * a scope's `$bind`. No client method takes a core name, so client methods\n * (and their factories) are read only for a member core does not answer.\n */\n #createViewProxy<V>(\n engine: QueryEngine,\n clientOmit: ClientOmitResolver | undefined,\n transaction: CallableFunction,\n methods: ExtensionMethods | undefined,\n extra?: (prop: string | symbol) => unknown\n ): V {\n // Raw SQL rides this view's engine: inside an interactive transaction it\n // shares the transaction's connection and rolls back with it. The surface\n // is built on first `$queryRaw`-family access.\n let rawSurface: RawSurface | undefined;\n return new Proxy(this.#createClient(engine, methods?.model, clientOmit), {\n get: (target, prop) => {\n if (typeof prop === \"string\" && !prop.startsWith(\"$\")) {\n return Reflect.get(target, prop);\n }\n if (prop === \"$schema\") return this.#schema;\n if (prop === \"$transaction\") return transaction;\n if (isRawMethodName(prop)) {\n rawSurface ??= createRawSurface({ engine });\n return rawSurface[prop];\n }\n const member = extra?.(prop);\n if (member !== undefined || typeof prop !== \"string\") return member;\n const client = methods?.client();\n if (client !== undefined && Object.hasOwn(client, prop)) {\n return client[prop];\n }\n // A `$`-named model is still reachable; anything else is absent.\n return Object.hasOwn(this.#schema, prop)\n ? Reflect.get(target, prop)\n : undefined;\n },\n }) as V;\n }\n\n /**\n * Build one concrete view over one engine scope and its extension chain.\n * Each factory scope's `$bind` returns `rebuild` of this engine with the\n * values bound: a view of this view's kind. `eager` invokes every factory\n * now; otherwise each runs when a method it returns is first read.\n */\n #createView<V>(\n engine: QueryEngine,\n clientOmit: ClientOmitResolver | undefined,\n rebuild: ((engine: QueryEngine) => unknown) | undefined,\n eager: boolean,\n extra?: (prop: string | symbol) => unknown\n ): V {\n const transaction = (\n input: TransactionInput<C>,\n options?: TransactionOptions | BatchTransactionOptions\n ) => this.#transact(engine, clientOmit, input, options);\n const chain = engine.extensionChain;\n const declared = chain?.methods;\n const methods =\n declared === undefined\n ? undefined\n : declared.bind((prior, extension) =>\n this.#createViewProxy<object>(\n engine,\n clientOmit,\n transaction,\n prior,\n (prop) =>\n prop === \"$bind\"\n ? (values: Readonly<Record<string, unknown>>) =>\n rebuild!(\n engine.withBound(\n (chain?.args?.bind ?? declared.bindNone)(\n extension,\n values,\n engine.bound\n )\n )\n )\n : // What the words on a method's scope read of its view\n // (`database`, `settled`).\n prop === SCOPE\n ? { engine, extension }\n : undefined\n )\n );\n if (eager) methods?.force();\n return this.#createViewProxy<V>(\n engine,\n clientOmit,\n transaction,\n methods,\n extra\n );\n }\n\n /**\n * The one `$transaction` of every view. Inside an interactive transaction\n * the engine is transaction-bound, so a nested call is a SAVEPOINT.\n */\n #transact(\n engine: QueryEngine,\n clientOmit: ClientOmitResolver | undefined,\n input: TransactionInput<C>,\n options: TransactionOptions | BatchTransactionOptions | undefined\n ): Promise<unknown> {\n try {\n const isArray = Array.isArray(input);\n // Refuse before dispatching, so that a path which never reaches a driver\n // entry point (an empty array) still rejects an option it could not\n // honor. A savepoint's option contract differs from the outermost one,\n // and the transaction-bound driver declares that difference.\n engine.driver.assertTransactionOptionsSupported(\n options,\n isArray ? \"batch\" : \"callback\"\n );\n const chain = engine.extensionChain;\n const context = createOperationExecutionContext(\n \"$transaction\",\n isArray ? \"$transaction([...])\" : \"$transaction(callback)\",\n chain\n );\n if (isArray) {\n return executeArrayTransaction(input, engine, options, context);\n }\n const view = (\n bound: QueryEngine\n ): TransactionClient<C, ExtensionStateConstraint> =>\n this.#createView(bound, clientOmit, view, false);\n // Each scope collects what its calls register: the outermost publishes\n // it after its commit, a savepoint hands it to its parent's.\n return transact(\n engine,\n options as TransactionOptions | undefined,\n context,\n async (txDriver: AnyDriver, scope) =>\n input(view(engine.bind(txDriver, chain, scope)))\n );\n } catch (error) {\n return Promise.reject(error);\n }\n }\n\n /** Create one root view: the shared ladder plus the root-only utilities. */\n #createRootView<\n X extends ExtensionStateConstraint,\n ViewConfig extends VibORMConfig = C,\n >(engine: QueryEngine, eager = true): VibORMClient<ViewConfig, X> {\n const chain = engine.extensionChain;\n const clientOmit =\n chain === undefined ? undefined : this.#resolveClientOmit(chain);\n // One close path behind two doors: `$disconnect()` and, where the platform\n // has the protocol, `await using`. They are the same function object.\n const disconnect = () =>\n engine.driver._disconnect(\n createOperationExecutionContext(\"$connection\", \"$disconnect\", chain)\n );\n\n // A root view `$extends` returns invokes every factory, where an\n // extension's faults belong; a view `$bind` derives, only those it uses.\n // Only a chain's factory scopes can `$bind`.\n const rebind =\n chain && ((bound: QueryEngine) => this.#createRootView(bound, false));\n const view = this.#createView<VibORMClient<ViewConfig, X>>(\n engine,\n clientOmit,\n rebind,\n eager,\n (prop) => {\n if (prop === \"$driver\") return engine.driver;\n if (prop === CLIENT_DIAGNOSTICS) return chain?.disclosure;\n if (prop === \"$extends\") {\n return (extension: unknown) => {\n if (!isAppliedExtension(extension))\n throw new ClientInitializationError(\n \"client.$extends takes an extension: client.$extends(extension(name, ...parts)).\"\n );\n const extensionChain = extension.append(\n chain,\n this.#schema,\n this.#registry\n );\n return this.#createRootView(\n engine.bind(engine.driver, extensionChain)\n );\n };\n }\n if (prop === \"$connect\") {\n return () =>\n engine.driver._connect(\n createOperationExecutionContext(\"$connection\", \"$connect\", chain)\n );\n }\n // `await using client = createClient({ ... })`. On an engine without the\n // protocol `ASYNC_DISPOSE` is undefined, which no property key equals, so\n // the property is absent — what missing disposal support looks like.\n return prop === \"$disconnect\" || prop === ASYNC_DISPOSE\n ? disconnect\n : undefined;\n }\n );\n return view;\n }\n\n /**\n * Create the full client with all utility methods\n */\n static create<\n C extends VibORMConfig,\n ViewConfig extends VibORMConfig = LinkedClientConfig<C>,\n >(config: C): VibORMClient<ViewConfig> {\n if (!config.driver) {\n throw new ClientInitializationError(\n \"Driver is required to create a client. Pass a driver in createClient options.\"\n );\n }\n\n // PostgreSQL always qualifies, so an adapter with no namespace would send\n // this client's SQL wherever the connection's search_path points while\n // migrations altered another schema. Only `PostgresAdapter` owns the\n // `public` default; a custom adapter is refused rather than defaulted.\n if (\n config.driver.dialect === \"postgresql\" &&\n config.driver.adapter.namespace === undefined\n ) {\n throw new ClientInitializationError(\n \"A PostgreSQL driver must supply an adapter with a namespace. Construct PostgresAdapter, or set `namespace` on a custom adapter.\"\n );\n }\n\n // Hydrate schema names (tsName, sqlName) for all models, scalars, and relations.\n // Construction faults (a malformed schema, an invalid identifier) surface as a typed\n // ClientInitializationError instead of a bare Error; already-typed failures pass through\n // unchanged so their own code survives.\n const orm = assertConstructed(() => {\n const checked = config.skipSchemaValidation === true;\n const reused = reusablePreparation(config.schema, checked);\n if (!reused) hydrateSchemaNames(config.schema, checked);\n // The selected adapter's physical capability, asked once here and before\n // any provider I/O (plan §3.1). A decimal domain no dialect could store is\n // a definition error, and the caller learns it at the line that bound the\n // schema rather than at the first UPDATE that could not compute inside it.\n // On SQLite the refusal is load-bearing: past 18 digits its range CHECK\n // stops being exact (see the SQLite adapter's arithmetic guards).\n const decimalRefusal = reused?.fittingDialects.has(config.driver.dialect)\n ? undefined\n : findDecimalProviderLimitRefusal(config.schema, config.driver.dialect);\n if (decimalRefusal !== undefined) {\n throw new ClientInitializationError(\n describeDecimalProviderLimitRefusal(decimalRefusal)\n );\n }\n if (config.driver.adapter.geoPoint === undefined) {\n refuseGeoPointFields(config.schema);\n }\n // ONE resolution for the whole client lifecycle: the gate's index goes\n // straight into the constructor, so the registry and query scopes are\n // composed over the same object (§11.4.10).\n const prepared = reused ?? prepareSchema(config.schema, checked);\n prepared.fittingDialects.add(config.driver.dialect);\n return new VibORM<C>(config, prepared);\n });\n\n return orm.#createRootView<EmptyClientExtensionState, ViewConfig>(\n orm.#engine\n );\n }\n}\n\n/** The driver-independent construction a client derives from its schema. */\ninterface PreparedSchema {\n readonly entries: readonly (readonly [string, unknown])[];\n readonly relations: ResolvedRelationIndex;\n readonly schemaRegistry: ReturnType<typeof createResolvedSchemaRegistry>;\n /** Dialects whose decimal storage limits this schema already fits. */\n readonly fittingDialects: Set<string>;\n /** Whether the full client validation ran, not only relation resolution. */\n readonly validated: boolean;\n}\n\n/**\n * Clients over the same schema object share its validated, resolved views:\n * they derive from the models alone, so a client created per request (one per\n * Worker invocation) skips re-validating and rebuilding them. The entries are\n * compared on reuse, so a schema object that gained or swapped a model since\n * is prepared again.\n */\nconst preparedSchemas = new WeakMap<object, PreparedSchema>();\n\nfunction reusablePreparation(\n schema: Schema,\n checked: boolean\n): PreparedSchema | undefined {\n const prepared = preparedSchemas.get(schema);\n // A validating client never reuses a preparation that skipped validation.\n if (!(prepared && (prepared.validated || checked))) return;\n const keys = Object.keys(schema);\n if (keys.length !== prepared.entries.length) return;\n for (const [index, [key, model]] of prepared.entries.entries()) {\n if (keys[index] !== key || schema[key] !== model) return;\n }\n return prepared;\n}\n\nfunction prepareSchema(schema: Schema, checked: boolean): PreparedSchema {\n const relations = checked\n ? resolveCheckedSchemaOrThrow(schema)\n : resolveSchemaOrThrow(schema);\n const schemaRegistry = createResolvedSchemaRegistry(schema, relations);\n const prepared: PreparedSchema = {\n entries: Object.entries(schema),\n relations,\n schemaRegistry,\n fittingDialects: new Set(),\n validated: !checked,\n };\n preparedSchemas.set(schema, prepared);\n return prepared;\n}\n\n/**\n * Run a client-construction step, re-typing bare failures as ClientInitializationError.\n *\n * Typed VibORM errors (a ValidationError from schema validation, for instance) keep their own\n * class and code — only untyped construction faults are re-typed, and their message is kept\n * verbatim so existing diagnostics still read the same.\n */\nfunction assertConstructed<T>(build: () => T): T {\n try {\n return build();\n } catch (error) {\n if (isVibORMError(error)) {\n throw error;\n }\n const cause = error instanceof Error ? error : undefined;\n throw new ClientInitializationError(\n cause?.message ?? \"Failed to create the VibORM client\",\n cause ? { cause } : undefined\n );\n }\n}\n\n/**\n * Create a VibORM client\n *\n * @example\n * ```ts\n * import { PGlite } from \"@electric-sql/pglite\";\n * import { PGliteDriver } from \"viborm/pglite\";\n * import { createClient } from \"viborm\";\n *\n * const db = new PGlite();\n * const driver = new PGliteDriver({ client: db });\n * const client = createClient({ driver, schema: { user, post } });\n *\n * // Query\n * const users = await client.user.findMany({ where: { name: \"Alice\" } });\n *\n * // Transaction\n * await client.$transaction(async (tx) => {\n * const user = await tx.user.create({ data: { name: \"Bob\" } });\n * await tx.post.create({ data: { title: \"Hello\", authorId: user.id } });\n * });\n *\n * // Raw query\n * const result = await client.$executeRaw(sql`SELECT * FROM users`);\n *\n * // Disconnect\n * await client.$disconnect();\n * ```\n */\nexport const createClient = <S extends Schema, Config extends VibORMConfig<S>>(\n // `Config` captures the whole literal for the result types. The structural\n // refusal rejects unknown keys for fresh and held configuration values.\n config: Config & VibORMConfig<S> & NoExtraConfigKeys<Config, VibORMConfig<S>>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<Config>]: LinkedClientConfig<Config>[P];\n}> => {\n // Explicit `Config`: the parameter's refusal members (`NoExtraConfigKeys`) are\n // there to reject typo'd keys, not to be threaded into the client's result\n // types — inferring `C` from the intersection would carry them along.\n return VibORM.create<\n Config,\n { [P in keyof LinkedClientConfig<Config>]: LinkedClientConfig<Config>[P] }\n >(config);\n};\n\n/**\n * The one driver-wrapper seam. It reads only core client properties, so removed\n * or driver-specific configuration getters are never copied into the core.\n */\nexport const createClientFromDriverConfig = <\n S extends Schema,\n C extends DriverConfig<S>,\n D extends AnyDriver,\n>(\n config: C,\n driver: D\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: D }>]: LinkedClientConfig<\n C & { driver: D }\n >[P];\n}> => {\n const { schema, skipSchemaValidation, findUniqueBatching } = config;\n const coreConfig = {\n schema,\n driver,\n ...(skipSchemaValidation === undefined ? {} : { skipSchemaValidation }),\n ...(findUniqueBatching === undefined ? {} : { findUniqueBatching }),\n };\n return VibORM.create<\n typeof coreConfig,\n {\n [P in keyof LinkedClientConfig<C & { driver: D }>]: LinkedClientConfig<\n C & { driver: D }\n >[P];\n }\n >(coreConfig);\n};\n"],"mappings":"wjEAeA,IAAa,GAAb,MAAa,WAAY,CACvB,OACA,eAKA,YAKA,MAMA,SAEA,QAOA,MAEA,YACE,EACA,EACA,EAAW,OAAO,gBAAgB,CAClC,EAAU,OAAO,eAAe,CAChC,EACA,EACA,EACA,CACA,KAAK,OAAS,EACd,KAAK,MAAQ,EACb,KAAK,eAAiB,EACtB,KAAK,YAAc,EACnB,KAAK,SAAW,EAChB,KAAK,QAAU,EACf,KAAK,MAAQ,EAOf,UAAU,EAAkC,CAC1C,OAAO,IAAI,YACT,KAAK,OACL,KAAK,MACL,KAAK,SACL,KAAK,QACL,KAAK,eACL,KAAK,YACL,EACD,CAGH,KACE,EACA,EAAqD,KAAK,eAC1D,EAA4C,KAAK,YACpC,CACb,OAAO,IAAI,YACT,EACA,KAAK,MACL,KAAK,SACL,OAAO,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