viborm 1.16.1 → 1.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-internals-Dz2nNEF5.mjs +2 -0
- package/dist/adapter-internals-Dz2nNEF5.mjs.map +1 -0
- package/dist/adapter-namespace-C1SUkH2U.mjs +2 -0
- package/dist/{adapter-namespace-DwFnfpED.mjs.map → adapter-namespace-C1SUkH2U.mjs.map} +1 -1
- package/dist/adapters.d.mts +50 -94
- package/dist/adapters.mjs +1 -1
- package/dist/{args-7WgBFd_f.mjs → args-DsGRkPRw.mjs} +2 -2
- package/dist/{args-7WgBFd_f.mjs.map → args-DsGRkPRw.mjs.map} +1 -1
- package/dist/{array-literal-BOzj0E2u.mjs → array-literal-U6SeastY.mjs} +1 -1
- package/dist/{array-literal-BOzj0E2u.mjs.map → array-literal-U6SeastY.mjs.map} +1 -1
- package/dist/auto-names-GpcDfhaw.mjs +2 -0
- package/dist/auto-names-GpcDfhaw.mjs.map +1 -0
- package/dist/batch-refs-BuICt2tu.mjs +2 -0
- package/dist/{batch-refs-Bd8HvwUc.mjs.map → batch-refs-BuICt2tu.mjs.map} +1 -1
- package/dist/better-auth.d.mts +1 -1
- package/dist/better-auth.mjs +2 -2
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +2 -2
- package/dist/cache.mjs +1 -1
- package/dist/call-D2E7dPCd.mjs +2 -0
- package/dist/{call-0bd_B9Vp.mjs.map → call-D2E7dPCd.mjs.map} +1 -1
- package/dist/cli.mjs +6 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-Cq_VcF43.d.mts +183 -0
- package/dist/client-DkNRAOuH.mjs +2 -0
- package/dist/client-DkNRAOuH.mjs.map +1 -0
- package/dist/{planner-CYu6_q4w.d.mts → client-driver-DuQy6lsN.d.mts} +3 -3
- package/dist/client-rIiFOn1W.mjs +9 -0
- package/dist/client-rIiFOn1W.mjs.map +1 -0
- package/dist/client.d.mts +2 -2
- package/dist/client.mjs +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/{confine-CyI9IwjC.mjs → confine-FIfjlAHp.mjs} +2 -2
- package/dist/{confine-CyI9IwjC.mjs.map → confine-FIfjlAHp.mjs.map} +1 -1
- package/dist/{object-store-BBDTj8x3.d.mts → conformance-C1JveA8y.d.mts} +5 -60
- package/dist/conformance-C4JYA0JG.mjs +2 -0
- package/dist/conformance-C4JYA0JG.mjs.map +1 -0
- package/dist/contract-BBone8RD.mjs +2 -0
- package/dist/contract-BBone8RD.mjs.map +1 -0
- package/dist/coordination-BxMskOgi.mjs +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/{database-adapter-01J6mYq5.d.mts → database-adapter-cW0nmWM6.d.mts} +2 -2
- package/dist/datetime-physical-codec-Ci0dyOot.mjs +2 -0
- package/dist/datetime-physical-codec-Ci0dyOot.mjs.map +1 -0
- package/dist/datetime-values-D_G6m5_o.mjs +2 -0
- package/dist/datetime-values-D_G6m5_o.mjs.map +1 -0
- package/dist/decimal-D4DRlT2y.mjs +2 -0
- package/dist/decimal-D4DRlT2y.mjs.map +1 -0
- package/dist/{defaults-DAPb-tJ4.mjs → defaults-BrXUK350.mjs} +2 -2
- package/dist/{defaults-DAPb-tJ4.mjs.map → defaults-BrXUK350.mjs.map} +1 -1
- package/dist/{document-DRPqjDv_.d.mts → document-B8ClXlb7.d.mts} +1 -1
- package/dist/{driver-kiIQS_Fd.mjs → driver-BOsmU3kz.mjs} +2 -2
- package/dist/{driver-kiIQS_Fd.mjs.map → driver-BOsmU3kz.mjs.map} +1 -1
- package/dist/{driver-CTjq1yxj.d.mts → driver-KgGMnfz8.d.mts} +1 -1
- package/dist/{driver-lShUkDmf.mjs → driver-PkP_1p80.mjs} +2 -2
- package/dist/{driver-lShUkDmf.mjs.map → driver-PkP_1p80.mjs.map} +1 -1
- package/dist/{driver-diagnostics-aQ54bArn.mjs → driver-diagnostics-sSpge6kv.mjs} +1 -1
- package/dist/{driver-diagnostics-aQ54bArn.mjs.map → driver-diagnostics-sSpge6kv.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/durable-object.d.mts +1 -1
- package/dist/durable-object.mjs +2 -2
- package/dist/error-mapping-B9rSvgG9.mjs +1 -1
- package/dist/every-tAZuZ50K.mjs +2 -0
- package/dist/{every-CgeIFxWR.mjs.map → every-tAZuZ50K.mjs.map} +1 -1
- package/dist/execution-context-couU2tgh.mjs +1 -1
- package/dist/{exports-nC8lsVKO.d.mts → exports-reE3GioL.d.mts} +1 -1
- package/dist/extension-Bf4vO5mp.mjs +2 -0
- package/dist/extension-Bf4vO5mp.mjs.map +1 -0
- package/dist/facts-Bjnzv3j-.mjs +2 -0
- package/dist/facts-Bjnzv3j-.mjs.map +1 -0
- package/dist/{fs-estate-n-QpsFqb.mjs → fs-estate-C3ahNKmi.mjs} +2 -2
- package/dist/{fs-estate-n-QpsFqb.mjs.map → fs-estate-C3ahNKmi.mjs.map} +1 -1
- package/dist/geo-area-codec-CBdiCOzj.mjs +2 -0
- package/dist/{geo-area-codec-Bti2PA2i.mjs.map → geo-area-codec-CBdiCOzj.mjs.map} +1 -1
- package/dist/geo-point-DCV0eO1p.mjs +2 -0
- package/dist/geo-point-DCV0eO1p.mjs.map +1 -0
- package/dist/id-domain-Cj6MnMxg.mjs +2 -0
- package/dist/{id-domain-Cg65TLZ-.mjs.map → id-domain-Cj6MnMxg.mjs.map} +1 -1
- package/dist/identifier-BdLx66pi.mjs +2 -0
- package/dist/identifier-BdLx66pi.mjs.map +1 -0
- package/dist/identifier-conversion-CMKVatU4.mjs +3 -0
- package/dist/identifier-conversion-CMKVatU4.mjs.map +1 -0
- package/dist/{identifiers-BxOf57qy.mjs → identifiers-BAZ_S6Lk.mjs} +1 -1
- package/dist/{identifiers-BxOf57qy.mjs.map → identifiers-BAZ_S6Lk.mjs.map} +1 -1
- package/dist/{identity-CJlRQA-m.mjs → identity-nPArhpsD.mjs} +2 -2
- package/dist/{identity-CJlRQA-m.mjs.map → identity-nPArhpsD.mjs.map} +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/introspect-dyBpdr2L.mjs +2 -0
- package/dist/{introspect-rGqr93B3.mjs.map → introspect-dyBpdr2L.mjs.map} +1 -1
- package/dist/json-DvvrTWUw.mjs +2 -0
- package/dist/{json-CsAdz9pg.mjs.map → json-DvvrTWUw.mjs.map} +1 -1
- package/dist/{json-number-C09rsm1g.mjs → json-number-Guh-5rff.mjs} +1 -1
- package/dist/{json-number-C09rsm1g.mjs.map → json-number-Guh-5rff.mjs.map} +1 -1
- package/dist/{json-parameter-D7hDrVKw.mjs → json-parameter-DtHhEfyE.mjs} +1 -1
- package/dist/{json-parameter-D7hDrVKw.mjs.map → json-parameter-DtHhEfyE.mjs.map} +1 -1
- package/dist/judge-words-CqNdnbou.mjs +2 -0
- package/dist/judge-words-CqNdnbou.mjs.map +1 -0
- package/dist/{key-BDH6oTyC.mjs → key-v4k7Cqb6.mjs} +2 -2
- package/dist/{key-BDH6oTyC.mjs.map → key-v4k7Cqb6.mjs.map} +1 -1
- package/dist/{keys-CIal55WQ.mjs → keys-BLWaO_YM.mjs} +1 -1
- package/dist/{keys-CIal55WQ.mjs.map → keys-BLWaO_YM.mjs.map} +1 -1
- package/dist/keys-o4Pl6Vsg.mjs +2 -0
- package/dist/{keys-DZdKAd4n.mjs.map → keys-o4Pl6Vsg.mjs.map} +1 -1
- package/dist/libsql-C0iMZifz.mjs +3 -0
- package/dist/libsql-C0iMZifz.mjs.map +1 -0
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/light-reLULeHN.mjs +2 -0
- package/dist/{light-D2wNSbzY.mjs.map → light-reLULeHN.mjs.map} +1 -1
- package/dist/memory-DtTuFo-h.mjs +2 -0
- package/dist/memory-DtTuFo-h.mjs.map +1 -0
- package/dist/methods-part-Dsi0DBNU.mjs +2 -0
- package/dist/{methods-part-BaNx3o7b.mjs.map → methods-part-Dsi0DBNU.mjs.map} +1 -1
- package/dist/migrations/mysql/runtime.d.mts +7 -0
- package/dist/migrations/mysql/runtime.mjs +2 -0
- package/dist/migrations/mysql/runtime.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +7 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/mysql.mjs.map +1 -1
- package/dist/migrations/postgres/runtime.d.mts +7 -0
- package/dist/migrations/postgres/runtime.mjs +2 -0
- package/dist/migrations/postgres/runtime.mjs.map +1 -0
- package/dist/migrations/postgres.d.mts +7 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/postgres.mjs.map +1 -1
- package/dist/migrations/snowflake.d.mts +7 -5
- package/dist/migrations/snowflake.mjs +1 -1
- package/dist/migrations/snowflake.mjs.map +1 -1
- package/dist/migrations/sqlite/runtime.d.mts +7 -0
- package/dist/migrations/sqlite/runtime.mjs +2 -0
- package/dist/migrations/sqlite/runtime.mjs.map +1 -0
- package/dist/migrations/sqlite.d.mts +7 -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 +7 -5
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/surrealdb.mjs.map +1 -1
- package/dist/migrations/tenant.d.mts +4 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations/tenant.mjs.map +1 -1
- package/dist/migrations.d.mts +7 -5
- package/dist/migrations.mjs +1 -1
- package/dist/migrations.mjs.map +1 -1
- package/dist/model-ByktcCGW.mjs +2 -0
- package/dist/model-ByktcCGW.mjs.map +1 -0
- package/dist/mysql-DPYi1p_g.mjs +4 -0
- package/dist/mysql-DPYi1p_g.mjs.map +1 -0
- package/dist/mysql-adapter-6gVm5PHp.mjs +2 -0
- package/dist/{mysql-adapter-BFWYPoM0.mjs.map → mysql-adapter-6gVm5PHp.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/{named-statements-CkOOD__I.mjs → named-statements-CswIc5m1.mjs} +2 -2
- package/dist/{named-statements-CkOOD__I.mjs.map → named-statements-CswIc5m1.mjs.map} +1 -1
- package/dist/native-types-BUkcVedc.mjs +2 -0
- package/dist/native-types-BUkcVedc.mjs.map +1 -0
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/normalized-result-D7nVkF36.mjs +1 -1
- package/dist/{object-store-Chq1PMYz.mjs → object-store-DnrLNxz_.mjs} +2 -2
- package/dist/{object-store-Chq1PMYz.mjs.map → object-store-DnrLNxz_.mjs.map} +1 -1
- package/dist/object-store-j4kgh61D.d.mts +59 -0
- package/dist/{on-ZkOVmE4-.mjs → on-nOenqmgP.mjs} +2 -2
- package/dist/{on-ZkOVmE4-.mjs.map → on-nOenqmgP.mjs.map} +1 -1
- package/dist/on.d.mts +1 -1
- package/dist/on.mjs +1 -1
- package/dist/ordering/keys.mjs +1 -1
- package/dist/ordering.d.mts +1 -1
- package/dist/ordering.mjs +2 -2
- package/dist/pending-operation-B5o-zhES.mjs +2 -0
- package/dist/{pending-operation-D4gUKMxD.mjs.map → pending-operation-B5o-zhES.mjs.map} +1 -1
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/pg.d.mts +2 -2
- package/dist/pg.mjs +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/{physical-DO4PEYcc.mjs → physical-BheMRPY0.mjs} +2 -2
- package/dist/{physical-DO4PEYcc.mjs.map → physical-BheMRPY0.mjs.map} +1 -1
- package/dist/{pinned-session-Y7-2pRBJ.mjs → pinned-session-eNyd0dkT.mjs} +2 -2
- package/dist/{pinned-session-Y7-2pRBJ.mjs.map → pinned-session-eNyd0dkT.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/postgres-CEGFOi8D.mjs +27 -0
- package/dist/postgres-CEGFOi8D.mjs.map +1 -0
- package/dist/postgres-adapter-B-im38AE.mjs +2 -0
- package/dist/postgres-adapter-B-im38AE.mjs.map +1 -0
- package/dist/{postgres-adapter-BpLizOaK.mjs → postgres-adapter-OoqoBdhb.mjs} +2 -2
- package/dist/{postgres-adapter-BpLizOaK.mjs.map → postgres-adapter-OoqoBdhb.mjs.map} +1 -1
- package/dist/{postgres-result-133boRW-.mjs → postgres-result-D-bqmofR.mjs} +1 -1
- package/dist/{postgres-result-133boRW-.mjs.map → postgres-result-D-bqmofR.mjs.map} +1 -1
- package/dist/postgres.d.mts +2 -2
- package/dist/postgres.mjs +1 -1
- package/dist/provider-limits-DvcCUw7l.mjs +2 -0
- package/dist/{provider-limits-SdI1SaJS.mjs.map → provider-limits-DvcCUw7l.mjs.map} +1 -1
- package/dist/{provider-parameter-snapshot-cyTUDutH.mjs → provider-parameter-snapshot-DnJ6Av9y.mjs} +2 -2
- package/dist/{provider-parameter-snapshot-cyTUDutH.mjs.map → provider-parameter-snapshot-DnJ6Av9y.mjs.map} +1 -1
- package/dist/push-fingerprint-CegYVFFp.mjs +18 -0
- package/dist/push-fingerprint-CegYVFFp.mjs.map +1 -0
- package/dist/{quantized-BKBs0joq.mjs → quantized-DLD2cd6q.mjs} +1 -1
- package/dist/{quantized-BKBs0joq.mjs.map → quantized-DLD2cd6q.mjs.map} +1 -1
- package/dist/query-DSEMPA7r.mjs +2 -0
- package/dist/query-DSEMPA7r.mjs.map +1 -0
- package/dist/query-backend-CzwVfrQ6.mjs +2 -0
- package/dist/{query-backend-TisPjCPF.mjs.map → query-backend-CzwVfrQ6.mjs.map} +1 -1
- package/dist/{query-inspection-DwYBKSDG.mjs → query-inspection-CvtTL5Fs.mjs} +2 -2
- package/dist/{query-inspection-DwYBKSDG.mjs.map → query-inspection-CvtTL5Fs.mjs.map} +1 -1
- package/dist/raw-B8cNef_V.mjs +2 -0
- package/dist/{raw-DqEb71JZ.mjs.map → raw-B8cNef_V.mjs.map} +1 -1
- package/dist/{relation-bound-CSNKLyDy.mjs → relation-bound-DHP5cpTE.mjs} +1 -1
- package/dist/{relation-bound-CSNKLyDy.mjs.map → relation-bound-DHP5cpTE.mjs.map} +1 -1
- package/dist/{result-parsing-BbffueEX.mjs → result-parsing-DfwBAXY2.mjs} +1 -1
- package/dist/{result-parsing-BbffueEX.mjs.map → result-parsing-DfwBAXY2.mjs.map} +1 -1
- package/dist/{rows-of-Bgl9GVtK.mjs → rows-of-UeSasWGq.mjs} +2 -2
- package/dist/{rows-of-Bgl9GVtK.mjs.map → rows-of-UeSasWGq.mjs.map} +1 -1
- package/dist/rule-words-ojG0-vSf.mjs +2 -0
- package/dist/{rule-words-DMbQuvD2.mjs.map → rule-words-ojG0-vSf.mjs.map} +1 -1
- package/dist/runtime-BAqlANG_.mjs +10 -0
- package/dist/runtime-BAqlANG_.mjs.map +1 -0
- package/dist/runtime-D0oaIS1E.mjs +2 -0
- package/dist/runtime-D0oaIS1E.mjs.map +1 -0
- package/dist/runtime-Dfkv59_p.mjs +15 -0
- package/dist/runtime-Dfkv59_p.mjs.map +1 -0
- package/dist/runtime-client-CvGGOOFd.d.mts +38 -0
- package/dist/runtime-client-xeiXA_1m.mjs +2 -0
- package/dist/runtime-client-xeiXA_1m.mjs.map +1 -0
- package/dist/scalar-BTYxpiP_.mjs +4 -0
- package/dist/scalar-BTYxpiP_.mjs.map +1 -0
- package/dist/schema/introspect.d.mts +2 -2
- package/dist/schema/introspect.mjs +1 -1
- package/dist/schema/json.d.mts +2 -2
- package/dist/schema/json.mjs +1 -1
- package/dist/schema-BzkBJTF-.mjs +2 -0
- package/dist/{schema-DDkAUfOb.mjs.map → schema-BzkBJTF-.mjs.map} +1 -1
- package/dist/schema-D7MyYTjA.mjs +2 -0
- package/dist/{schema-DqR_Kcje.mjs.map → schema-D7MyYTjA.mjs.map} +1 -1
- package/dist/{schema-introspection-Bbo4DN_d.mjs → schema-introspection-b4xPGPfu.mjs} +4 -4
- package/dist/{schema-introspection-Bbo4DN_d.mjs.map → schema-introspection-b4xPGPfu.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-CEpNu-Gw.mjs → select-assembly-B01JtBRm.mjs} +2 -2
- package/dist/{select-assembly-CEpNu-Gw.mjs.map → select-assembly-B01JtBRm.mjs.map} +1 -1
- package/dist/serializer-CIhcZMxs.mjs +7 -0
- package/dist/serializer-CIhcZMxs.mjs.map +1 -0
- package/dist/{settle-Pui-1tfJ.mjs → settle-CIbvnLED.mjs} +1 -1
- package/dist/{settle-Pui-1tfJ.mjs.map → settle-CIbvnLED.mjs.map} +1 -1
- package/dist/{settled-DYYPcaBX.mjs → settled-Clanz_kI.mjs} +2 -2
- package/dist/{settled-DYYPcaBX.mjs.map → settled-Clanz_kI.mjs.map} +1 -1
- package/dist/snowflake-C1dqbche.mjs +2 -0
- package/dist/{snowflake-B8Ei88bg.mjs.map → snowflake-C1dqbche.mjs.map} +1 -1
- package/dist/snowflake.d.mts +2 -2
- package/dist/snowflake.mjs +2 -2
- package/dist/snowflake.mjs.map +1 -1
- package/dist/soft-delete.d.mts +1 -1
- package/dist/soft-delete.mjs +1 -1
- package/dist/{spans-DwDXMvyd.mjs → spans-CVl3RKUR.mjs} +1 -1
- package/dist/{spans-DwDXMvyd.mjs.map → spans-CVl3RKUR.mjs.map} +1 -1
- package/dist/sql-AHN2niBz.mjs +2 -0
- package/dist/{sql-M5WsPhqr.mjs.map → sql-AHN2niBz.mjs.map} +1 -1
- package/dist/sql-control-Cdp0_Mwy.mjs +2 -0
- package/dist/sql-control-Cdp0_Mwy.mjs.map +1 -0
- package/dist/{sql-statement-tokens-Z5Ta4iDB.mjs → sql-statement-tokens-BdVJnUQY.mjs} +2 -2
- package/dist/{sql-statement-tokens-Z5Ta4iDB.mjs.map → sql-statement-tokens-BdVJnUQY.mjs.map} +1 -1
- package/dist/sql-tegqTqGq.mjs +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sqlite-adapter-B7r7w3CS.mjs +2 -0
- package/dist/sqlite-adapter-B7r7w3CS.mjs.map +1 -0
- package/dist/{sqlite-statement-classifier-JBHiQO6Q.mjs → sqlite-statement-classifier-CBmKy8Ta.mjs} +2 -2
- package/dist/{sqlite-statement-classifier-JBHiQO6Q.mjs.map → sqlite-statement-classifier-CBmKy8Ta.mjs.map} +1 -1
- package/dist/sqlite-storage-audit-D8nA9ylL.mjs +2 -0
- package/dist/sqlite-storage-audit-D8nA9ylL.mjs.map +1 -0
- package/dist/{sqlite-utils-Bfmtkt1b.mjs → sqlite-utils-BAUMCrok.mjs} +2 -2
- package/dist/{sqlite-utils-Bfmtkt1b.mjs.map → sqlite-utils-BAUMCrok.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/{standard-sql-Bl2OHGfi.mjs → standard-sql-tpcKlArE.mjs} +2 -2
- package/dist/{standard-sql-Bl2OHGfi.mjs.map → standard-sql-tpcKlArE.mjs.map} +1 -1
- package/dist/surrealdb.d.mts +2 -2
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/surrealql-AyDLKSEQ.mjs +2 -0
- package/dist/surrealql-AyDLKSEQ.mjs.map +1 -0
- package/dist/time-step-BIdl2Iy7.mjs +2 -0
- package/dist/time-step-BIdl2Iy7.mjs.map +1 -0
- package/dist/transaction-operation-CaWzo7gE.mjs +1 -1
- package/dist/type-mapping-BYre7JQ1.mjs +3 -0
- package/dist/type-mapping-BYre7JQ1.mjs.map +1 -0
- package/dist/{types-Dy33vBdd.mjs → types-M-IdB4Mo.mjs} +1 -1
- package/dist/{types-Dy33vBdd.mjs.map → types-M-IdB4Mo.mjs.map} +1 -1
- package/dist/{unit-DUPX5Sdd.mjs → unit-Dnp2HIWg.mjs} +2 -2
- package/dist/{unit-DUPX5Sdd.mjs.map → unit-Dnp2HIWg.mjs.map} +1 -1
- package/dist/{unit-words-BXpLpyr2.mjs → unit-words-DjVhRXAQ.mjs} +2 -2
- package/dist/{unit-words-BXpLpyr2.mjs.map → unit-words-DjVhRXAQ.mjs.map} +1 -1
- package/dist/{utils-BHkJsduV.mjs → utils-BB_4NZQC.mjs} +2 -2
- package/dist/{utils-BHkJsduV.mjs.map → utils-BB_4NZQC.mjs.map} +1 -1
- package/dist/utils-DYrxwV_M.mjs +2 -0
- package/dist/utils-DYrxwV_M.mjs.map +1 -0
- package/dist/{v1-parse-shared-cJ-uD14P.mjs → v1-parse-shared-CNiFHAJF.mjs} +1 -1
- package/dist/{v1-parse-shared-cJ-uD14P.mjs.map → v1-parse-shared-CNiFHAJF.mjs.map} +1 -1
- package/dist/validation-CEnhYqhl.mjs +2 -0
- package/dist/{validation-BHjx13zG.mjs.map → validation-CEnhYqhl.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-CISkL46K.mjs +2 -0
- package/dist/validator-CISkL46K.mjs.map +1 -0
- package/dist/{values-Ch2cTlss.mjs → values-D0k60ei0.mjs} +2 -2
- package/dist/{values-Ch2cTlss.mjs.map → values-D0k60ei0.mjs.map} +1 -1
- package/dist/{client-Bb2oZOzg.d.mts → verify-v1-CJFrJ4lx.d.mts} +10 -183
- package/dist/version-nEOMCWfV.mjs +2 -0
- package/dist/{version-Bu2LCuaj.mjs.map → version-nEOMCWfV.mjs.map} +1 -1
- package/dist/view-CmLQ0I6x.mjs +2 -0
- package/dist/{view-CHgjF2BO.mjs.map → view-CmLQ0I6x.mjs.map} +1 -1
- package/dist/write-sinks-BhwgQn_5.mjs +2 -0
- package/dist/{write-sinks-Bei5vFHP.mjs.map → write-sinks-BhwgQn_5.mjs.map} +1 -1
- package/package.json +27 -2
- package/dist/adapter-namespace-DwFnfpED.mjs +0 -2
- package/dist/batch-refs-Bd8HvwUc.mjs +0 -2
- package/dist/call-0bd_B9Vp.mjs +0 -2
- package/dist/client-BvAmGuYW.mjs +0 -9
- package/dist/client-BvAmGuYW.mjs.map +0 -1
- package/dist/client-Q4zkYZbn.mjs +0 -2
- package/dist/client-Q4zkYZbn.mjs.map +0 -1
- package/dist/datetime-physical-codec-DAF7WJpy.mjs +0 -2
- package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +0 -1
- package/dist/every-CgeIFxWR.mjs +0 -2
- package/dist/extension-Dh1ddrlA.mjs +0 -2
- package/dist/extension-Dh1ddrlA.mjs.map +0 -1
- package/dist/geo-area-codec-Bti2PA2i.mjs +0 -2
- package/dist/id-domain-Cg65TLZ-.mjs +0 -2
- package/dist/identifier-conversion-BTDxDwDB.mjs +0 -2
- package/dist/identifier-conversion-BTDxDwDB.mjs.map +0 -1
- package/dist/introspect-rGqr93B3.mjs +0 -2
- package/dist/json-CsAdz9pg.mjs +0 -2
- package/dist/judge-words-k5GCc4cV.mjs +0 -2
- package/dist/judge-words-k5GCc4cV.mjs.map +0 -1
- package/dist/keys-DZdKAd4n.mjs +0 -2
- package/dist/libsql-BZAXy5PY.mjs +0 -3
- package/dist/libsql-BZAXy5PY.mjs.map +0 -1
- package/dist/light-D2wNSbzY.mjs +0 -2
- package/dist/memory-DgBGBQdJ.mjs +0 -2
- package/dist/memory-DgBGBQdJ.mjs.map +0 -1
- package/dist/methods-part-BaNx3o7b.mjs +0 -2
- package/dist/model-Dtd37Sky.mjs +0 -2
- package/dist/model-Dtd37Sky.mjs.map +0 -1
- package/dist/mysql-BjIAoFH6.mjs +0 -9
- package/dist/mysql-BjIAoFH6.mjs.map +0 -1
- package/dist/mysql-adapter-BFWYPoM0.mjs +0 -2
- package/dist/native-types-1ewJXVks.mjs +0 -2
- package/dist/native-types-1ewJXVks.mjs.map +0 -1
- package/dist/pending-operation-D4gUKMxD.mjs +0 -2
- package/dist/postgres-CaMB2Y4p.mjs +0 -35
- package/dist/postgres-CaMB2Y4p.mjs.map +0 -1
- package/dist/postgres-adapter-psTVfuw7.mjs +0 -2
- package/dist/postgres-adapter-psTVfuw7.mjs.map +0 -1
- package/dist/provider-limits-SdI1SaJS.mjs +0 -2
- package/dist/query-BTb6iakn.mjs +0 -2
- package/dist/query-BTb6iakn.mjs.map +0 -1
- package/dist/query-backend-TisPjCPF.mjs +0 -2
- package/dist/raw-DqEb71JZ.mjs +0 -2
- package/dist/rule-words-DMbQuvD2.mjs +0 -2
- package/dist/scalar-Dm9brvAU.mjs +0 -4
- package/dist/scalar-Dm9brvAU.mjs.map +0 -1
- package/dist/schema-DDkAUfOb.mjs +0 -2
- package/dist/schema-DqR_Kcje.mjs +0 -2
- package/dist/serializer-Br9JgpQI.mjs +0 -33
- package/dist/serializer-Br9JgpQI.mjs.map +0 -1
- package/dist/snowflake-B8Ei88bg.mjs +0 -2
- package/dist/sql-M5WsPhqr.mjs +0 -2
- package/dist/sqlite-adapter-Cb-SJw2f.mjs +0 -2
- package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +0 -1
- package/dist/surrealql-f2Rgu47F.mjs +0 -2
- package/dist/surrealql-f2Rgu47F.mjs.map +0 -1
- package/dist/time-step-DJaIhpAz.mjs +0 -2
- package/dist/time-step-DJaIhpAz.mjs.map +0 -1
- package/dist/validation-BHjx13zG.mjs +0 -2
- package/dist/validator-DMzH5Tz0.mjs +0 -2
- package/dist/validator-DMzH5Tz0.mjs.map +0 -1
- package/dist/version-Bu2LCuaj.mjs +0 -2
- package/dist/view-CHgjF2BO.mjs +0 -2
- package/dist/write-sinks-Bei5vFHP.mjs +0 -2
- /package/dist/{contract-CxJn0_cV.d.mts → contract-CAoFgKSO.d.mts} +0 -0
- /package/dist/{named-statements-NF7Iycjk.d.mts → named-statements-CT4Gbd6t.d.mts} +0 -0
- /package/dist/{sql-C4_sFNDm.d.mts → sql-C-SBCGCx.d.mts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-DkNRAOuH.mjs","names":["#q","#projections","#within","sql","#projection","#probe","#tombstones","#answered","#limited","#sets","#decode","sent","side","#n","sent","#schema","#transport","#hear","#made","#log","#known","#meta","#concrete","#missed","#presumed","#used","#left","#stale","#touched","#again","#members","#says","#absences","#reset","#learnt","#learn","#settle","#sent","#whole","#deliver","#steps","#delivered","#fail","#markConcrete","#answers","#asserted","#outcomes","#handed","#raw","loose","#asked","#absent","#said","#of","#about","#waited","#name","holds","#linked","#pend","#putKnown","#putMeta","#holds","#changed","#rows","#spoiled","#recalled","read","#presume","#attempting","#heard","#note","#seen","#spoil","#follow","#key","#cascades","#writing","#markDeleted","#told","#copies","rows","within","#attempted","#store","#operation","#schema","#q","#said","#make","#born","#nested","#leave","#memberOne","#paired","#stated","#writes","#updateSet","#plain","#members","#several","#write","#copyUpdate","#createNested","#made","#join","#markMissing","#relationsOf","#spelled","#keyed","#relationsIn","#referencing","#slots","#moved","row","#single","#once","#after","#relate","old","#reaching","#set","#decode","#one","#answering","#many","#removes","loose","#config","#queries","#modelName","#requested","#operation","#rawArgs","#scope","#model","#missing","#admitted","#prepared","#read","#facts","#context","schema","target","#schema","#snapshot","#engine","#relations","#registry","#modelNames","#prepareModelOperation","#prepareChainedModelOperation","call","#extensionOmitResolvers","#createClient","#transact","#createViewProxy","#createView","#resolveClientOmit","#createRootView","prepared"],"sources":["../src/query-engine/query-engine.ts","../src/drivers/positional-result.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","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}\" malformed positional rows for \"${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) => [\n column,\n Object.hasOwn(row, index) ? row[index] : undefined,\n ])\n )\n );\n return { rows, rowCount: rows.length };\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 Queries,\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 { hasOwn, 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 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 /** The view the call's read was prepared by, where its preparer names one. */\n readonly #reader: Queries | undefined;\n #queries: SqlQueries | 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 reader?: Queries\n ) {\n this.schema = schema;\n this.scope = scope;\n this.modelName = modelName;\n this.operation = operation;\n this.#caller = caller;\n this.#reader = reader;\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 }\n\n /**\n * The call's own statement owner: the aliases it counts and the rows its\n * statements read are this call's. Made where the call first states or\n * decodes with it, which a read answered by the driver it was prepared for\n * never does ({@link #decoder}).\n */\n get queries(): SqlQueries {\n return (this.#queries ??= new (this.backend?.queries ?? SqlQueries)(\n this.schema,\n this.driver.adapter,\n this.driver.result,\n this.scope?.domain,\n this.scope\n ) as SqlQueries);\n }\n\n /**\n * What decodes a read's rows. The view that prepared the read does, where\n * the call has no row scope and the driver that answers is the one that\n * view was made for: decoding reads the adapter and the driver's parser and\n * nothing of a statement, and compiles its reader per batch either way. A\n * statement owner made only to decode was 4 % of a `findUnique`'s client\n * CPU and 0.7 kB. Any other call decodes with its own.\n */\n get #decoder(): Queries {\n const reader = this.#reader;\n return reader && !this.scope && reader.decs(this.driver)\n ? reader\n : this.queries;\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 `\"${operation}\" invalid ${scalarType} result: ${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 const decoder = this.#decoder;\n decoder.chkRows(read.query, rows.length);\n return decoder.decodeResult(rows, this.operation, (raw) =>\n decoder.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 const decoder = this.#decoder;\n decoder.chkRows(read.query, response.rows.length);\n return decide(\n read,\n missing,\n decoder.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 pubPrep(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 result for '${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 reqAtom(): 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}\" lacks transactions and atomic batches.`,\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 ? \"Non-returning upsert requires rollback.\"\n : `Driver '${driver.driverName}' '${this.operation}' requires rollback.`,\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, [InsertValue, 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);\n if (entry) entry[1].push(index);\n else fields.set(field, [value, [index]]);\n }\n }\n }\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, [InsertValue, 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 #overWrites: WeakMap<PreparedProjection, readonly [Sql, boolean]> | undefined;\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 (keys.some((key) => key.some((field) => hasOwn(written, field))))\n return false;\n }\n return this.#overWrite(model, projection)[1];\n }\n\n #overWrite(\n model: AnyModel,\n projection: PreparedProjection\n ): readonly [Sql, 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 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] as const;\n (this.#overWrites ??= new WeakMap()).set(projection, over);\n return over;\n }\n\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.reqAtom();\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 fromEntries,\n isArr,\n listed,\n nameOf,\n objEntries,\n objKeys,\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\nconst relatedOf = (question: Question): \"root\" | \"related\" =>\n question.member || question.through ? \"related\" : \"root\";\n\nconst membershipOf = (question: Question) =>\n question.member && {\n edge: question.member.edge,\n parent: question.member.of,\n };\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 /** 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, referenced, limit } = question;\n const only = keys ?? question.only;\n const known = only && q.includeIdentities(model, only);\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 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 related = relatedOf(question);\n const taken = q.candidates(own, related, undefined, this.judged(question));\n const tomb = scope?.rows.tombstones;\n const chosen =\n question.intent === \"delete\" &&\n scope &&\n scope.defaults !== scope.domain &&\n tomb?.has(nameOf(model))\n ? q.candidates(taken, related, scope.defaults)\n : taken;\n if (!referenced) return chosen;\n return q.andSelectors(model, [\n limit === undefined || only ? chosen : q.window(chosen, limit),\n tomb!.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: fromEntries(fields.map((field) => [field, true])) },\n true\n );\n }\n /** The whole row of a model, and its key, as projections. */\n #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 /** `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.memWhere(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.mL(\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 objEntries(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 q = this.#q;\n const [question] = questions as [Question];\n const { model, joined, limit } = question;\n const selectors = questions.map((each) => this.selector(each));\n const { filters, subqueries } = this.adapter;\n return q.select(\n model,\n limit === undefined ? {} : { take: limit },\n membershipOf(question),\n {\n forUpdate: hold,\n condition:\n joined &&\n ((alias) => {\n const join = joined.join(\n q.spelling(model, this.operation.driver.dialect),\n alias\n );\n return q.settle(\n filters.some(subqueries.existsCheck(join.source, join.on))\n );\n }),\n projection: this.#projection(model, true),\n selector:\n selectors.length === 1\n ? selectors[0]\n : {\n model,\n predicate: {\n kind: \"or\",\n predicates: selectors.map((each) => each.predicate!),\n },\n },\n }\n );\n }\n #probe(\n model: AnyModel,\n options: Parameters<SqlQueries[\"select\"]>[3],\n controls: Parameters<SqlQueries[\"select\"]>[1] = { take: 1 },\n membership?: Parameters<SqlQueries[\"select\"]>[2]\n ): Sql {\n return this.#q.select(model, controls, membership, {\n projection: this.#projection(model, false),\n ...options,\n }).sql;\n }\n /** What a call refuses with where a row a question asks for is not there. */\n abs(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} '${edge.name}': target not found${question.member ? \" for 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 */\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, capabilities } = this.adapter;\n const [[question]] = asked as [[Question]];\n const { model } = question;\n const lock = held && capabilities.supportsRowLocks;\n const asking = (\n [each, key]: readonly [Question, (Input | Input[])?],\n more?: Sql\n ) => {\n const keys = isArr(key) ? key : undefined;\n return this.#probe(\n model,\n {\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 { take: 1, ...(keys && { skip: keys.length - 1 }) },\n membershipOf(each)\n );\n };\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 sql: heard && lock ? probe : this.asserts(probe, \"exists\"),\n probe,\n premise: \"exists\",\n believed: believed === \"presumed\" && question.must ? undefined : believed,\n stops: this.abs(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 (objKeys(kept).length > 0)\n written =\n kind === \"create\"\n ? schema.mkVals(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 /** What a row of `model` takes instead of going, where its model keeps the rows it deletes; none where it removes them. */\n mks(model: AnyModel): Input | undefined {\n return this.#tombstones?.marks(this, model);\n }\n get #tombstones() {\n return this.operation.scope?.rows.tombstones;\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 refd(member: Question[\"member\"], of?: Input): Question[\"referenced\"] {\n return this.#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 restr(model: AnyModel): PreparedGuardFailure | undefined {\n return this.#tombstones!.restriction(this.operation.schema, model);\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 stl(model: AnyModel, values: Input): Statement {\n const probe = this.#probe(model, {\n selector: this.#q.prepareSelector(model, values, false),\n });\n return {\n model,\n sql: this.asserts(probe, \"exists\"),\n probe,\n premise: \"exists\",\n stops: {\n kind: \"query\",\n message: `Created '${nameOf(model)}' changed across 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 bsd(\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 = objKeys(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 let written: Sql;\n if (fields.length > 0) {\n const columns = fields.map((field) => q.columnName(model, field));\n let source: Sql[][] | { readonly select: Sql };\n if (judged) {\n source = { select: judged.probe };\n } else {\n const encoders = fields.map((field) =>\n q.fieldValueEncoder(model, field)\n );\n const built = new Array<Sql[]>(rows.length);\n for (let r = 0; r < rows.length; r++) {\n const row = rows[r]!;\n const cells = new Array<Sql>(fields.length);\n for (let c = 0; c < fields.length; c++) {\n cells[c] = encoders[c]!(row[fields[c]!]);\n }\n built[r] = cells;\n }\n source = built;\n }\n written = mutations.insert(\n q.table(model),\n columns,\n source,\n skip?.prefix\n );\n } else {\n written = mutations.insertDefault(q.table(model));\n }\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) =>\n this.#within(question, alias, q.lowerSelector(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.settle(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 cmp(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 objEntries(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 jdg(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.abs(question)\n ): Statement {\n const { model, strict } = question;\n const probe = this.#probe(\n model,\n {\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 { take: 1 },\n membershipOf(question)\n );\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 loc(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 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.jW(edge, {\n ...own,\n ...(to && named(edge.targetSide, to)),\n }),\n ...kept.map((row) =>\n operators.not(\n q.jW(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 get passes(): boolean {\n return false;\n }\n get sy(): boolean {\n return this.adapter.capabilities.supportsReturning;\n }\n cnts(kind: string): boolean {\n return kind === \"delete\" || this.operation.driver.dialect !== \"mysql\";\n }\n scr(id: string, model: AnyModel): { 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 kpt(\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 key(model: AnyModel): PreparedProjection {\n return this.#projection(model, false);\n }\n #decode(projection: PreparedProjection, rows: Input[]): Input[] {\n return rows.length > 0\n ? (this.#q.decodeProjection(projection.shape, rows, true) as Input[])\n : [];\n }\n tld(model: AnyModel, fields: readonly string[], rows: Input[]): Input[] {\n return fields.length > 0\n ? this.#decode(this.fields(model, fields), rows)\n : [];\n }\n keys(model: AnyModel, rows: Input[]): Input[] {\n return this.#decode(this.#projection(model, false), rows);\n }\n cnt(sent: Sent): number {\n return this.adapter.capabilities.countsCascadedChanges\n ? sent.rows.length\n : sent.rowCount;\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 '${edge.name}': '${name}' requires ${missing.map((f) => `$through.${f}`).join(\", \")}.`,\n edge.name\n );\n const sink = writeSinks.get(attribution);\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 '${edge.name}': extensions observe '${name}'; write via '${name}' delegate.`\n );\n return {\n row: {\n ...schema.mkVals(\n model,\n 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 && objKeys(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 async link(\n edge: Junction,\n pairs: readonly (readonly [Input, Input])[],\n through?: Input\n ): Promise<Statement[]> {\n const { identifiers, mutations, operators, set } = this.adapter;\n const { uniqueSide, declared } = edge;\n const q = this.#q;\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 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 objEntries(own.row)) {\n columns.push(this.operation.schema.physicalField(model, field).name);\n for (const row of rows) row.push(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 (name === \"source\" ? edge.sourceSide : edge.targetSide).members.map(\n (pair) => pair.junctionField\n );\n const other =\n uniqueSide && side(uniqueSide === \"source\" ? \"target\" : \"source\");\n const statements = other\n ? rows.flatMap((row) => {\n const val = (column: string) => row[columns.indexOf(column)]!;\n return mutations.insertAbsent(\n table,\n columns,\n [row],\n side(uniqueSide!),\n listed(\n other.map((column) =>\n set.assign(identifiers.escape(column), val(column))\n )\n ),\n operators.and(\n ...other.map((column) =>\n operators.eq(\n identifiers.column(edge.table, column),\n val(column)\n )\n )\n )\n );\n })\n : mutations.insertAbsent(\n table,\n columns,\n rows,\n declared?.key ?? columns,\n takes\n );\n return statements.map((statement) => ({\n sql: statement,\n model: edge.source,\n }));\n }\n}\n","/**\n * The image: what one call believes of the rows it touches.\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 {\n fromEntries,\n hasOwn,\n isArr,\n nameOf,\n objKeys,\n pushTo,\n same,\n scalarsOf,\n} 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. */\nexport class Lost {\n readonly f: unknown;\n constructor(failure: unknown) {\n this.f = failure;\n }\n}\n\ninterface Meta {\n readonly m: AnyModel;\n readonly q?: Question;\n /** made */\n c?: true;\n /** at */\n a?: number;\n /** partial */\n p?: true;\n /** named */\n readonly n?: string;\n /** gone */\n g?: true;\n /** moved */\n v?: true;\n /** stood */\n s?: Input;\n /** passed */\n x?: true;\n /** wrote */\n w?: Set<string>;\n /** born */\n b?: Input;\n /** inserted count */\n i?: number;\n}\n\n/** What a set write says once it is sent. */\nexport interface Later {\n s?: Sent;\n c?: boolean;\n}\n\nclass Pending {\n readonly r: Row;\n readonly f: string;\n readonly a: number;\n readonly s?: () => unknown;\n readonly n: boolean;\n readonly #n: string;\n constructor(\n r: Row,\n f: string,\n name: string,\n a: number,\n s?: () => unknown,\n n = false\n ) {\n this.r = r;\n this.f = f;\n this.#n = name;\n this.a = a;\n this.s = s;\n this.n = n;\n }\n toString(): string {\n return this.#n;\n }\n}\n\nconst UNHEARD = Symbol(\"unheard\");\nconst PASSED = Symbol(\"passed\");\nexport const SEVERAL = Symbol(\"several\");\n\nexport const text = (value: unknown): string =>\n JSON.stringify(value, (_, each) =>\n typeof each === \"bigint\" ? `${each}n` : each\n );\n\nconst pick = (row: Input, fields: Iterable<string>): Input => {\n const out: Input = {};\n for (const field of fields) out[field] = row[field];\n return out;\n};\n\nconst endOf = (side: Junction[\"sourceSide\"], row: Row): Input =>\n pick(\n row,\n side.members.map((pair) => pair.referencedField)\n );\n\nconst linksReady = ({ edge, of }: NonNullable<Question[\"member\"]>): boolean =>\n edge.kind !== \"junction\" ||\n edge.sourceSide.members.every(\n (pair) => of[pair.referencedField] !== undefined\n );\n\nconst hasWritten = (sent: readonly Sent[]): boolean =>\n sent.some((each) => each.rowCount > 0 || each.rows.length > 0);\n\nconst oneStatement = (p: Statement | Promise<Statement>) =>\n after(p, (s) => [s]);\n\ntype InsertEntry = {\n readonly k: \"i\";\n readonly r: Row;\n readonly l?: string;\n readonly d: readonly string[];\n};\ntype UpdateEntry = {\n readonly k: \"u\";\n readonly r: Row;\n readonly y: Input;\n readonly s: Input;\n readonly h: readonly string[];\n readonly q: Question;\n};\ntype DeleteEntry = {\n readonly k: \"d\";\n readonly r: Row;\n readonly y: Input;\n readonly q: Question;\n};\ntype AllEntry = {\n readonly k: \"a\";\n readonly q: Question;\n readonly s?: Input;\n readonly p?: PreparedProjection;\n};\ntype SkippingEntry = {\n readonly k: \"s\";\n readonly m: AnyModel;\n readonly rs: readonly Input[];\n readonly p?: PreparedProjection;\n readonly ps: boolean;\n};\ntype EitherEntry = {\n readonly k: \"e\";\n readonly q: Question;\n readonly r: Input;\n readonly s: Input;\n readonly p: PreparedProjection;\n readonly mk?: Sql;\n};\ntype LinkEntry = {\n readonly k: \"l\";\n readonly e: Junction;\n readonly f: Row;\n readonly t: Row;\n readonly ks: readonly [Input, Input];\n readonly th?: Input;\n};\ntype UnlinkEntry = {\n readonly k: \"x\";\n readonly e: Junction;\n readonly f: Row;\n readonly t?: Row;\n readonly kp: readonly Row[];\n readonly ks: readonly [Input, Input | undefined, Input[]];\n};\ntype NoneEntry = {\n readonly k: \"n\";\n readonly q: Question;\n readonly st?: PreparedGuardFailure;\n readonly b?: true;\n};\ntype ReadEntry = {\n readonly k: \"r\";\n readonly m: AnyModel;\n readonly rs: readonly Row[];\n readonly p?: PreparedProjection;\n readonly qs: () => Query[];\n};\n\ntype Entry = (\n | InsertEntry\n | UpdateEntry\n | DeleteEntry\n | AllEntry\n | SkippingEntry\n | EitherEntry\n | LinkEntry\n | UnlinkEntry\n | NoneEntry\n | ReadEntry\n) & {\n tk?(sent: Sent[], queries?: Query[]): void;\n at?: number;\n rt?: boolean;\n};\n\ninterface Step {\n w(): Statement[] | Promise<Statement[]>;\n t?(sent: Sent[]): void;\n a?: number;\n r?: boolean;\n wr?: boolean;\n c?: boolean;\n}\n\ninterface Answer {\n readonly q: Question;\n readonly r: Input[];\n}\n\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\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[] = [];\nconst STILL: Step = { w: () => [] };\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 op: SqlOperationContext;\n readonly w: Writer;\n readonly wt: WriteWatch | undefined;\n readonly #schema: EngineSchema;\n readonly #transport: Transport;\n #answers: Map<string, Answer> | undefined;\n #concrete: Set<string> | undefined;\n #copies: Map<string, unknown> | undefined;\n #sent = 0;\n #delivered = 0;\n #heard: Map<number, Sent[]> | undefined;\n #asserted: Set<string> | undefined;\n sg = 0;\n sd = false;\n #members!: number[];\n #raw: WeakMap<Input, Input> | undefined;\n #meta: WeakMap<Row, Meta> | undefined;\n #known: Map<string, Row> | undefined;\n #log!: Entry[];\n #missed: Map<string, [Question | undefined, number]> | undefined;\n #outcomes: Map<number, boolean> | undefined;\n #attempting: number | undefined;\n #presumed: Map<string, [Question, Row | undefined, number]> | undefined;\n #used: Map<Answer, number> | undefined;\n #stale!: Map<AnyModel, Set<string> | true>;\n #touched!: Set<AnyModel | string>;\n #again!: boolean;\n #waited: Pending | undefined;\n #made!: number;\n #handed = false;\n #left: Set<string> | undefined;\n #says!: ((failure: unknown) => unknown)[];\n #absences!: [\n AnyModel,\n NonNullable<ReturnType<Writer[\"selector\"]>[\"uniqueKey\"]>,\n ][];\n\n constructor(operation: SqlOperationContext, transport: Transport) {\n this.op = operation;\n this.#schema = operation.schema;\n this.#transport = transport;\n this.w = new (operation.backend?.writer ?? Writer)(\n operation,\n transport.holds ? (sql, model) => this.#hear({ sql, model }) : undefined\n );\n this.wt = writeSinks.get(operation.attribution)?.attempt();\n }\n\n #hear = async (statement: Statement): Promise<Input[]> =>\n (await this.#transport.send([statement], false))[0]!.rows;\n\n #pend(row: Row, field: string, spell?: () => unknown, named = false) {\n return new Pending(\n row,\n field,\n `@${++this.#made}`,\n this.#log.length,\n spell,\n named\n );\n }\n\n #putKnown(name: string, row: Row) {\n (this.#known ??= new Map()).set(name, row);\n }\n\n #putMeta(row: Row, meta: Meta) {\n (this.#meta ??= new WeakMap()).set(row, meta);\n }\n\n #markConcrete(id: string) {\n (this.#concrete ??= new Set()).add(id);\n }\n\n #fail(stops: PreparedGuardFailure, model: AnyModel) {\n return createFailureError(stops, nameOf(model), this.op.operation);\n }\n\n #reset() {\n this.#meta =\n this.#known =\n this.#missed =\n this.#presumed =\n this.#used =\n this.#left =\n undefined;\n this.#log = [];\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 }\n\n #settle<T>(work: () => () => T): (() => T) | undefined {\n for (;;) {\n this.#reset();\n let answer: (() => T) | undefined;\n let refused: { e: unknown } | undefined;\n try {\n answer = work();\n } catch (e) {\n refused = { e };\n }\n if (this.#again) continue;\n if (this.#missed?.size) return;\n if (refused) throw refused.e;\n return answer!;\n }\n }\n\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 async run<T>(work: () => () => T): Promise<T> {\n for (let races = 0; ; ) {\n try {\n const answer = this.#settle(work) ?? (await this.#learnt(work));\n const [only] = this.#log;\n if (\n only &&\n this.#log.length === 1 &&\n (only.k === \"a\" || only.k === \"s\" || only.k === \"e\") &&\n only.at === undefined &&\n !(this.#presumed?.size || this.#used?.size || this.#sent)\n ) {\n const whole = this.#whole(only);\n const sent = await this.#transport.send(\n whole instanceof Promise ? await whole : whole,\n true\n );\n this.sd = true;\n this.#sent = 1;\n if (this.#transport.loose && hasWritten(sent)) this.sg++;\n only.tk?.(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 if (!believed || this.#delivered > 0) throw this.#fail(stops!, model);\n if (believed === \"presumed\")\n for (const id of this.#presumed?.keys() ?? []) this.#markConcrete(id);\n else if (++races > 3)\n throw new NotFoundError(nameOf(model), this.op.operation);\n else this.#answers = undefined;\n this.#asserted = this.#outcomes = undefined;\n this.#sent = 0;\n }\n }\n }\n\n async pr<T>(work: () => () => T) {\n this.#handed = true;\n const answer = this.#settle(work) ?? (await this.#learnt(work));\n const written: [Statement[], Step][] = [];\n try {\n for (const step of this.#steps(this.#log.length))\n written.push([await step.w(), step]);\n } catch (error) {\n throw error === UNHEARD ? SEVERAL : error;\n }\n return {\n statements: written.flatMap(([s]) => s),\n answer: (sent: readonly Sent[]) => {\n let at = 0;\n for (const [statements, step] of written) {\n step.t?.(sent.slice(at, at + statements.length));\n at += statements.length;\n }\n return answer();\n },\n };\n }\n\n async #learn(): Promise<void> {\n const missed = [...(this.#missed?.values() ?? [])];\n const afterAt = Math.min(...missed.map(([, a]) => a));\n if (\n this.#handed &&\n missed.some(\n ([q, a]) => a > 0 || !q?.unique || q.must || q.through || q.member\n )\n )\n throw SEVERAL;\n const steps = afterAt > this.#sent ? this.#steps(afterAt) : [];\n const groups = new Map<string, [string, Question][]>();\n const pins = (q: Question) =>\n q.unique && !(q.member || q.limit)\n ? this.w.selector(q).uniqueValues\n : undefined;\n const group = (q: Question) =>\n pins(q) &&\n text([nameOf(q.model), q.through?.name, q.intent, q.writes, q.makes]);\n for (const [id, [q, a]] of this.#missed ?? []) {\n if (a !== afterAt || !q) continue;\n pushTo(groups, group(q) || id, [id, q]);\n }\n for (const [id, [q, row]] of this.#presumed ?? []) {\n const together = row && groups.get(group(q) || \"\");\n if (together) together.push([id, q]);\n }\n for (const asked of groups.values()) {\n const [[, first]] = asked as [[string, Question]];\n const { model } = first;\n let query: Query;\n let found: [string, Question, Input[]][] | undefined;\n const take = ([sent]: Sent[]) => {\n const rows = this.op.queries.decodeQuery(query, sent!.rows);\n const raw = (this.#raw ??= new WeakMap());\n for (const [at, row] of rows.entries()) raw.set(row, sent!.rows[at]!);\n const before = found;\n found = asked.map(([id, q]) => [\n id,\n q,\n asked.length === 1\n ? rows\n : rows.filter((row) =>\n [...pins(q)!].every(([field, value]) => same(row[field], value))\n ),\n ]);\n const answers = (this.#answers ??= new Map());\n for (const [id, q, r] of found) answers.set(id, { q, r });\n return before;\n };\n const loose =\n this.#transport.holds &&\n first.makes === true &&\n this.w.adapter.capabilities.locksMissingKeys === true;\n steps.push({\n w: () => {\n query = this.w.read(\n asked.map(([, q]) => this.#asked(q)),\n this.#transport.holds && !loose\n );\n return [{ sql: query.sql, model }];\n },\n t: take,\n });\n if (loose)\n steps.push({\n w: () => {\n if (!found) throw UNHEARD;\n const again = found\n .filter(([, , rows]) => rows.length > 0)\n .map(([, q, rows]) => ({\n ...this.#asked(q),\n only: rows.map((row) => this.#schema.identity(model, row)),\n again: true,\n }));\n if (again.length === 0) return [];\n query = this.w.read(again, true);\n return [{ sql: query.sql, model }];\n },\n t: (sent) => {\n if (sent.length === 0) return;\n const before = take(sent)!;\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\n #name(model: AnyModel, values: Input): string {\n const keys = this.#schema.keys(model);\n if (keys.length === 0) return `${nameOf(model)}#${++this.#made}`;\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\n #of({ edge, of }: NonNullable<Question[\"member\"]>): Input {\n return pick(\n of,\n new Set([\n ...(edge.kind === \"reference\" ? [] : this.#schema.keys(edge.source)),\n ...hopFieldsOf(edge),\n ])\n );\n }\n\n #about(row: Row) {\n return this.#meta?.get(row) as Meta;\n }\n\n #absent(question: Question, lost?: boolean) {\n return this.#fail(this.w.abs(question, lost), question.model);\n }\n\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\n #key(row: Row): Input {\n return this.#schema.identity(this.#about(row).m, row);\n }\n\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.r[value.f] : value;\n if (said instanceof Pending) {\n if (!said.n && (this.#transport.holds || !said.s)) {\n this.#waited = said;\n throw UNHEARD;\n }\n heard[field] = said.s!();\n } else if (said !== undefined) heard[field] = said;\n }\n return heard;\n }\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.g) return false;\n const { member } = question;\n const selector = this.w.selector(question);\n const { facts } = selector;\n const name = this.#name(meta.m, row);\n if (question.except?.some((key) => this.#name(meta.m, key) === name))\n return false;\n const rewritten =\n meta.w !== undefined &&\n [...meta.w].some((field) => facts.fields.has(field));\n let unsure = false;\n for (const [field, value] of facts.equals) {\n if (!hasOwn(row, field) || row[field] instanceof Pending) continue;\n const holds = this.op.queries.tld(meta.m, field, row[field], value);\n if (holds === false) return false;\n unsure ||= holds === undefined;\n }\n if (member?.edge.kind === \"reference\") {\n const { discriminator, pairs } = member.edge;\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 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 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 if (\n facts.exact &&\n !(selector.scoped || unsure) &&\n [...facts.equals.keys()].every((field) => field in row)\n )\n return true;\n if (was && !meta.c && facts.reads.size === 0 && !rewritten) return true;\n return undefined;\n }\n\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.k !== \"l\" && entry.k !== \"x\") || entry.e.table !== edge.table)\n continue;\n const [a, b] = entry.e.source === edge.source ? [from, to] : [to, from];\n const side = entry.e.uniqueSide;\n if (entry.k === \"l\") {\n if (entry.f === a && entry.t === b) linked = true;\n else if (side === \"source\" ? entry.f === a : side && entry.t === b)\n linked = false;\n } else if (\n entry.f === a &&\n (entry.t === b || !(entry.t || entry.kp.includes(b)))\n )\n linked = false;\n }\n return linked;\n }\n\n #presume(id: string, question: Question): Row[] | undefined {\n const schema = this.#schema;\n const { model } = question;\n const pins = this.w.selector(question).uniqueValues;\n const keys = schema.keys(model);\n if (!(question.must && question.unique && pins) || this.#concrete?.has(id))\n return undefined;\n const named = !keys.every((field) => pins.has(field));\n if (\n named &&\n (question.member ||\n question.through ||\n !this.w.adapter.capabilities.supportsMutationTargetInSubquery)\n )\n return undefined;\n const key = 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)?.p\n ) {\n this.#markConcrete(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] = this.#pend(\n partial,\n field,\n () => this.w.loc(question, field),\n true\n );\n this.#putKnown(name, row);\n this.#putMeta(row, {\n m: model,\n q: question,\n p: true,\n n: named ? id : undefined,\n });\n }\n (this.#presumed ??= new Map()).set(id, [question, row, this.#log.length]);\n return [row];\n }\n\n #recalled(question: Question): Row[] | boolean {\n const { uniqueValues, facts } = this.w.selector(question);\n const pins =\n uniqueValues ??\n (this.#schema.keys(question.model).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).m !== 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\n #changed(row: Row): boolean {\n const meta = this.#about(row);\n return Boolean(meta.c || meta.g || meta.w);\n }\n\n #spoiled(question: Question): boolean {\n const { model, member } = question;\n if (member && this.#meta?.get(member.of)?.v) return true;\n const stale = this.#stale.get(model);\n if (stale === true) return true;\n const { facts } = this.w.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 [...facts.reads].some(\n (read) => this.#touched.has(read) || this.#stale.has(read as AnyModel)\n )\n );\n }\n\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\n rd(question: Question, fields: readonly string[]): boolean {\n const { facts } = this.w.selector(question);\n return fields.some((field) => facts.fields.has(field));\n }\n\n rs(question: Question): Row[] {\n this.wr(question);\n const { member } = question;\n const stood = member && this.#meta?.get(member.of)?.s;\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\n #rows(question: Question, late: boolean): Row[] {\n const { model, member } = question;\n if (this.#left?.size && question.unique) {\n const pins = this.w.selector(question).uniqueValues;\n const name =\n pins &&\n this.#schema.keys(model).every((field) => pins.has(field)) &&\n this.#name(model, fromEntries(pins));\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)?.c;\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 && !linksReady(member)) return [];\n const afterAt = 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 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 afterAt,\n question.joined && 1,\n ]);\n const use = (ans: Answer) =>\n (this.#used ??= new Map()).set(ans, this.#log.length);\n const answer =\n fresh && !late ? { q: question, r: [] } : this.#answers?.get(id);\n if (!answer) {\n const recalled = !late && this.#recalled(question);\n if (recalled === true) return this.#rows(question, true);\n const read = isArr(recalled)\n ? recalled.filter((row) => !this.#changed(row))\n : [];\n if (read.length > 0) use({ q: question, r: read });\n const known = recalled || (!late && this.#presume(id, question));\n if (known) return known;\n (this.#missed ??= new Map()).set(id, [\n member\n ? { ...question, member: { ...member, of: this.#of(member) } }\n : question,\n afterAt,\n ]);\n return [];\n }\n if (!(fresh || this.#used?.has(answer))) use(answer);\n const raw = (this.#raw ??= new WeakMap());\n const read = new Set(\n answer.r.map((values) => {\n const key = this.#name(model, values);\n let row = this.#known?.get(key);\n if (!row) {\n row = { ...values };\n this.#putKnown(key, row);\n this.#putMeta(row, { m: model, q: question });\n }\n const meta = this.#about(row);\n raw.set(row, raw.get(values)!);\n if (meta.p) {\n Object.assign(row, { ...values, ...row });\n meta.p = undefined;\n }\n if (late) Object.assign(row, values);\n return row;\n })\n );\n const rows = [...read];\n if (late) return rows;\n for (const row of this.#known?.values() ?? []) {\n if (this.#about(row).m !== 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 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\n kp(model: AnyModel): boolean {\n return this.w.mks(model) !== undefined;\n }\n\n o(question: Question): Row {\n const missed = this.#missed?.size ?? 0;\n const [row] = this.rs({ ...question, must: true });\n if (!row && (this.#missed?.size ?? 0) > missed) {\n const unknown: Row = {};\n this.#putMeta(unknown, { m: question.model, q: question });\n return unknown;\n }\n if (!row) throw this.#absent(question);\n return row;\n }\n\n vl(\n model: AnyModel,\n kind: \"create\" | \"update\",\n admitted: Input,\n raw: Input = {}\n ): Input {\n return this.w.values(model, kind, admitted, raw);\n }\n\n #note(entry: Entry): void {\n entry.at = this.#attempting;\n if (entry.k === \"i\" || entry.k === \"u\" || entry.k === \"d\")\n this.#touched.add(this.#about(entry.r).m);\n else if (entry.k === \"s\") this.#touched.add(entry.m);\n else if (entry.k === \"l\" || entry.k === \"x\")\n this.#touched.add(entry.e.table);\n const place = this.#log.push(entry) - 1;\n const heard = this.#heard?.get(place);\n if (heard) entry.tk?.(heard);\n }\n\n ins(\n model: AnyModel,\n admitted: Input,\n raw?: Input,\n relation?: string,\n takes?: Input\n ): Row {\n const row: Row = this.w.values(model, \"create\", admitted, raw, takes);\n if (takes) Object.assign(row, takes);\n let computed: Input | undefined;\n for (const field in row)\n if (row[field] instanceof InsertValue)\n (computed ??= {})[field] = row[field];\n let decided = NONE;\n for (const field of decidable(this.#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) row[field] = this.#pend(row, field);\n const name = this.#name(model, row);\n if (!this.#known?.has(name)) this.#putKnown(name, row);\n const meta: Meta = { m: model, c: true, a: this.#log.length, b: computed };\n this.#putMeta(row, meta);\n this.#note({\n k: \"i\",\n r: row,\n l: relation,\n d: decided,\n tk: ([sent]) => {\n meta.i = sent!.rowCount;\n const [rawRow] = sent!.rows;\n const [said] =\n rawRow && decided.every((field) => field in rawRow)\n ? this.w.tld(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 #seen(row: Row, kind: WriteKind): void {\n const { m } = this.#about(row);\n const name = nameOf(m);\n const { wt } = this;\n if (!wt?.wants(name, kind)) return;\n const q = this.op.queries;\n const projection = q.prepareProjection(m, {});\n this.r(row, projection, (rows) =>\n wt.shows(name, kind, q.decodeProjection(projection.shape, rows))\n );\n }\n\n #writing(row: Row, write: Partial<Question>): Question {\n const { m, q } = this.#about(row);\n return {\n model: m,\n where: q?.where,\n member: q?.member,\n through: q?.through,\n verb: q?.verb,\n ...write,\n };\n }\n\n #cascades(model: AnyModel): void {\n for (const other of dependentsOf(this.#schema, model)) this.#spoil(other);\n }\n\n #follow(row: Row, before: Row): void {\n const schema = this.#schema;\n const { m } = this.#about(row);\n for (const edge of holders(schema, m)) {\n if (\n edge.reference?.onUpdate !== \"cascade\" ||\n edge.pairs.every(\n (pair) =>\n !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.m !== edge.target ||\n !edge.pairs.every(\n (pair) =>\n 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.w ??= new Set()).add(pair.target);\n }\n if (schema.keys(meta.m).some((key) => was[key] !== child[key])) {\n this.#putKnown(this.#name(meta.m, child), child);\n meta.v = true;\n }\n this.#follow(child, was);\n }\n }\n }\n\n u(\n row: Row,\n set: Input,\n writes?: readonly string[],\n joined?: Membership,\n removes = false,\n of?: Row\n ): void {\n const setKeys = objKeys(set);\n if (setKeys.length === 0) return;\n const meta = this.#about(row);\n const model = meta.m;\n const key = this.#key(row);\n const keys = this.#schema.keys(model);\n if (\n meta.n !== undefined &&\n setKeys.some(\n (field) =>\n keys.includes(field) ||\n this.w.selector(meta.q!).uniqueValues?.has(field)\n )\n ) {\n this.#markConcrete(meta.n);\n this.#again = true;\n }\n const hears: string[] = [];\n const before = { ...row };\n let computed = false;\n const q = this.op.queries;\n for (const field of setKeys) {\n const value = set[field];\n const update =\n value instanceof Pending\n ? { kind: \"value\" as const, value }\n : readUpdate(value);\n (meta.w ??= new Set()).add(field);\n const made = meta.a ?? Number.POSITIVE_INFINITY;\n const later =\n (update.kind === \"value\" &&\n update.value instanceof Pending &&\n update.value.a > made) ||\n (of !== undefined && (this.#meta?.get(of)?.a ?? -1) > made);\n if (update.kind !== \"value\" || later) {\n const stood = row[field];\n if (\n meta.c &&\n !(\n (meta.b && field in meta.b) ||\n (stood instanceof Pending && stood.r === row)\n )\n )\n (meta.b ??= {})[field] = stood;\n computed = true;\n }\n if (update.kind === \"value\") row[field] = update.value;\n else {\n const stood = row[field];\n row[field] = this.#pend(\n row,\n field,\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 let keyMoved = false;\n let keyChanged = false;\n for (const field of keys)\n if (field in set) {\n keyMoved = true;\n if (row[field] instanceof Pending || !same(row[field], before[field]))\n keyChanged = true;\n }\n if (keyChanged) meta.s ??= before;\n if (keyMoved) {\n (this.#left ??= new Set()).add(this.#name(model, before));\n this.#putKnown(this.#name(model, row), row);\n meta.v = true;\n this.#cascades(model);\n }\n this.#follow(row, before);\n if (meta.c && !computed) return;\n this.#note({\n k: \"u\",\n r: row,\n y: key,\n s: set,\n h: hears,\n q: this.#writing(\n row,\n joined\n ? { intent: \"join\", through: joined }\n : removes\n ? { intent: \"delete\" }\n : { intent: \"update\", writes }\n ),\n tk: ([sent]) => {\n if (hears.length === 0) return;\n const [said] = this.w.keys(model, sent!.rows);\n if (!said) throw this.#absent(meta.q ?? { model });\n for (const field of hears) row[field] = said[field];\n },\n });\n if (meta.q?.verb) this.#seen(row, \"update\");\n }\n\n #markDeleted(row: Row, marks: Input): void {\n this.u(row, marks, undefined, undefined, true);\n this.#about(row).g = true;\n }\n\n d(row: Row): void {\n const meta = this.#about(row);\n const { m: model, q: question } = meta;\n const marks = this.w.mks(model);\n if (question?.verb && !marks) this.#seen(row, \"delete\");\n if (marks) {\n const stops = this.w.restr(model);\n const through = question?.member;\n if (stops)\n this.n(\n {\n model,\n where: this.#key(row),\n unique: true,\n intent: \"delete\",\n referenced: this.w.refd(through, through && this.#key(through.of)),\n },\n stops\n );\n this.#markDeleted(row, marks);\n return;\n }\n meta.g = true;\n const made = this.#log.findIndex(\n (entry) => entry.k === \"i\" && entry.r === row\n );\n if (made >= this.#sent) {\n this.#log.splice(made, 1);\n return;\n }\n this.#note({\n k: \"d\",\n r: row,\n y: this.#key(row),\n q: this.#writing(row, { intent: \"delete\" }),\n });\n this.#cascades(model);\n }\n\n a(question: Question, set?: Input, projection?: PreparedProjection): Later {\n const { model, member } = question;\n if (member) linksReady(member);\n const q = this.op.queries;\n const name = nameOf(model);\n const kind = set ? \"update\" : \"delete\";\n const watched =\n question.verb && this.wt?.wants(name, kind)\n ? q.prepareProjection(model, {})\n : undefined;\n const returns = projection ?? watched;\n const marks = set ? undefined : this.w.mks(model);\n const stops = marks && this.w.restr(model);\n const later: Later = {};\n const referenced =\n stops && this.w.refd(member, member && this.#key(member.of));\n const held =\n stops && !(this.#handed || member || question.limit !== undefined);\n const noStmt = (k: \"update\" | \"delete\", s?: Input) =>\n Boolean(returns && !this.op.answersInStatement(model, returns, k, s));\n if (\n marks ? watched || (stops && !(this.#handed || held)) : noStmt(kind, set)\n ) {\n const joined =\n set &&\n Object.values(set).find(\n (value): value is JoinedValue => value instanceof JoinedValue\n );\n const rows = this.rs(joined ? { ...question, joined } : question);\n const take = (read: Input[]) => {\n later.s = { rows: read, rowCount: read.length };\n };\n const answer = () =>\n projection\n ? this.sr(model, rows, projection, \"updateMany\", take)\n : take(rows);\n if (!(set || marks)) answer();\n if (stops && rows.length > 0)\n this.n(\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) this.#markDeleted(row, marks);\n else if (set)\n this.u(\n row,\n set,\n question.writes,\n undefined,\n question.intent === \"delete\"\n );\n else this.d(row);\n if (set || marks) answer();\n return later;\n }\n if (marks) {\n if (\n held &&\n this.#transport.holds &&\n this.w.adapter.capabilities.supportsRowLocks &&\n !noStmt(\"update\", marks)\n )\n this.#note({\n k: \"r\",\n m: model,\n rs: [],\n qs: () => [\n this.op.scope!.rows.tombstones!.lock(\n q,\n this.w.selector({ ...question, intent: \"delete\" })\n ),\n ],\n });\n if (stops)\n this.n(\n { ...question, must: undefined, intent: \"delete\", referenced },\n stops\n );\n return this.a(question, marks, projection);\n }\n this.wr(question);\n if (question.must && this.#handed)\n (this.#presumed ??= new Map()).set(`a:${this.#log.length}`, [\n question,\n undefined,\n this.#log.length,\n ]);\n this.#note({\n k: \"a\",\n q: question,\n s: set,\n p: returns,\n tk: ([sent]) => {\n later.s = sent;\n if (watched)\n this.wt!.shows(\n name,\n kind,\n q.decodeProjection(watched.shape, sent!.rows)\n );\n },\n });\n this.#spoil(model, set && objKeys(set));\n if (!set) this.#cascades(model);\n return later;\n }\n\n e(\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.op.queries;\n const { capabilities } = this.w.adapter;\n const selector = this.w.selector(question);\n const pins = selector.uniqueValues;\n const row = this.vl(model, \"create\", admitted, raw);\n const fields = objKeys(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.#schema.keys(model).some((key) => key in set) ||\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.op.answersInStatement(model, projection, \"update\", set)\n )\n return undefined;\n const later: Later = {};\n const name = nameOf(model);\n const asked =\n this.wt?.wants(name, \"create\") || this.wt?.wants(name, \"update\");\n const marker =\n asked && returningSafeProjection(projection)\n ? this.w.adapter.mutations.upserted\n : undefined;\n let created: boolean | undefined;\n if (asked && !marker)\n this.#note({\n k: \"r\",\n m: model,\n rs: [],\n qs: () => [this.w.read([question], false)],\n tk: ([sent]) => {\n created = sent!.rows.length === 0;\n },\n });\n this.#note({\n k: \"e\",\n q: question,\n r: row,\n s: set,\n p: projection,\n mk: marker,\n tk: ([sent]) => {\n later.s = sent;\n for (const said of marker ? sent!.rows : []) {\n created = said.__viborm_inserted === true;\n said.__viborm_inserted = undefined;\n }\n later.c = created;\n },\n });\n this.#spoil(model);\n return later;\n }\n\n l(edge: Junction, from: Row, to: Row, through?: Input): void {\n const source = endOf(edge.sourceSide, from);\n const target = endOf(edge.targetSide, to);\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 if (\n a !== undefined &&\n b !== undefined &&\n !(a instanceof Pending || b instanceof Pending) &&\n !same(a, b)\n )\n throw new NestedWriteError(\n `Cannot link '${edge.name}': rows disagree on '${pair.junctionField}'.`,\n edge.name,\n { meta: { field: pair.junctionField, relation: edge.name } }\n );\n }\n this.#note({\n k: \"l\",\n e: edge,\n f: from,\n t: to,\n ks: [source, target],\n th: through,\n });\n }\n\n ul(edge: Junction, from: Row, to?: Row, kept: readonly Row[] = []): void {\n this.#note({\n k: \"x\",\n e: edge,\n f: from,\n t: to,\n kp: kept,\n ks: [\n endOf(edge.sourceSide, from),\n to && endOf(edge.targetSide, to),\n kept.map((row) => endOf(edge.targetSide, row)),\n ],\n });\n }\n\n wr(question: Question): void {\n if (question.strict && this.w.jdg(question))\n this.#note({ k: \"n\", q: question });\n }\n\n n(question: Question, stops: PreparedGuardFailure): void {\n if (question.member) linksReady(question.member);\n this.#note({ k: \"n\", q: question, st: stops });\n }\n\n ab(question: Question): void {\n if (!this.#transport.holds) this.#note({ k: \"n\", q: question, b: true });\n }\n\n r(\n row: Row,\n projection: PreparedProjection,\n take: (rows: Input[]) => void\n ): void {\n const { m } = this.#about(row);\n const said = this.#told([row], projection);\n if (said) {\n take(said);\n return;\n }\n this.#note({\n k: \"r\",\n m,\n rs: [row],\n p: projection,\n qs: () => [this.w.one(m, this.#said(this.#key(row)), projection)],\n tk: ([sent]) => take(sent!.rows),\n });\n }\n\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((entry) => entry.k === \"r\" || entry.k === \"n\") &&\n projection.fields.every((field) => field.kind === \"scalar\")\n ? (said as Input[])\n : undefined;\n }\n\n sr(\n model: AnyModel,\n rows: readonly Row[],\n projection: PreparedProjection,\n kind: \"createMany\" | \"updateMany\",\n take: (rows: Input[]) => void\n ): void {\n const there = rows.filter((row) => !this.#about(row).x);\n const said = this.#told(there, projection);\n if (said) {\n take(said);\n return;\n }\n this.#note({\n k: \"r\",\n m: model,\n rs: there,\n p: projection,\n qs: () =>\n this.op.seriesQueries(\n projection,\n there.map((row) => this.#said(this.#key(row))),\n kind\n ),\n tk: (sent, queries) => {\n for (const [at, query] of (queries ?? []).entries()) {\n const expected = query.expectedRows;\n if (!expected || sent[at]!.rows.length >= expected.count) continue;\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.w.abs(question),\n believed: \"presumed\",\n });\n throw expected.missing;\n }\n take(sent.flatMap((each) => each.rows));\n },\n });\n }\n\n sy(say: (failure: unknown) => unknown): void {\n this.#says.push(say);\n }\n\n cr(question: Question): void {\n const key = this.w.selector(question).uniqueKey;\n if (key) this.#absences.push([question.model, key]);\n }\n\n rc(failure: unknown): boolean {\n return (\n failure instanceof UniqueConstraintError &&\n this.#absences.some(([model, key]) =>\n this.w.refusedFor(model, key, failure)\n )\n );\n }\n\n mb(): void {\n this.#members.push(this.#log.length);\n }\n\n mbs(series = false): number {\n if (series && this.#members.length === 0) return 0;\n return [...this.#members.slice(1), this.#log.length].filter(\n (end) => end <= this.#sent\n ).length;\n }\n\n ats(rows: string): void {\n if (this.#handed) throw SEVERAL;\n if (!this.#transport.attempt)\n throw new UnsupportedOperationError(\n `skipDuplicates on ${rows} requires a savepoint on '${this.op.driver.driverName}'.`,\n { meta: { operation: this.op.operation } }\n );\n }\n\n at(work: () => Row, rows: string): boolean {\n this.ats(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((entry) => entry.k === \"i\" && entry.r === made);\n if (root) root.rt = true;\n const written = this.#outcomes?.get(from);\n if (written === undefined) {\n (this.#missed ??= new Map()).set(`at:${from}`, [\n undefined,\n this.#log.length,\n ]);\n return true;\n }\n if (!written)\n for (const entry of part) {\n if (entry.k !== \"i\") continue;\n const meta = this.#about(entry.r);\n meta.g = true;\n meta.x = true;\n const name = this.#name(meta.m, entry.r);\n if (this.#known?.get(name) === entry.r) this.#known?.delete(name);\n }\n return written;\n }\n\n wn(rows: readonly Row[]): number {\n let count = 0;\n for (const row of rows) count += this.#meta?.get(row)?.i ?? 0;\n return count;\n }\n\n get hd(): boolean {\n return this.#handed;\n }\n\n sk(\n model: AnyModel,\n rows: readonly (readonly [Input, Input, Input?])[],\n projection?: PreparedProjection,\n passes = true\n ): Later | undefined {\n if (\n (passes && this.w.adapter.mutations.skipDuplicatesStrategy !== \"sql\") ||\n (projection && !this.op.answersInStatement(model, projection, \"insert\"))\n )\n return undefined;\n const later: Later = {};\n this.#note({\n k: \"s\",\n m: model,\n rs: rows.map(([admitted, raw, takes]) =>\n Object.assign(\n this.w.values(model, \"create\", admitted, raw, takes),\n takes\n )\n ),\n p: projection,\n ps: passes,\n tk: (sent) => {\n const said = sent.flatMap((each) => each.rows);\n later.s = {\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\n cp<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 #steps(to: number): Step[] {\n const { w, op } = this;\n const schema = this.#schema;\n const { holds } = this.#transport;\n const sentFrom = this.#sent;\n const said = (values: Input) => this.#said(values);\n const about = (row: Row) => this.#about(row);\n const steps: Step[] = [];\n let current: Entry | undefined;\n const push = (step: Step) => {\n if (current) {\n step.a = current.at;\n step.r = current.rt;\n step.wr = current.k !== \"r\";\n }\n steps.push(step);\n };\n const log = this.#log;\n const last = to === log.length;\n let scratch: [string, AnyModel] | undefined;\n const span = log.slice(sentFrom, to);\n const needed = new Map<Row, number>();\n const needs = (values: readonly (Input | undefined)[], ownRow?: Row) => {\n const rows = new Set<Row>();\n for (const each of values)\n if (each)\n for (const field in each) {\n const value = each[field];\n if (value instanceof Pending && value.r !== ownRow)\n rows.add(value.r);\n }\n for (const row of rows) needed.set(row, (needed.get(row) ?? 0) + 1);\n };\n const wanted = (row: Row) =>\n (needed.get(row) ?? 0) >\n +Object.values(this.#key(row)).some((value) => value instanceof Pending);\n let writes = 0;\n for (let at = sentFrom; at < log.length; at++) {\n const e = log[at]!;\n const { k } = e;\n if (at < to && k !== \"n\" && k !== \"r\") writes++;\n if (k === \"i\") needs([e.r], e.r);\n else if (k === \"u\") needs([e.y, e.s]);\n else if (k === \"d\") needs([e.y]);\n else if (k === \"l\" || k === \"x\") needs(e.ks.flat());\n else if (k === \"r\") needs(e.rs.map((row) => this.#key(row)));\n }\n const passed = (row: Row | undefined) =>\n sentFrom > 0 && row && this.#changed(row);\n const confirms = new Map<Entry, Question>();\n const asked = new Map<string, [Question, (Input | Input[])?][]>();\n const ask = (\n q: Question,\n ownId: string,\n believed: \"presumed\" | \"read\",\n key?: Input | Input[],\n place?: number,\n held = holds || q.intent === \"join\"\n ) => {\n const group = text([\n believed,\n nameOf(q.model),\n q.member ? ownId : q.through?.name,\n q.verb,\n q.intent,\n q.writes,\n place,\n held,\n ]);\n let together = asked.get(group);\n if (!together) {\n together = [];\n asked.set(group, together);\n push({\n w: () => [\n w.asks(\n together!.map(([each, k]) => [this.#asked(each), k]),\n believed,\n holds,\n held\n ),\n ],\n });\n }\n together.push([q, key]);\n };\n const firsts = new Map<Row, Entry>();\n for (const e of log) if (\"r\" in e && !firsts.has(e.r)) firsts.set(e.r, e);\n const later: [number, () => void][] = [];\n const made = (q: Question, at: number) => {\n const m = q.member;\n return (\n m !== undefined &&\n log\n .slice(sentFrom, at)\n .some((e) =>\n \"r\" in e\n ? e.r === m.of\n : e.k === \"l\" &&\n m.edge.kind === \"junction\" &&\n e.e.table === m.edge.table\n )\n );\n };\n const taken = [...(this.#presumed ?? [])].filter(\n ([id, [, row, at]]) =>\n !(at > to || (holds ? this.#asserted?.has(id) : passed(row)))\n );\n const mayConfirm = holds || !(this.#handed || writes > 1);\n const says = taken.map(([, [, row]]) => {\n if (!mayConfirm) return undefined;\n const first = span.find(\n (e) =>\n ((e.k === \"u\" || e.k === \"d\") && e.r === row) ||\n (e.k === \"x\" && e.t === row)\n );\n return first &&\n first.k !== \"x\" &&\n w.cnts(first.k === \"u\" ? \"update\" : \"delete\")\n ? first\n : undefined;\n });\n for (\n let place = says.length, wasAsked = false, held = false;\n place-- > 0;\n ) {\n if (wasAsked && (held || says[place] !== log[sentFrom]))\n says[place] = undefined;\n const { through } = taken[place]![1][0];\n wasAsked ||= !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, [q, , at]]] of taken.entries()) {\n (this.#asserted ??= new Set()).add(id);\n const first = says[place];\n if (first) {\n confirms.set(first, q);\n behind = sentFrom + 1;\n continue;\n }\n const from = Math.max(made(q, at) ? at : 0, behind);\n if (from > 0)\n later.push([from, () => ask(q, id, \"presumed\", undefined, from)]);\n else ask(q, id, \"presumed\");\n }\n const under = (\n e: UpdateEntry | DeleteEntry,\n run: readonly (UpdateEntry | DeleteEntry)[] = [e]\n ) => ({\n ...this.#asked({ ...e.q, member: confirms.get(e)?.member }),\n through: e.q.member?.edge ?? e.q.through,\n again:\n !holds &&\n run.every(\n (each) =>\n each.q.where === e.q.where &&\n firsts.get(each.r) === each &&\n !this.#meta?.get(each.r)?.c\n ),\n });\n const consumed = (q: Question, rows: number, sent: Sent | undefined) => {\n if (q.again && sent && w.cnt(sent) < rows)\n throw new TransactionError(\n `${q.verb ?? op.operation} row count changed.`,\n {\n meta: { model: op.modelName, operation: op.operation },\n }\n );\n };\n const unkeyed = (e: Entry) =>\n \"r\" in e && this.#meta?.get(e.r)?.n !== undefined;\n const keyed = (run: readonly (UpdateEntry | DeleteEntry)[]) =>\n unkeyed(run[0]!) ? undefined : run.map((next) => said(next.y));\n const own = new Map<Entry, [ReadEntry, number]>();\n const told = new Set<Entry>();\n const spare = new Map<Entry, ReadEntry>();\n const spared = new Map<Entry, Sent>();\n const sizes = new Map<Entry, number>();\n const mates = (e: Entry, next: Entry) => {\n const a = confirms.get(e);\n const b = confirms.get(next);\n return (\n Boolean(a) === Boolean(b) &&\n a?.member?.of === b?.member?.of &&\n a?.member?.edge === b?.member?.edge &&\n !(own.has(next) || spare.has(next) || spare.has(e)) &&\n !(unkeyed(e) || unkeyed(next))\n );\n };\n const confirmed = (e: Entry, sent: Sent) => {\n const q = confirms.get(e);\n if (q && w.cnt(sent) < (sizes.get(e) ?? 1)) throw this.#absent(q);\n };\n for (let place = sentFrom; place < to; place++) {\n const read = log[place]!;\n if (!(read.k === \"r\" && read.p && read.rs.length === 1)) continue;\n const [row] = read.rs;\n const model = read.m;\n let changed = false;\n for (let at = place - 1; at >= sentFrom; at--) {\n const e = log[at]!;\n if ((e.k === \"i\" || e.k === \"u\") && e.r === row) {\n if (\n !(own.has(e) || spare.has(e)) &&\n (at === place - 1 || returningSafeProjection(read.p)) &&\n (e.k === \"i\" || e.h.length === 0) &&\n op.answersInStatement(\n model,\n read.p,\n e.k === \"i\" ? \"insert\" : \"update\",\n e.k === \"u\" ? e.s : undefined\n )\n ) {\n if (changed) {\n if (e.k === \"u\") spare.set(e, read);\n } else {\n own.set(e, [read, place]);\n told.add(read);\n }\n }\n break;\n }\n const touched =\n e.k === \"a\" || e.k === \"e\"\n ? e.q.model\n : e.k === \"d\" || e.k === \"u\"\n ? about(e.r).m\n : undefined;\n if (\n touched === model ||\n (touched && dependentsOf(schema, touched).has(model))\n )\n changed = true;\n }\n }\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?.k === \"r\" &&\n next.p &&\n next.rs.length === rows.length &&\n next.rs.every((row, place) => row === rows[place]) &&\n op.answersInStatement(next.m, next.p, effect)\n ? next\n : undefined;\n };\n for (const [answer, at] of this.#used ?? []) {\n if (holds) continue;\n const { model, where } = answer.q;\n const rowOf = (values: Input) =>\n this.#known?.get(this.#name(model, values));\n const keys = (at > to ? [] : answer.r)\n .filter((values) => !passed(rowOf(values)))\n .map((values) =>\n pick(\n values,\n new Set([\n ...schema.keys(model),\n ...getModelKeyCatalog(model)\n .referenceableKeys.flat()\n .filter((field) => (values[field] ?? null) !== null),\n ])\n )\n );\n if (keys.length === 0) continue;\n const key = keys.length === 1 ? keys[0] : keys;\n const held = !(\n writes === answer.r.length &&\n answer.r.every((values) => {\n const first = firsts.get(rowOf(values) as Row);\n return (first?.k === \"u\" || first?.k === \"d\") && span.includes(first);\n })\n );\n if (made(answer.q, at))\n later.push([\n at,\n () => ask(answer.q, text(where), \"read\", key, at, held),\n ]);\n else ask(answer.q, text(where), \"read\", key, undefined, held);\n }\n const settled = (row: Row): Input => {\n const computes = about(row).b;\n const values: Input = {};\n for (const field in row) {\n const value = computes?.[field] ?? row[field];\n if (\n value !== undefined &&\n !(value instanceof Pending && value.r === row)\n )\n values[field] = value;\n }\n return values;\n };\n later.sort(([a], [b]) => a - b);\n for (let at = sentFrom; 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 const beside = <T extends Entry>(\n sameEntry: (next: T) => boolean\n ): T[] => {\n const run = [entry as T];\n while (\n at + 1 < to &&\n log[at + 1]!.at === entry.at &&\n !(later.length > 0 && later[0]![0] <= at + 1) &&\n sameEntry(log[at + 1] as T)\n )\n run.push(log[++at] as T);\n return run;\n };\n const hearAt = (from: number, sent: Sent[]) => {\n (this.#heard ??= new Map()).set(from, sent);\n confirmed(entry, sent[0]!);\n };\n const take = (sent: Sent[], queries?: Query[]) => {\n hearAt(place, sent);\n entry.tk?.(sent, queries);\n };\n const tells =\n (read: Entry | undefined, from: number) => (sent: Sent[]) => {\n hearAt(from, sent);\n read?.tk?.(sent);\n };\n if (entry.k === \"i\") {\n const model = about(entry.r).m;\n const decided = entry.d;\n const columns = objKeys(settled(entry.r));\n const fits = (rows: Row[], next: Entry | undefined) =>\n next?.k === \"i\" &&\n about(next.r).m === model &&\n next.l === entry.l &&\n w.bsd(model, columns, rows.length, settled(next.r));\n let rows = [entry.r];\n const mine = own.get(entry);\n let end = at + 1;\n while (!mine && end < to && fits(rows, log[end]))\n rows.push((log[end++] as InsertEntry).r);\n let read = mine?.[0] ?? answered(end, rows, \"insert\");\n const both = Boolean(mine) && wanted(entry.r);\n if (mine && both && !(holds && returningSafeProjection(mine[0].p!))) {\n told.delete(mine[0]);\n read = undefined;\n } else if (mine) rows = [entry.r];\n else if (read && !rows.some(wanted)) at = end;\n else {\n read = undefined;\n rows = [entry.r];\n beside<InsertEntry>((next) => {\n const joins =\n fits(rows, next) &&\n !(needed.has(entry.r) || needed.has(next.r) || own.has(next));\n if (joins) rows.push(next.r);\n return joins;\n });\n }\n const hears = (both || !read) && needed.has(entry.r);\n if (hears && decided.length > 1 && !w.sy)\n throw new Error(\"Generated values need RETURNING or one increment.\");\n if (hears && last && !holds) scratch ??= [crypto.randomUUID(), model];\n push({\n w: async () => {\n const insert = (returns?: PreparedProjection) =>\n w.insert(\n model,\n rows.map((row) => said(settled(row))),\n entry.l,\n returns,\n read && hears ? decided : undefined,\n entry.rt && w.passes\n );\n const kept =\n scratch &&\n hears &&\n !read &&\n w.kpt(scratch[0], `${place}`, decided, await insert());\n if (!kept)\n return [\n await insert(\n read?.p ?? (hears ? w.fields(model, decided) : undefined)\n ),\n ];\n entry.r[decided[0]!] = kept.value;\n return kept.statements;\n },\n t: (sent) => {\n if (entry.rt && w.passes && sent[0]!.rows.length === 0)\n throw PASSED;\n take(sent);\n if (read) tells(read, mine?.[1] ?? at)(sent);\n },\n });\n } else if (entry.k === \"u\") {\n const { model } = entry.q;\n const hears = entry.h;\n const fields = objKeys(entry.s);\n const run = hears.length\n ? [entry]\n : beside<UpdateEntry>(\n (next) =>\n next.k === \"u\" &&\n next.q.model === model &&\n objKeys(next.s).length === fields.length &&\n fields.every((field) =>\n Object.is(next.s[field], entry.s[field])\n ) &&\n next.q.intent === entry.q.intent &&\n next.q.through === entry.q.through &&\n next.q.verb === entry.q.verb &&\n mates(entry, next)\n );\n if (run.length > 1) sizes.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)![0]);\n const read = mine?.[0];\n const kept = hears.length === 0 ? spare.get(entry) : undefined;\n let askedComp = false;\n let named: Question | undefined;\n push({\n c: confirms.has(entry),\n w: async () => {\n const set = said(entry.s);\n const first =\n hears.length > 0 && w.cmp(under(entry), said(entry.y), set);\n askedComp = Boolean(first);\n named = under(entry, run);\n const stmt = await w.update(\n named,\n set,\n keyed(run),\n read?.p ??\n kept?.p ??\n (hears.length > 0 && !first ? w.key(model) : undefined),\n confirms.has(entry) || named.again\n );\n return first ? [first, stmt] : [stmt];\n },\n t: read\n ? tells(read, mine![1])\n : (sent) => {\n if (kept) spared.set(kept, sent.at(-1)!);\n take(askedComp ? sent.slice(0, 1) : sent);\n if (w.cnts(\"update\")) consumed(named!, run.length, sent.at(-1));\n },\n });\n } else if (entry.k === \"d\") {\n const { model } = entry.q;\n const run = beside<DeleteEntry>(\n (next) =>\n next.k === \"d\" && next.q.model === model && mates(entry, next)\n );\n if (run.length > 1) sizes.set(entry, run.length);\n const named = under(entry, run);\n push({\n c: confirms.has(entry),\n w: () => [\n w.remove(\n named,\n keyed(run),\n undefined,\n confirms.has(entry) || named.again\n ),\n ],\n t: (sent) => {\n take(sent);\n consumed(named, run.length, sent[0]);\n },\n });\n } else if (entry.k === \"a\" || entry.k === \"s\" || entry.k === \"e\")\n push({ w: () => this.#whole(entry), t: take });\n else if (entry.k === \"l\") {\n const plain = (l: LinkEntry) =>\n !(l.th || l.e.declared || l.e.uniqueSide);\n const run = beside<LinkEntry>(\n (next) =>\n next.k === \"l\" && next.e === entry.e && plain(entry) && plain(next)\n );\n push({\n w: () =>\n w.link(\n entry.e,\n run.map((next) => [said(next.ks[0]), said(next.ks[1])] as const),\n entry.th\n ),\n });\n } else if (entry.k === \"x\")\n push({\n w: () => [\n w.unlink(\n entry.e,\n said(entry.ks[0]),\n entry.ks[1] && said(entry.ks[1]),\n entry.ks[2].map(said)\n ),\n ],\n });\n else if (entry.k === \"n\")\n push({\n w: () => [\n {\n ...w.none(this.#asked(entry.q), entry.st),\n ...(entry.b && { believed: \"read\" as const }),\n },\n ],\n });\n else if (!told.has(entry)) {\n const removal = log[at + 1];\n if (\n at + 1 < to &&\n removal?.k === \"d\" &&\n answered(at, [removal.r], \"delete\")\n ) {\n at++;\n push({\n w: () => [w.remove(under(removal), [said(removal.y)], entry.p)],\n t: (sent) => {\n confirmed(removal, sent[0]!);\n take(sent);\n },\n });\n continue;\n }\n let queries: Query[];\n push({\n w: () => {\n queries = entry.qs();\n return queries.map((query) => ({ sql: query.sql, model: entry.m }));\n },\n t: (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 for (const [, run] of later) run();\n if (scratch) {\n const { open, close } = w.scr(scratch[0], scratch[1]);\n steps.unshift({ w: () => open });\n steps.push({ w: () => [close] });\n }\n this.#sent = Math.max(sentFrom, to);\n return steps;\n }\n\n #whole(\n entry: AllEntry | SkippingEntry | EitherEntry\n ): Statement[] | Promise<Statement[]> {\n const { w } = this;\n if (entry.k === \"a\")\n return oneStatement(\n entry.s\n ? w.update(\n this.#asked(entry.q),\n this.#said(entry.s),\n undefined,\n entry.p\n )\n : w.remove(this.#asked(entry.q), undefined, entry.p)\n );\n if (entry.k === \"e\")\n return oneStatement(\n w.either(\n entry.q,\n this.#said(entry.r),\n this.#said(entry.s),\n entry.p,\n entry.mk\n )\n );\n const chunks: Input[][] = [];\n let columns: string[] = [];\n for (const row of entry.rs) {\n const chunk = chunks.at(-1);\n if (chunk && w.bsd(entry.m, columns, chunk.length, row)) chunk.push(row);\n else {\n chunks.push([row]);\n columns = objKeys(row);\n }\n }\n const written = chunks.map((chunk) =>\n w.insert(\n entry.m,\n chunk.map((row) => this.#said(row)),\n undefined,\n entry.p,\n undefined,\n entry.ps\n )\n );\n return written.some((s) => s instanceof Promise)\n ? Promise.all(written)\n : (written as Statement[]);\n }\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: [Statement[], Step][] = [];\n const flush = async (end: boolean) => {\n const told = waiting;\n waiting = [];\n const one = told.length === 1;\n const statements = one ? told[0]![0] : told.flatMap(([s]) => s);\n const sent = statements.length > 0 ? await send(statements, end) : [];\n this.sd ||= end && !within;\n let at = 0;\n const parts = told.map(([own]) =>\n one ? sent : sent.slice(at, (at += own.length))\n );\n if (\n !within &&\n this.#transport.loose &&\n told.some(([, step], place) => step.wr && hasWritten(parts[place]!))\n )\n this.sg++;\n for (let place = 0; place < told.length; place++)\n told[place]![1].t?.(parts[place]!);\n };\n const outer = this.#hear;\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 if (!within && step.a !== undefined) {\n await flush(false);\n const part = [step];\n while (steps[at + 1]?.a === step.a) part.push(steps[++at]!);\n const written = await this.#attempted(part);\n (this.#outcomes ??= new Map()).set(step.a, written);\n continue;\n }\n let statements: Statement[];\n try {\n statements = await step.w();\n } catch (error) {\n if (error !== UNHEARD) throw error;\n await flush(false);\n const waited = this.#waited;\n this.#waited = undefined;\n if (waited && !(within || this.#transport.holds))\n waiting.push([\n [\n this.w.stl(this.#about(waited.r).m, {\n ...this.#key(waited.r),\n [waited.f]: waited.r[waited.f],\n }),\n ],\n STILL,\n ]);\n statements = await step.w();\n }\n waiting.push([statements, step]);\n if (within ? step.r && this.w.passes : this.#transport.holds && step.c)\n await flush(last && at === steps.length - 1);\n }\n await flush(last);\n } finally {\n this.#hear = outer;\n }\n }\n\n async #attempted(part: Step[]): Promise<boolean> {\n let first: Statement | undefined;\n const told = part.map((step) =>\n step.r\n ? {\n ...step,\n w: async () => {\n const statements = await step.w();\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: written as if the store were the database itself.\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 { type PreparedProjection, 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 {\n engineFault,\n fromEntries,\n isArr,\n isObj,\n nameOf,\n objEntries,\n objKeys,\n same,\n unsupported,\n} from \"../shared/terms\";\nimport type { Question } from \"./statements\";\nimport { type Later, type Row, type Store, text } from \"./store\";\n\nconst plainObject = (value: unknown): value is Input => {\n if (!isObj(value)) return false;\n const kind = Object.getPrototypeOf(value);\n return kind === Object.prototype || kind === null;\n};\n\nconst list = (value: unknown): unknown[] =>\n value === undefined || value === false ? [] : isArr(value) ? value : [value];\n\nconst joinQ = (\n edge: Membership,\n where: Input,\n verb: string,\n makes?: boolean\n): Question => ({\n model: edge.target,\n where,\n unique: true,\n through: edge,\n intent: \"join\",\n verb,\n ...(makes && { makes }),\n});\n\nconst depends = (\n operation: string,\n relation: string,\n earlier: string,\n kind: \"membership\" | \"target\"\n): never => {\n throw new NestedWriteError(\n `Nested '${operation}' on '${relation}' depends on '${earlier}' (${kind}).`,\n relation,\n { meta: { operation, conflictsWith: earlier } }\n );\n};\n\nconst moves = (held: unknown, written: unknown): boolean => {\n if (written === undefined) return false;\n if (!isObj(written)) return !same(written, held);\n const { set, increment, decrement, multiply, divide } = written;\n if (set !== undefined) return !same(set, held);\n return !(\n Number(increment ?? 0) === 0 &&\n Number(decrement ?? 0) === 0 &&\n Number(multiply ?? 1) === 1 &&\n Number(divide ?? 1) === 1\n );\n};\n\nconst holds = (edge: Membership) =>\n edge.kind === \"reference\" && edge.owner === \"source\";\n\nconst cleared = (edge: Membership): Input =>\n fromEntries(\n (edge.clearability as { fields?: string[] }).fields!.map((field) => [\n field,\n null,\n ])\n );\n\nconst within = (parent: Row, edge: Membership, where?: unknown) => ({\n model: edge.target,\n where: where as Input | undefined,\n member: { edge, of: parent },\n});\n\nconst computedKey = (source: string, edge: Membership) =>\n new NestedWriteError(\n `Non-literal key '${source}' update during '${edge.name}'.`,\n edge.name,\n { meta: { operation: \"update\", field: source, relation: edge.name } }\n );\n\ntype RelEntry = [name: string, edge: Membership, payload: Input];\n\nexport class Verbs {\n readonly #store: Store;\n readonly #operation;\n readonly #schema;\n readonly #q;\n readonly #said = new WeakMap<object, unknown>();\n #made: WeakMap<Row, boolean> | undefined;\n #several = 1;\n #slots: WeakMap<Row, Map<string, [string, string]>> | undefined;\n\n constructor(store: Store) {\n this.#store = store;\n this.#operation = store.op;\n this.#schema = this.#operation.schema;\n this.#q = this.#operation.queries;\n }\n\n #createNested(\n parent: Row,\n edge: Membership,\n data: Input,\n arm = false,\n through = data.$through as Input\n ) {\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\") this.#store.l(edge, parent, row, through);\n }\n\n /** Nested verbs for to-many relations, in execution order (disconnect/delete first, then slice(2)). */\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.#memberOne(parent, edge, where, \"join\", \"disconnect\")\n );\n },\n delete(parent, edge, where) {\n const row = this.#memberOne(parent, edge, where, \"delete\", \"delete\");\n if (\n edge.kind === \"junction\" &&\n (edge.targetSide.onDelete ?? \"cascade\") !== \"cascade\" &&\n !this.#store.w.mks(edge.target)\n )\n this.#store.ul(edge, parent, row);\n this.#store.d(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.#updateSet(edge.target, values);\n if (this.#plain(edge.target, values, set))\n this.#store.a({ ...within(parent, edge, where), ...ask }, set);\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 at === 0\n ? values\n : this.#copyUpdate(\n edge.target,\n `${edge.name} ${Object.values(this.#schema.identity(edge.target, row)).join()}`,\n this.#stated(values)\n )\n );\n this.#several = outer;\n }\n },\n deleteMany(parent, edge, where) {\n this.#store.a({\n ...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.#memberOne(\n parent,\n edge,\n where,\n \"update\",\n \"update\",\n this.#writes(edge.target, values)\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 const [found] = this.#store.rs({\n ...named,\n through: edge,\n makes: true,\n });\n if (!found) this.#createNested(parent, edge, create as Input, true);\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.l(edge, parent, found);\n } else {\n const row = this.#store.o({ ...named, member: { edge, of: parent } });\n if (objKeys(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 = joinQ(edge, where as Input, \"connectOrCreate\", true);\n const [row] = this.#store.rs(asked);\n if (row)\n this.#join(parent, edge, row, \"connectOrCreate\", $through as Input);\n else {\n this.#markMissing(asked, create as Input);\n this.#createNested(\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.o(joinQ(edge, where, \"connect\")),\n \"connect\",\n $through as Input\n );\n },\n create(parent, edge, data, arm, through) {\n this.#createNested(parent, edge, data, arm, through);\n },\n createMany(parent, edge, { data, skipDuplicates }) {\n const rows = list(data) as Input[];\n if (!skipDuplicates) {\n for (const entry of rows) this.#createNested(parent, edge, entry);\n return;\n }\n const bare = (row: Input) =>\n this.#relationsOf(edge.target, row).length === 0;\n this.#store.ats(\"nested createMany rows\");\n if (\n edge.kind === \"reference\" &&\n rows.every(bare) &&\n this.#store.sk(\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.at(\n () =>\n (made = this.#make(\n edge.target,\n row,\n this.#born(parent, edge),\n edge.name\n )),\n \"nested createMany rows\"\n );\n if (edge.kind !== \"junction\") continue;\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.rs({\n model: edge.target,\n where: named,\n through: edge,\n intent: \"join\",\n verb: \"createMany\",\n })[0];\n if (member) this.#store.l(edge, parent, member, row.$through as Input);\n }\n },\n };\n\n #memberOne(\n parent: Row,\n edge: Membership,\n where: unknown,\n intent: \"join\" | \"delete\" | \"update\",\n verb: string,\n writes?: readonly string[]\n ): Row {\n return this.#store.o({\n ...within(parent, edge, where),\n unique: true,\n intent,\n verb,\n ...(writes && { writes }),\n });\n }\n\n #updateSet(model: AnyModel, data: Input): Input {\n return this.#store.vl(model, \"update\", data, this.#stated(data));\n }\n\n #paired<T>(admitted: T, raw: unknown): T {\n if (isArr(admitted)) {\n this.#said.set(admitted, raw);\n for (let at = 0; at < admitted.length; at++) {\n const child = admitted[at];\n if (!isObj(child)) continue;\n const next = (raw as unknown[] | undefined)?.[at];\n this.#paired(child, next === undefined && at === 0 ? raw : next);\n }\n } else if (plainObject(admitted)) {\n this.#said.set(admitted, raw);\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 (!isObj(child)) 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 #copyUpdate(model: AnyModel, key: string, raw: Input): Input {\n return this.#store.cp(key, () =>\n this.#paired(\n parseStamped(this.#operation.scope?.rows.stamps ?? new Map(), () =>\n this.#schema.update(model, raw)\n ),\n raw\n )\n );\n }\n\n #markMissing(asked: Question, create: Input): void {\n if (this.#keyed(asked, create)) this.#store.cr(asked);\n else this.#store.ab(asked);\n }\n\n #decode(shape: PreparedProjection[\"shape\"], rows: Input[]): Input[] {\n return this.#q.decodeResult(rows, this.#operation.operation, (raw) =>\n this.#q.decodeProjection(shape, raw)\n );\n }\n\n #stated(admitted: Input): Input {\n return (this.#said.get(admitted) ?? {}) as Input;\n }\n\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 objEntries(takes)) {\n const written = own[field];\n if (written === undefined) continue;\n const plain = isObj(written) && \"set\" in written ? written.set : 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 '${objKeys(takes).join(\", \")}'; omit from nested data.`\n : `${kind} conflicts on '${this.#q.columnName(model, field)}' via '${relation}'.`\n );\n }\n return takes;\n }\n\n #spelled(model: AnyModel, own: Input): Input | undefined {\n const whole = (fields: readonly string[]) =>\n fields.every((field) => (own[field] ?? null) !== null)\n ? 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 #relationsOf(model: AnyModel, data: Input): RelEntry[] {\n return model[\"~\"].relationNames.some((name) => data[name] !== undefined)\n ? this.#relationsIn(model, data)\n : [];\n }\n\n #relationsIn(model: AnyModel, data: Input): RelEntry[] {\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 const arms: [string | undefined, Input][] =\n \"members\" in resolved.edge && !resolved.member\n ? resolved.edge.members.map(({ variant }) => [\n variant,\n fromEntries(\n objEntries(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 return verb === \"create\"\n ? named.data\n : named.data || named.create\n ? named\n : 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]) => objKeys(mine).length > 0)\n .map(\n ([variant, mine]): RelEntry => [\n name,\n this.#schema.membership(model, name, variant),\n mine,\n ]\n );\n });\n }\n\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 fromEntries([\n ...(discriminator?.side === held\n ? [[discriminator.field, discriminator.value]]\n : []),\n ...edge.pairs.map((pair) => {\n const field = pair[referenced];\n if (this.#made?.get(row) === true && (row[field] ?? null) === null)\n unsupported(`Create '${edge.name}' needs parent '${field}'.`);\n if (row[field] === null)\n throw new NestedWriteError(\n `Cannot connect '${edge.name}': target '${field}' is null.`,\n edge.name\n );\n return [pair[held], row[field]];\n }),\n ]);\n }\n\n #born(parent: Row, edge: Membership): Input {\n return this.#referencing(edge, parent, \"target\");\n }\n\n #reaching(edge: Membership, row: Row): Input {\n return this.#referencing(edge, row, \"source\");\n }\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.cp(`moved ${nameOf(model)}`, () =>\n this.#schema.update(model, {})\n )\n ),\n ...takes,\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.rs({ ...within(parent, edge, where), ...ask });\n }\n\n #keyed(question: Question, data: Input): boolean {\n const { uniqueKey, uniqueValues } = this.#store.w.selector(question);\n return (\n uniqueKey?.fields.every((field) => {\n const proposed = data[field];\n return (\n proposed !== undefined && same(proposed, uniqueValues?.get(field))\n );\n }) === true\n );\n }\n\n #writes(model: AnyModel, data: Input, set?: Input): string[] | undefined {\n const own = this.#stated(data);\n const fields = objKeys(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 objKeys(payload).some(\n (verb) =>\n payload[verb] !== undefined &&\n verb !== \"update\" &&\n (holds(edge) || (edge.kind === \"junction\" && verb !== \"updateMany\"))\n )\n ? [\n name,\n ...(edge.kind === \"reference\" &&\n holds(edge) &&\n !edge.discriminator\n ? edge.pairs.map((pair) => pair.source)\n : []),\n ]\n : []\n );\n const written =\n objKeys(set ?? this.#store.vl(model, \"update\", data, own)).length > 0;\n return written || relations.length > 0\n ? [...fields, ...relations]\n : undefined;\n }\n\n #join(\n parent: Row,\n edge: Membership,\n row: Row,\n verb: string,\n through?: Input\n ) {\n if (\n this.#several > 1 &&\n (edge.kind === \"reference\" || edge.uniqueSide === \"target\")\n )\n unsupported(\n `updateMany (${this.#several}) cannot '${verb}' '${edge.name.split(\".\")[0]}': single parent only.`\n );\n if (edge.kind === \"junction\") {\n this.#store.l(edge, parent, row, through);\n return;\n }\n const takes = this.#born(parent, edge);\n const mine = this.#slots?.get(row);\n for (const field of objKeys(takes)) {\n const by = mine?.get(field);\n if (by) depends(by[1], by[0], verb, \"membership\");\n }\n this.#store.u(\n row,\n this.#moved(row, edge, takes),\n undefined,\n edge,\n false,\n parent\n );\n }\n\n #leave(parent: Row, edge: Membership, row: Row) {\n return edge.kind === \"junction\"\n ? this.#store.ul(edge, parent, edge.many ? row : undefined)\n : this.#store.u(\n row,\n this.#moved(row, edge, 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 if (relations.length === 0 && relation === undefined) {\n const row = this.#store.ins(\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 const held = relations\n .filter(([, edge]) => holds(edge))\n .map(([, edge, payload]): [Membership, Input, (() => void)[]] => [\n edge,\n ...this.#single(undefined, model, edge, payload, said),\n ]);\n const takes = Object.assign(\n {},\n relation === undefined\n ? given\n : this.#once(\"create\", model, said, given, relation, true),\n ...held.map(([edge, ownTakes]) =>\n this.#once(\"create\", model, given, ownTakes, edge.name)\n )\n );\n const row = this.#store.ins(\n model,\n data,\n this.#stated(data),\n relation,\n takes\n );\n (this.#made ??= new WeakMap()).set(row, !arm);\n this.#after(\n row,\n model,\n relations,\n held.map(([, , then]) => then),\n said\n );\n return row;\n }\n\n #after(\n row: Row,\n model: AnyModel,\n relations: readonly RelEntry[],\n held: readonly (() => void)[][],\n said: Input\n ) {\n for (const listFn of held) for (const next of listFn) next();\n for (const [, edge, payload] of relations)\n if (!holds(edge))\n if (edge.many) this.#relate(row, edge, payload);\n else this.#single(row, model, edge, payload, said);\n }\n\n #write(\n model: AnyModel,\n row: Row,\n data: Input,\n portable = true,\n given?: Input,\n relation?: string\n ): void {\n const s = this.#store;\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 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 s.n(\n {\n model: edge.target,\n member: {\n edge,\n of: {\n ...row,\n ...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 '${edge.name}' (onUpdate '${edge.reference.onUpdate ?? \"restrict\"}') while occupied.`,\n raceable: false,\n }\n );\n };\n const keys = this.#schema.keys(model);\n for (const [, edge] of relations) {\n if (edge.kind !== \"reference\" || edge.owner !== \"target\") continue;\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 computedKey(source, edge);\n const moved = edge.pairs.filter((pair) =>\n moves(row[pair.source], said[pair.source])\n );\n for (const { source } of moved)\n if (!moves(null, said[source]))\n throw new NestedWriteError(\n `Cannot null key '${source}' during '${edge.name}'.`,\n edge.name,\n { meta: { operation: \"update\", field: source } }\n );\n if (moved.length > 0) vacant(edge);\n }\n const own = relations.filter(([, edge]) => 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 objKeys(singles[at]![0]))\n fields.set(field, [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(([ownTakes], at) =>\n given\n ? this.#once(\"update\", model, given, ownTakes, own[at]![1].name)\n : ownTakes\n )\n );\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 ((isObj(next) && !(next instanceof Date)) ||\n moves(row[pair.source], next))\n );\n })\n )\n vacant(edge);\n const decided = fromEntries(\n own.flatMap(([, edge]) =>\n (edge as Extract<Membership, { kind: \"reference\" }>).pairs.map(\n (pair) => [pair.source, true]\n )\n )\n );\n s.u(\n row,\n {\n ...s.vl(model, \"update\", data, {\n ...decided,\n ...this.#stated(data),\n ...takes,\n }),\n ...takes,\n },\n this.#writes(model, data)\n );\n this.#after(\n row,\n model,\n relations,\n singles.map(([, then]) => then),\n said\n );\n }\n\n #single(\n row: Row | undefined,\n model: AnyModel,\n edge: Membership,\n payload: Input,\n said: Input\n ): [Input, (() => void)[]] {\n const s = this.#store;\n const held = holds(edge);\n const then: (() => void)[] = [];\n const { target } = edge;\n const kind = row ? \"update\" : \"create\";\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 const final =\n held && edge.kind === \"reference\"\n ? edge.pairs.filter((pair) => said[pair.source] !== undefined)\n : [];\n const stated = (field: string) => readUpdate(said[field]);\n for (const { source } of final)\n if (stated(source).kind !== \"value\") throw computedKey(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 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 if (disconnect === true && held) take(cleared(edge));\n else if (disconnect) {\n const old = current({ intent: \"join\", verb: \"disconnect\" }, disconnect);\n if (old) held ? take(cleared(edge)) : this.#leave(row!, edge, old);\n }\n const isRef = edge.kind === \"reference\";\n const pairHas = (fn: \"every\" | \"some\") =>\n held &&\n isRef &&\n of &&\n edge.pairs[fn]((pair) => (of[pair.source] ?? null) !== null);\n const remove = first(\"delete\");\n if (remove && held && first(\"connect\"))\n depends(\"connect\", edge.name, \"delete\", \"target\");\n const removal = { intent: \"delete\", verb: \"delete\" } as const;\n const old =\n remove &&\n (pairHas(\"every\")\n ? s.o({\n ...within(of!, edge, remove === true ? undefined : remove),\n ...removal,\n })\n : current(removal, remove));\n if (old) {\n if (held) {\n if (!s.kp(target)) take(cleared(edge));\n then.push(() => s.d(old));\n } else s.d(old);\n } else if (remove === true && pairHas(\"some\")) take(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\") s.l(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 let supplied: Row | undefined;\n const created = first(\"create\");\n if (created) supplied = create(created, false);\n const connected = first(\"connect\");\n if (connected) {\n const { $through, ...where } = connected as Input;\n const question = joinQ(edge, where, \"connect\");\n const found = s.o(question);\n if (found === row && s.rd(question, objKeys(said)))\n depends(\"connect\", edge.name, \"update\", \"target\");\n supplied = adopt(found, \"connect\", $through as Input | undefined);\n }\n const either = first(\"connectOrCreate\") as Input | undefined;\n if (either) {\n const asked = joinQ(edge, either.where as Input, \"connectOrCreate\", true);\n const [found] = s.rs(asked);\n const through = either.$through as Input | undefined;\n if (!found) this.#markMissing(asked, either.create as Input);\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 then.push(() =>\n this.#write(\n target,\n supplied && !update.where\n ? supplied\n : s.o({\n ...within(of!, edge, update.where),\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, []];\n }\n\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.o(joinQ(edge, where, \"set\"));\n });\n const others: Question = {\n ...within(parent, edge),\n except: kept.map((row) => this.#schema.identity(edge.target, row)),\n intent: \"join\",\n verb: \"set\",\n strict: `Cannot disconnect '${edge.name}'.`,\n };\n if (edge.kind === \"junction\") {\n this.#store.wr(others);\n this.#store.ul(edge, parent, undefined, kept);\n } else if (edge.clearability.kind === \"none\") {\n if (this.#store.rs(others).length > 0)\n throw new NestedWriteError(\n `Cannot set '${edge.name}': required FK ${sideFields(edge, \"target\").join(\", \")} cannot be cleared.`,\n edge.name\n );\n } else this.#store.a(others, 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 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 objKeys(Verbs.#nested).slice(2)) {\n const entries = list(payload[verb]) as Input[];\n const once =\n verb === \"connect\"\n ? new Map(\n entries.map((entry) => {\n const { $through: _, ...where } = entry;\n return [text(where), entry];\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(\n model: AnyModel,\n args: Arguments,\n kinds: WriteKind[]\n ): [PreparedProjection, (rows: Input[], kind?: WriteKind) => unknown] {\n const shows = this.#store.wt?.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.#decode(projection.shape, rows);\n return (shows?.cut(read, kind) ?? read)[0];\n };\n return [projection, said];\n }\n\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.r(row, projection, (rows) => {\n value = said(rows);\n });\n return () => value;\n }\n\n #plain(model: AnyModel, data: Input, set: Input) {\n return (\n this.#relationsOf(model, data).length === 0 &&\n objKeys(set).length > 0 &&\n !this.#schema.keys(model).some((key) => set[key] !== undefined)\n );\n }\n\n #removes(model: AnyModel): WriteKind {\n return this.#operation.scope?.rows.tombstones?.has(nameOf(model))\n ? \"update\"\n : \"delete\";\n }\n\n #many(model: AnyModel, args: Arguments, kind: WriteKind) {\n const select = args.select as Input | undefined;\n const shows = this.#store.wt?.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.#decode(projection!.shape, rows);\n if (!shows) return read;\n shows.cut(read, kind);\n return select ? read : { count: read.length };\n };\n const again = (rows: Row[], verb: \"createMany\" | \"updateMany\") => {\n const returned: Input[] = [];\n if (projection && rows.length > 0)\n this.#store.sr(model, rows, projection, verb, (read) =>\n returned.push(...read)\n );\n return () =>\n projection\n ? decoded(returned)\n : {\n count: verb === \"createMany\" ? this.#store.wn(rows) : rows.length,\n };\n };\n const count = (later: Later) => () =>\n projection\n ? decoded(later.s!.rows)\n : { count: this.#store.w.cnt(later.s!) };\n return [\n projection,\n decoded,\n again,\n () => (select ? [] : { count: 0 }),\n count,\n ] as const;\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 const later =\n this.#relationsOf(model, data).length === 0 &&\n this.#store.sk(model, [[data, this.#stated(data)]], shown[0], false);\n if (later) return () => shown[1](later.s!.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 if (entries.length === 0 && this.#store.hd)\n engineFault(\"No data for createMany.\");\n const bearing = entries.some(\n (data) => this.#relationsOf(model, data).length > 0\n );\n const later = bearing\n ? undefined\n : this.#store.sk(\n model,\n entries.map((data) => [data, this.#stated(data)]),\n projection,\n args.skipDuplicates === true\n );\n if (later) {\n if (!args.skipDuplicates) for (const _ of entries) this.#store.mb();\n return () =>\n projection ? decoded(later.s!.rows) : { count: later.s!.rowCount };\n }\n if (args.skipDuplicates) {\n const rows: Row[] = [];\n for (const data of entries)\n this.#store.at(\n () => {\n const row = this.#make(model, data, {});\n rows.push(row);\n return row;\n },\n bearing ? \"nested writes\" : \"duplicate rows\"\n );\n return again(rows, \"createMany\");\n }\n return again(\n entries.map((data) => {\n this.#store.mb();\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.#updateSet(model, 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.a({ ...question, must: true }, set, projection);\n return () => said(later.s!.rows);\n }\n const row = this.#store.o(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 s = this.#store;\n const data = this.#paired(args.data as Input, raw.data);\n const [projection, , again, none, count] = 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.#updateSet(model, 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]) => holds(edge));\n if (this.#plain(model, data, set))\n return count(s.a(question, set, projection));\n const rows = s.rs(question);\n this.#several = rows.length;\n if (beside) for (const row of rows) s.u(row, set, question.writes);\n for (const [at, row] of rows.entries()) {\n s.mb();\n const own =\n at === 0 ? data : this.#copyUpdate(model, `${at}`, raw.data as Input);\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 s = this.#store;\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 const hasUpdate = objKeys(this.#stated(update)).length > 0;\n if (related + guards.length === 0 && hasUpdate) {\n const [projection, said] = this.#one(model, args, [\"create\", \"update\"]);\n const later = s.e(\n question,\n create,\n this.#stated(create),\n this.#updateSet(model, update),\n projection\n );\n if (later)\n return () => said(later.s!.rows, later.c ? \"create\" : \"update\");\n }\n const [found] = s.rs({ ...question, makes: true });\n const where = args.where as Input;\n const asked = {\n ...question,\n where: { ...where, AND: [...list(where.AND), ...guards] },\n };\n const matched = !found || guards.length === 0 || s.rs(asked).length > 0;\n if (!matched) s.ab(asked);\n const keyed = !found && this.#keyed(question, create);\n if (keyed) s.cr(question);\n const key = keyed ? s.w.selector(question).uniqueKey : undefined;\n const refuses =\n key && this.#operation.queries.domain?.judge?.located(model);\n if (refuses)\n s.sy((failure) =>\n failure instanceof UniqueConstraintError &&\n s.w.refusedFor(model, key, failure)\n ? refuses(failure)\n : failure\n );\n const updates = found && matched && hasUpdate;\n if (updates) this.#write(model, found, update, followed.length > 0);\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.a(\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.s!.rows);\n }\n\n deleteMany(model: AnyModel, args: Arguments) {\n const [projection, , , none, count] = this.#many(\n model,\n args,\n this.#removes(model)\n );\n if (args.limit === 0) return none;\n return count(\n this.#store.a(\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 );\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.op.operation as \"create\"](model, args, raw as Input);\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.f : error;\n if (\n again ||\n !(failure !== error || store.rc(error)) ||\n store.sg > 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.sg > 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.sd ? \"result\" : \"member\",\n committedSegments: store.sg,\n // Of a unit that may have been made, nothing is known to be.\n completedMembers: made ? store.mbs(true) : 0,\n committedWriteMembers: made ? store.mbs() : 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.sg > 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.wt?.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.pr(\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 result for '${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.wt?.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 {\n adapterPinnedTable,\n sharedAdapterFor,\n} 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 memo,\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 this.#queries\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 let binding: ExecutionBinding | undefined;\n if (driverOverride)\n binding = {\n driver: driverOverride,\n kind: \"borrowed-transaction\",\n writeOutcome,\n };\n else if (engineDriver === this.#config.driver)\n binding = writeOutcome && { kind: \"standalone\", writeOutcome };\n else {\n const region: MemberRollback = (execute, scoped) =>\n engineDriver.withTransaction(execute, undefined, scoped);\n binding = {\n driver: engineDriver,\n kind: \"borrowed-transaction\",\n memberRollback: region,\n operationRegion: region,\n writeOutcome,\n };\n }\n return this.execute(binding, execution.context);\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.pubPrep(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 */\ntype SharedEngine = readonly [\n EngineSchema,\n WeakMap<object, [WeakMap<object, Queries>, Queries?]>,\n];\nconst sharedEngines = new WeakMap<object, SharedEngine>();\n\nfunction sharedQueries(config: EngineConfig): Queries {\n const { adapter, result, backend } = config.driver;\n const queryAdapter = backend ? adapter : sharedAdapterFor(adapter);\n const make = (schema: EngineSchema): Queries =>\n new (backend ? engineBackend(backend).queries : SqlQueries)(\n schema,\n queryAdapter,\n result\n );\n const key = config.resolved?.registry;\n const fresh = (): SharedEngine => [\n new EngineSchema(config.schema, config.resolved),\n new WeakMap(),\n ];\n const [schema, byAdapter] = key ? memo(sharedEngines, key, fresh) : fresh();\n const byResult = memo(\n byAdapter,\n queryAdapter,\n (): [WeakMap<object, Queries>, Queries?] => [new WeakMap()]\n );\n return result\n ? memo(byResult[0], result, () => make(schema))\n : (byResult[1] ??= make(schema));\n}\n\nexport type CommandEngine = ReturnType<typeof createCommandEngine>;\n\nexport function createCommandEngine(config: EngineConfig) {\n const queries = sharedQueries(config);\n memo(renderers, config.schema, () => new WeakMap()).set(\n config.driver.adapter,\n queries\n );\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 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(\"$rows() requires a namespace.\");\n const scope = rows?.prepare(queries, instant);\n scope?.domain.project?.refuseGatedRows(model);\n return ((scope ? scope.domain.reads(scope) : queries) as SqlQueries).rowsOf(\n model,\n alias\n );\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' field '${key}.${field}' is not a readable scalar.`,\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 findFirstOrThrow findMany findUnique findUniqueOrThrow create update upsert delete\".split(\n \" \"\n )\n);\n\nexport const applyClientOmit = (\n model: AnyModel,\n operation: Operations | string,\n args: Record<string, unknown>,\n resolve: ClientOmitResolver\n): Record<string, unknown> =>\n PROJECTING_OPERATIONS.has(operation) ||\n ((operation === \"createMany\" ||\n operation === \"updateMany\" ||\n operation === \"deleteMany\") &&\n args.omit !== undefined)\n ? rewriteNode(model, args, resolve)\n : args;\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\n ? isPlainRecord(node.omit)\n ? { ...defaults, ...node.omit }\n : { ...defaults }\n : node.omit;\n\n if (\n nextSelect === selectValue &&\n nextInclude === includeValue &&\n nextOmit === node.omit\n )\n return node;\n\n return {\n ...node,\n ...(nextSelect !== selectValue && { select: nextSelect }),\n ...(nextInclude !== includeValue && { include: nextInclude }),\n ...(nextOmit !== node.omit && { omit: nextOmit }),\n };\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 const carrier = directVariantCarrier(resolved);\n let rewritten: unknown = value;\n if (carrier) {\n rewritten = rewriteVariantCarrier(carrier, value, resolve);\n } else {\n const target = slotTarget(resolved);\n if (value === true) {\n const defaults = resolve.omit(target);\n if (defaults) rewritten = { omit: { ...defaults } };\n } else if (isPlainRecord(value)) {\n rewritten = rewriteLinkRow(\n resolved,\n rewriteNode(target, value, resolve),\n resolve\n );\n }\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 = (resolved: ResolvedSlot): AnyModel => {\n const edge = resolved.edge;\n if (edge.kind === \"foreignKey\" || edge.kind === \"junction\") {\n // The slot's own model, which a view reading its source's slot is not.\n const [first, second] = edge.endpoints;\n return first.source === resolved.slot.source &&\n 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 a unique key.\",\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 {\n ClientInitializationError,\n isVibORMError,\n ValidationError,\n} 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 baseOperation,\n isWriteOperation,\n ROUTED_OPERATIONS,\n} from \"@query-engine/routed-operations\";\nimport type { TransactionOperation } from \"@query-engine/transaction-operation\";\nimport type { PrepareOptions } from \"@query-engine/types\";\nimport { hydrateSchemaNames } from \"@schema/hydration\";\nimport type { AnyModel } from \"@schema/model\";\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 refreshView,\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/** Find the first GeoPoint field (`model.field`), or `null` when none exists. */\nfunction findGeoPointField(schema: Schema): string | null {\n for (const modelName in schema) {\n if (!Object.hasOwn(schema, modelName)) continue;\n const scalars: Record<string, Scalar> =\n schema[modelName]![\"~\"].state.scalars;\n for (const fieldName in scalars) {\n if (!Object.hasOwn(scalars, fieldName)) continue;\n if (scalars[fieldName]![\"~\"].state.type === \"point\") {\n return `${modelName}.${fieldName}`;\n }\n }\n }\n return null;\n}\n\nconst EMPTY_STRING_SET: ReadonlySet<string> = new Set();\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: `$sql`, `$rows(alias)` and `$refresh(options)`. */\n core?: (model: keyof S, member: string, argument?: unknown) => unknown,\n path: string[] = [],\n /** The proxy's own target: a view that answers for a root hands its own. */\n target: object = path.length === 2 ? () => undefined : {},\n /** Pre-built root model-name set shared across every view of the same schema. */\n rootMembers?: ReadonlySet<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: ReadonlySet<string> =\n path.length === 0\n ? (rootMembers ?? new Set(Object.keys(schema)))\n : path.length === 1\n ? new Set([\n ...ROUTED_OPERATIONS,\n ...(core ? [\"$rows\", \"$sql\", \"$refresh\"] : []),\n ...Object.keys(methods ?? {}),\n ])\n : EMPTY_STRING_SET;\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\" && core) return core(path[0]!, key);\n let child = children.get(key);\n if (child === undefined) {\n child =\n (key === \"$rows\" || key === \"$refresh\") && core\n ? (argument: unknown) => core(path[0]!, key, argument)\n : createModelProxy(schema, createOperation, modelMethods, core, [\n ...path,\n key,\n ]);\n children.set(key, child);\n }\n return child;\n };\n return new Proxy(target, {\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 /** Detached snapshot of the validated schema entries, insulated from caller mutation. */\n readonly #snapshot: 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 readonly #modelNames: ReadonlySet<string>;\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(\n config: C,\n { snapshot, relations, schemaRegistry, modelNames }: PreparedSchema\n ) {\n this.#schema = config.schema as ClientSchema<C>;\n this.#snapshot = snapshot as ClientSchema<C>;\n this.#relations = relations;\n this.#registry = schemaRegistry;\n this.#modelNames = modelNames;\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.#snapshot,\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 target: object\n ): Client<C> {\n return createModelProxy(\n this.#snapshot,\n ({ modelName, operation, args }) =>\n this.#prepareModelOperation(\n engine,\n modelName,\n operation,\n args,\n clientOmit\n ),\n modelMethods,\n (modelName, member, argument) =>\n member === \"$sql\"\n ? renderers\n .get(this.#snapshot)!\n .get(engine.driver.adapter)!\n .spelling(this.#snapshot[modelName]!, engine.driver.dialect)\n : member === \"$rows\"\n ? createRowsFragment(engine, this.#snapshot[modelName]!, argument)\n : refreshView(engine, this.#snapshot[modelName]!, argument),\n [],\n target,\n this.#modelNames\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.#snapshot[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 let rawArgs = (args ?? {}) as Record<string, unknown>;\n // `named` is the call's, not its payload's: it leaves the arguments before\n // anything reads them, so neither the SQL, a cache key nor an extension\n // sees it, and reaches every statement of the call through its context.\n let options: PrepareOptions | undefined;\n if (Object.hasOwn(rawArgs, \"named\")) {\n const { named, ...payload } = rawArgs;\n rawArgs = payload;\n if (named !== undefined)\n options = { named: admitNamed(modelNameStr, operation, named) };\n }\n const chain = engine.extensionChain;\n // Without a chain or an omission nothing transforms the arguments, plans\n // a field or watches a write: the operation is its arguments as given.\n // Apart, so that such a call makes none of what a chain's steps share\n // (0.2 kB and 1 % of a `findUnique`'s client CPU).\n if (chain === undefined && clientOmit === undefined) {\n assertNonEmptyUniqueWhere(modelNameStr, operation, rawArgs);\n return engine.prepare(model, operation, rawArgs, options);\n }\n return this.#prepareChainedModelOperation(\n engine,\n model,\n modelNameStr,\n operation,\n rawArgs,\n clientOmit,\n chain,\n options?.named\n );\n }\n\n /** One model operation of a client with an extension chain or an omission. */\n #prepareChainedModelOperation(\n engine: QueryEngine,\n model: AnyModel,\n modelNameStr: string,\n operation: Operations,\n rawArgs: Record<string, unknown>,\n clientOmit: ClientOmitResolver | undefined,\n chain: ResolvedExtensionChain | undefined,\n named: boolean | undefined\n ): PendingOperation<unknown> {\n const isWrite = isWriteOperation(operation);\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 ? named === undefined\n ? undefined\n : { named }\n : {\n named,\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.#snapshot,\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 // The view and its model proxy share one target, and the view asks the\n // model proxy by name. A proxy whose target is a proxy checks each member\n // it answers against that target's own property: every `db.user` asked\n // the model proxy for a descriptor and read the member a second time\n // (4 % of a `findUnique`'s client CPU).\n const target = {};\n const models = this.#createClient(\n engine,\n methods?.model,\n clientOmit,\n target\n );\n return new Proxy(target, {\n get: (_target, prop) => {\n if (typeof prop === \"string\" && !prop.startsWith(\"$\")) {\n return Reflect.get(models, 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.#snapshot, prop)\n ? Reflect.get(models, prop)\n : undefined;\n },\n // What the model proxy answered while it was the target.\n has: (_target, key) => Reflect.has(models, key),\n ownKeys: () => Reflect.ownKeys(models),\n getOwnPropertyDescriptor: (_target, key) =>\n Reflect.getOwnPropertyDescriptor(models, key),\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 \"$extends requires an extension.\"\n );\n const extensionChain = extension.append(\n chain,\n this.#snapshot,\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(\"Driver is required.\");\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(\"PostgreSQL requires a namespace.\");\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 let geoPointField: string | null | undefined = reused?.geoPointField;\n if (config.driver.adapter.geoPoint === undefined) {\n if (geoPointField === undefined) {\n geoPointField = findGeoPointField(config.schema);\n if (reused) reused.geoPointField = geoPointField;\n }\n if (geoPointField !== null) {\n throw new ClientInitializationError(\n `GeoPoint field '${geoPointField}' unsupported by adapter.`\n );\n }\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 =\n reused ?? prepareSchema(config.schema, checked, geoPointField);\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 /** Detached shallow snapshot of the validated schema entries. */\n readonly snapshot: Schema;\n readonly keys: readonly string[];\n readonly models: readonly AnyModel[];\n readonly modelNames: ReadonlySet<string>;\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 /** Memoized GeoPoint scan (`undefined` = unchecked, `null` = none, `string` = first `model.field`). */\n geoPointField: string | null | undefined;\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. A second WeakMap keyed on the first model also catches\n * fresh `{ ...models }` object literals wrapping the exact same model instances.\n */\nconst preparedSchemas = new WeakMap<object, PreparedSchema>();\nconst preparedByFirstModel = new WeakMap<object, PreparedSchema>();\n\nfunction matchesPreparedSchema(\n schema: Schema,\n prepared: PreparedSchema\n): boolean {\n const { keys, models } = prepared;\n let count = 0;\n for (const key in schema) {\n if (!Object.hasOwn(schema, key)) continue;\n if (\n count >= keys.length ||\n keys[count] !== key ||\n schema[key] !== models[count]\n )\n return false;\n count++;\n }\n return count === keys.length;\n}\n\nfunction reusablePreparation(\n schema: Schema,\n checked: boolean\n): PreparedSchema | undefined {\n let prepared = preparedSchemas.get(schema);\n if (prepared === undefined) {\n for (const key in schema) {\n if (!Object.hasOwn(schema, key)) continue;\n const first = schema[key];\n if (first !== undefined && typeof first === \"object\" && first !== null) {\n prepared = preparedByFirstModel.get(first);\n }\n break;\n }\n }\n // A validating client never reuses a preparation that skipped validation.\n if (!(prepared && (prepared.validated || checked))) return;\n if (!matchesPreparedSchema(schema, prepared)) return;\n return prepared;\n}\n\nfunction prepareSchema(\n schema: Schema,\n checked: boolean,\n geoPointField: string | null | undefined\n): PreparedSchema {\n const snapshot: Schema = {};\n const keys: string[] = [];\n const models: AnyModel[] = [];\n for (const key in schema) {\n if (!Object.hasOwn(schema, key)) continue;\n const model = schema[key]!;\n keys.push(key);\n models.push(model);\n snapshot[key] = model;\n }\n const relations = checked\n ? resolveCheckedSchemaOrThrow(snapshot)\n : resolveSchemaOrThrow(snapshot, true);\n const schemaRegistry = createResolvedSchemaRegistry(snapshot, relations);\n const prepared: PreparedSchema = {\n snapshot,\n keys,\n models,\n modelNames: new Set(keys),\n relations,\n schemaRegistry,\n fittingDialects: new Set(),\n geoPointField,\n validated: !checked,\n };\n preparedSchemas.set(schema, prepared);\n if (models.length > 0 && models[0] !== undefined) {\n preparedByFirstModel.set(models[0], prepared);\n }\n return prepared;\n}\n\n/** A call's `named` option, admitted once: a boolean, or the call is refused. */\nfunction admitNamed(\n model: string,\n operation: Operations,\n named: unknown\n): boolean {\n if (typeof named === \"boolean\") return named;\n throw new ValidationError(\n baseOperation(operation),\n [{ path: \"named\", message: \"named must be a boolean.\" }],\n { meta: { model } }\n );\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":"ktDAeA,IAAa,GAAb,MAAa,CAAY,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,EACT,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,EACT,EACA,KAAK,MACL,KAAK,SACL,OAAO,eAAe,CACtB,EACA,EACA,KAAK,MACN,CAMH,QACE,EACA,EACA,EACA,EACA,EACA,EACqB,CACrB,OAAO,GACL,KACA,EACA,EACA,EACA,EACA,EACA,EACD,GCnFL,MAAM,GAAoB,IAAI,QAE9B,SAAgB,GACd,EACA,EACA,EACM,CACN,GAAkB,IAAI,EAAQ,CAAE,UAAS,aAAY,CAAC,CAGxD,SAAgB,GACd,EAC+B,CAC/B,IAAM,EAAY,GAAkB,IAAI,EAAO,CAC/C,OAAO,GAAW,WAAW,EAAO,CAAG,EAAU,QAAU,IAAA,GAG7D,SAAgB,GACd,EACA,EACA,EAC6B,CAC7B,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAK,OAAQ,IAAS,CAChD,IAAM,EAAM,EAAK,GACjB,GACE,EAAE,OAAO,OAAO,EAAM,EAAM,EAAI,MAAM,QAAQ,EA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