viborm 1.3.1 → 1.3.2

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.
Files changed (167) hide show
  1. package/dist/{adapter-namespace-BpMbLKpL.mjs → adapter-namespace-B8XWzCev.mjs} +1 -1
  2. package/dist/{adapter-namespace-BpMbLKpL.mjs.map → adapter-namespace-B8XWzCev.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +1 -1
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/{batch-refs-B4zn-FAu.mjs → batch-refs-DoWlPD2h.mjs} +1 -1
  6. package/dist/{batch-refs-B4zn-FAu.mjs.map → batch-refs-DoWlPD2h.mjs.map} +1 -1
  7. package/dist/{builder-s1ySUuMb.mjs → builder-DhxaVYP2.mjs} +2 -2
  8. package/dist/{builder-s1ySUuMb.mjs.map → builder-DhxaVYP2.mjs.map} +1 -1
  9. package/dist/bun-sql.d.mts +1 -1
  10. package/dist/bun-sql.mjs +1 -1
  11. package/dist/bun-sqlite.d.mts +1 -1
  12. package/dist/bun-sqlite.mjs +1 -1
  13. package/dist/cache/cloudflare-kv.d.mts +1 -1
  14. package/dist/cache/cloudflare-kv.mjs +1 -1
  15. package/dist/cache/memory.d.mts +1 -1
  16. package/dist/cache/memory.mjs +1 -1
  17. package/dist/cache.d.mts +1 -1
  18. package/dist/cache.mjs +1 -1
  19. package/dist/cache.mjs.map +1 -1
  20. package/dist/chain-BjJ_M7EE.mjs +2 -0
  21. package/dist/chain-BjJ_M7EE.mjs.map +1 -0
  22. package/dist/cli.mjs +1 -1
  23. package/dist/client-BCgMXn6N.mjs +2 -0
  24. package/dist/client-BCgMXn6N.mjs.map +1 -0
  25. package/dist/{client-70MrTq1E.d.mts → client-Df81J4oB.d.mts} +1 -1
  26. package/dist/{client-BgJ7Faln.mjs → client-q6ccRgdO.mjs} +2 -2
  27. package/dist/{client-BgJ7Faln.mjs.map → client-q6ccRgdO.mjs.map} +1 -1
  28. package/dist/client.d.mts +1 -1
  29. package/dist/client.mjs +1 -1
  30. package/dist/{clock-C24RcpwO.mjs → clock-YTLtjLFS.mjs} +1 -1
  31. package/dist/{clock-C24RcpwO.mjs.map → clock-YTLtjLFS.mjs.map} +1 -1
  32. package/dist/config.d.mts +1 -1
  33. package/dist/config.mjs +1 -1
  34. package/dist/d1.d.mts +1 -1
  35. package/dist/d1.mjs +1 -1
  36. package/dist/{driver-vn-9CN0y.mjs → driver-D6_Ik58x.mjs} +2 -2
  37. package/dist/{driver-vn-9CN0y.mjs.map → driver-D6_Ik58x.mjs.map} +1 -1
  38. package/dist/{driver-B9fIori_.mjs → driver-Ddt147dK.mjs} +2 -2
  39. package/dist/{driver-B9fIori_.mjs.map → driver-Ddt147dK.mjs.map} +1 -1
  40. package/dist/driver.d.mts +1 -1
  41. package/dist/driver.mjs +1 -1
  42. package/dist/every-dpzVDwzu.mjs +2 -0
  43. package/dist/{every-CcpKWCVo.mjs.map → every-dpzVDwzu.mjs.map} +1 -1
  44. package/dist/{fs-estate-i8Zlr1OQ.mjs → fs-estate-azK36i9V.mjs} +2 -2
  45. package/dist/{fs-estate-i8Zlr1OQ.mjs.map → fs-estate-azK36i9V.mjs.map} +1 -1
  46. package/dist/{hydration-BsPZI4jE.mjs → hydration-C2uXmJy6.mjs} +2 -2
  47. package/dist/{hydration-BsPZI4jE.mjs.map → hydration-C2uXmJy6.mjs.map} +1 -1
  48. package/dist/{identifier-conversion-BneQiLxQ.mjs → identifier-conversion-C2pwwFOS.mjs} +2 -2
  49. package/dist/{identifier-conversion-BneQiLxQ.mjs.map → identifier-conversion-C2pwwFOS.mjs.map} +1 -1
  50. package/dist/identity-Bj2EN6Ss.mjs +2 -0
  51. package/dist/identity-Bj2EN6Ss.mjs.map +1 -0
  52. package/dist/{index-VsM29vYN.d.mts → index-D4O0Twvs.d.mts} +16 -8
  53. package/dist/index.d.mts +1 -1
  54. package/dist/index.mjs +1 -1
  55. package/dist/instrumentation.d.mts +1 -1
  56. package/dist/instrumentation.mjs +1 -1
  57. package/dist/{key-D9LtHxVK.mjs → key-B7vuAYPG.mjs} +2 -2
  58. package/dist/{key-D9LtHxVK.mjs.map → key-B7vuAYPG.mjs.map} +1 -1
  59. package/dist/{libsql-BlSBYwd_.mjs → libsql-DUO6vHad.mjs} +2 -2
  60. package/dist/{libsql-BlSBYwd_.mjs.map → libsql-DUO6vHad.mjs.map} +1 -1
  61. package/dist/libsql.d.mts +1 -1
  62. package/dist/libsql.mjs +1 -1
  63. package/dist/{memory-C0k-_S_n.mjs → memory-BApsTkt1.mjs} +2 -2
  64. package/dist/{memory-C0k-_S_n.mjs.map → memory-BApsTkt1.mjs.map} +1 -1
  65. package/dist/migrations/mysql.d.mts +4 -4
  66. package/dist/migrations/mysql.mjs +1 -1
  67. package/dist/migrations/postgres.d.mts +4 -4
  68. package/dist/migrations/postgres.mjs +1 -1
  69. package/dist/migrations/sqlite.d.mts +4 -4
  70. package/dist/migrations/sqlite.mjs +1 -1
  71. package/dist/migrations/storage/durable-object.mjs +1 -1
  72. package/dist/migrations/storage/fs.mjs +1 -1
  73. package/dist/migrations/storage/r2.mjs +1 -1
  74. package/dist/migrations/tenant.d.mts +2 -2
  75. package/dist/migrations/tenant.mjs +1 -1
  76. package/dist/migrations.d.mts +4 -4
  77. package/dist/migrations.mjs +1 -1
  78. package/dist/{mysql-DOLHwIM_.mjs → mysql-D1GlcktG.mjs} +2 -2
  79. package/dist/{mysql-DOLHwIM_.mjs.map → mysql-D1GlcktG.mjs.map} +1 -1
  80. package/dist/{mysql-adapter-C6c5govr.mjs → mysql-adapter-ClOoHKpn.mjs} +2 -2
  81. package/dist/{mysql-adapter-C6c5govr.mjs.map → mysql-adapter-ClOoHKpn.mjs.map} +1 -1
  82. package/dist/mysql2.d.mts +1 -1
  83. package/dist/mysql2.mjs +1 -1
  84. package/dist/neon-http.d.mts +1 -1
  85. package/dist/neon-http.mjs +1 -1
  86. package/dist/{object-store-D9mvOHP4.d.mts → object-store-BN64q8Zn.d.mts} +3 -3
  87. package/dist/{object-store-ChYHlOMD.mjs → object-store-CZADAv4c.mjs} +2 -2
  88. package/dist/{object-store-ChYHlOMD.mjs.map → object-store-CZADAv4c.mjs.map} +1 -1
  89. package/dist/permissions.d.mts +2 -2
  90. package/dist/permissions.mjs +1 -1
  91. package/dist/permissions.mjs.map +1 -1
  92. package/dist/pg.d.mts +1 -1
  93. package/dist/pg.mjs +1 -1
  94. package/dist/pglite.d.mts +1 -1
  95. package/dist/pglite.mjs +1 -1
  96. package/dist/{pinned-session-BTplL3iZ.mjs → pinned-session-CjvR0Ge2.mjs} +2 -2
  97. package/dist/{pinned-session-BTplL3iZ.mjs.map → pinned-session-CjvR0Ge2.mjs.map} +1 -1
  98. package/dist/planetscale.d.mts +1 -1
  99. package/dist/planetscale.mjs +1 -1
  100. package/dist/{planner-C1NzLBge.d.mts → planner-8smxUOt9.d.mts} +1 -1
  101. package/dist/{postgres-DQVSTqVm.mjs → postgres-Be0jMJWI.mjs} +2 -2
  102. package/dist/{postgres-DQVSTqVm.mjs.map → postgres-Be0jMJWI.mjs.map} +1 -1
  103. package/dist/{postgres-adapter-CxEit2-v.mjs → postgres-adapter-BoQ4RRwr.mjs} +2 -2
  104. package/dist/{postgres-adapter-CxEit2-v.mjs.map → postgres-adapter-BoQ4RRwr.mjs.map} +1 -1
  105. package/dist/{postgres-adapter-CGthb5yh.mjs → postgres-adapter-C_Mt8lVC.mjs} +2 -2
  106. package/dist/{postgres-adapter-CGthb5yh.mjs.map → postgres-adapter-C_Mt8lVC.mjs.map} +1 -1
  107. package/dist/{postgres-result-KyBKBNJr.mjs → postgres-result-CYu1dyI_.mjs} +1 -1
  108. package/dist/{postgres-result-KyBKBNJr.mjs.map → postgres-result-CYu1dyI_.mjs.map} +1 -1
  109. package/dist/postgres.d.mts +1 -1
  110. package/dist/postgres.mjs +1 -1
  111. package/dist/result-shape-DQc-tDJ5.mjs +2 -0
  112. package/dist/{result-shape-B6yWtnx_.mjs.map → result-shape-DQc-tDJ5.mjs.map} +1 -1
  113. package/dist/rows-JXjhWwyb.mjs +2 -0
  114. package/dist/rows-JXjhWwyb.mjs.map +1 -0
  115. package/dist/{scalar-CpEwuJvn.mjs → scalar-CqqZ6jWd.mjs} +2 -2
  116. package/dist/{scalar-CpEwuJvn.mjs.map → scalar-CqqZ6jWd.mjs.map} +1 -1
  117. package/dist/schema/json.d.mts +1 -1
  118. package/dist/schema/json.mjs +1 -1
  119. package/dist/{schema-BnzGHn7k.mjs → schema-Cv-hhpl5.mjs} +2 -2
  120. package/dist/{schema-BnzGHn7k.mjs.map → schema-Cv-hhpl5.mjs.map} +1 -1
  121. package/dist/{schema-introspection-DZsdP6bi.mjs → schema-introspection-B2Rvqgut.mjs} +3 -3
  122. package/dist/{schema-introspection-DZsdP6bi.mjs.map → schema-introspection-B2Rvqgut.mjs.map} +1 -1
  123. package/dist/schema.d.mts +1 -1
  124. package/dist/schema.mjs +1 -1
  125. package/dist/{select-assembly-CkGe2ABs.mjs → select-assembly-BxtETbG9.mjs} +1 -1
  126. package/dist/{select-assembly-CkGe2ABs.mjs.map → select-assembly-BxtETbG9.mjs.map} +1 -1
  127. package/dist/{settle-CS_k6Ztm.mjs → settle-etgtP1WM.mjs} +2 -2
  128. package/dist/{settle-CS_k6Ztm.mjs.map → settle-etgtP1WM.mjs.map} +1 -1
  129. package/dist/sha256-CEYo7k7R.mjs +2 -0
  130. package/dist/sha256-CEYo7k7R.mjs.map +1 -0
  131. package/dist/soft-delete.d.mts +1 -1
  132. package/dist/{sql-statement-tokens-CFi1y3bK.mjs → sql-statement-tokens-BW7Q-rF-.mjs} +1 -1
  133. package/dist/{sql-statement-tokens-CFi1y3bK.mjs.map → sql-statement-tokens-BW7Q-rF-.mjs.map} +1 -1
  134. package/dist/{sqlite-adapter-BXAJy3mI.mjs → sqlite-adapter-B_LNxPA0.mjs} +2 -2
  135. package/dist/{sqlite-adapter-BXAJy3mI.mjs.map → sqlite-adapter-B_LNxPA0.mjs.map} +1 -1
  136. package/dist/{sqlite-utils-D_cypcyW.mjs → sqlite-utils-DIOll4P7.mjs} +1 -1
  137. package/dist/{sqlite-utils-D_cypcyW.mjs.map → sqlite-utils-DIOll4P7.mjs.map} +1 -1
  138. package/dist/sqlite3.d.mts +1 -1
  139. package/dist/sqlite3.mjs +1 -1
  140. package/dist/{standard-sql-CoGqv-iX.mjs → standard-sql-mJt0RHHE.mjs} +1 -1
  141. package/dist/{standard-sql-CoGqv-iX.mjs.map → standard-sql-mJt0RHHE.mjs.map} +1 -1
  142. package/dist/{to-many-C5RMZl05.mjs → to-many-BSipkSbK.mjs} +2 -2
  143. package/dist/{to-many-C5RMZl05.mjs.map → to-many-BSipkSbK.mjs.map} +1 -1
  144. package/dist/{utils-C3r4gO3Y.mjs → utils-DjXObbUK.mjs} +2 -2
  145. package/dist/{utils-C3r4gO3Y.mjs.map → utils-DjXObbUK.mjs.map} +1 -1
  146. package/dist/v-CrJYqdzu.mjs +2 -0
  147. package/dist/v-CrJYqdzu.mjs.map +1 -0
  148. package/dist/validation.d.mts +1 -1
  149. package/dist/validation.mjs +1 -1
  150. package/dist/{validator-CVSrhn0u.mjs → validator-BqzpyNmt.mjs} +2 -2
  151. package/dist/{validator-CVSrhn0u.mjs.map → validator-BqzpyNmt.mjs.map} +1 -1
  152. package/dist/version-Dus3if78.mjs +2 -0
  153. package/dist/{version-C8QLCt1n.mjs.map → version-Dus3if78.mjs.map} +1 -1
  154. package/package.json +15 -15
  155. package/dist/chain-7qiFSE8J.mjs +0 -2
  156. package/dist/chain-7qiFSE8J.mjs.map +0 -1
  157. package/dist/client-6YgGlXzN.mjs +0 -2
  158. package/dist/client-6YgGlXzN.mjs.map +0 -1
  159. package/dist/controls-KQ85SWfT.mjs +0 -2
  160. package/dist/controls-KQ85SWfT.mjs.map +0 -1
  161. package/dist/every-CcpKWCVo.mjs +0 -2
  162. package/dist/identity-oQvIe7u8.mjs +0 -2
  163. package/dist/identity-oQvIe7u8.mjs.map +0 -1
  164. package/dist/result-shape-B6yWtnx_.mjs +0 -2
  165. package/dist/v-DtLdBQYg.mjs +0 -2
  166. package/dist/v-DtLdBQYg.mjs.map +0 -1
  167. package/dist/version-C8QLCt1n.mjs +0 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-BCgMXn6N.mjs","names":["#engine","#execution","#context","#method","#captured","#parse","#queryHandlers","parse","#resolve","#queryContext","#runResolved","#readInstrumentationFacts","#observationCommitCertainty","#resolved","#resolveQuery","#runAttributed","#withObservationNotifications","#run","#getPromise","error","candidate","own","own","own","member","#membershipViews","#physicalFields","#storedFieldLists","#clearabilityViews","#restrictingSlotViews","#upsert","#admitArguments","operation","#queryViewsByAdapter","sql","#queries","#prepared","#inputs","#layered","#projected","#projectedFacts","#view","#prepareSelector","own","#produced","#views","#result","#call","#sharesBodies","#shared","#sharing","#sharingBodies","#excluded","#scope","#drops","#lowersLayer","#values","#instant","#instantOf","#nextAlias","#scalarValue","#listValue","#typedScalarValue","#geoPoint","#nativeType","#projectedTypedColumn","#leaf","#rootAlias","#named","#prepareUpdate","#arithmeticTarget","#rooted","#prepareWhere","#scopes","#prepareScalarPredicate","#capturedSet","#known","#outsideOwnSubtree","#walk","#sameRow","#producedRows","states","#holds","#ascendingKeys","#frames","#lowerStated","#resolve","#lowerPredicate","#within","#capped","#prepareExists","#prepareSlotPredicate","#scalar","#prepareOperations","#prepareOperatorFilter","#prepareOperand","#prepareOuterOperand","#prepareFieldOperand","entries","#relationPredicate","#relationScope","#relationFacts","#bound","#lowerRelationPredicate","#lowerExists","#boundParameters","#guarded","#masked","#gateHolds","#preparedColumn","#aggregateExpression","#lowerTarget","#lowerJsonOperation","#outerAlias","literal","#targetValue","#lowerOtherOperation","#distanceExpression","#sumTargetValue","#relationExists","#membershipWhere","#related","#lowerOrder","#orderTerms","#orderTerm","#relationOrderTerm","#operand","#gatedHere","#sortKey","#correlatedCount","#totalOrder","#reverseOrder","#cursorCondition","#completeOrder","#identityEntries","#page","#selectWhere","#read","#readAggregate","rows","#prepareAggregates","#masks","#overMasked","#aggregateLeaf","#splitSum","#carriedValue","#splitSumSql","#prepareCounts","#distanceLeaf","#prepareRelationProjection","#collectionShape","#relationShape","#projectCounts","#projectDistance","#projectEvidence","#projectVariants","#lowerProjectionField","#orphanedMemberships","#lowerRelationProjection","#parentClaimsArm","#missingArm","#lowerEvidence","#truth","#duplicateMembershipGuard","#lowerRecursiveRelationProjection","#lowerSpecialProjectionField","#layerHolds","#memberSource","object","#rowKey","#junctionTarget","#aliased","#step","#recursiveIdentity","nodeFacts","edgeFacts","#grouped","#prepareHaving","#groupOrderTerms","arms","#compileCollection","#compileGatedDocument","#compileScalarValue","#enterJsonContainer","member","#publications","#carriedValues","#producers","#premises","#judged","#members","#withheld","#ownership","#memberRollback","#operationRegion","#writeOutcome","#attempt","#attemptStore","#continuationCount","#continuationList","#committedProgress","#committedSegments","#mayHaveCommittedSegment","#incompletePreparationSentinel","#correlationId","#correlationIdValue","#requiresEnvelopeSentinel","#callerAttribution","#transport","#errorMeta","#memberAdmissionStarted","#memberAttributionMap","#executingMember","#completedMembers","#withMemberRollback","#ownRegionOpen","#answeredFailureSet","#setWindow","#committedMemberSet","#regionPhase","#withinRegion","#openRegionPhase","#stateWriteOutcome","#runWrite","#runFailure","#requireAtomicUnit","#region","#batchAttempt","#regionAttempt","#envelope","#restart","#performed","#vacatedMemberships","#replaceAttempt","#acceptInsertRecovery","#recoverySpent","#publishPositional","#decideRead","#queue","#preparedParser","#flushQueued","#readsBatchReference","#atomicAssertionRejection","#carryScratch","member","#answered","#settleCarry","#preparedGuardList","#decodeTerminalResults","parse","#setMutation","#queueJudged","#judging","sql","#produced","#forbidden","#insertIdField","#insertStatement","#completeSetMutation","#updateAssignments","#produce","#capturedMutation","#updatedIdentity","#packagedPresence","inserted","projection","rows","#effect","#spendSlot","statement","#refusal","target","child","#writes","#requested","#held","#named","#equal","#refusal","#bindings","#resolveValue","#rowProjection","#identityProjection","#bindMembership","#rowQuery","#entered","#currentAttempt","#replaceRegions","#matchesSelectedConstraint","#requireTransitions","#membershipValues","#unrepresentable","#spentByHolder","#recover","replacement","#foundFailure","#carried","#refusal","#membershipParent","#sharesInsert","#insertTogether","confirmationFailure","#mutationConfirmationFailure","#linkValues","#executeRecords","#executeSeries","record","count","#adoptSuppressed","command","#locateSuppressed","#requireNoAddedMember","#exclusiveMemberMove","#memberData","#admitMember","#direct","#hasSupply","#commands","#parent","#slot","#admitted","#raw","#supplier","#relation","#setTargets","#clearMembership","origin","#membershipSource","#requireLookup","#requireUnreferenced","#child","#supply","facts","target","supplied","#correlationParent","source","#replaceMembership","mutation","#requireSeriesCapture","#linkFields","#relations","#nextMutation","#origin","#recipeChildren","#materializePlacement","#bindTree","#analyzeOccurrence","edge","literal","#literalOf","disjoint","#depend","command","origin","#reader","#runsBefore","own","#dependencyRead","#seriesOwner","#recordOwner","#visitDirectWrites","#visitWrites","#childBranch","#visitReads","#visitPrecedingWrites","#isSeriesMember","#branchOf","#checkPair","#compatible","#readMembership","#readTarget","#analyzeRead","#analyzeChildren","record","refusal","#visitFollowingReads","#activeRefusal","key","series","projection","values","#unreferenced","#rootUpsert","occurrence","#config","#schema","#queries","#operation","#model","#modelName","#rawArgs","#missing","#scope","#admitted","#admit","#prepared","#read","#facts","#plan","#body","#context","#factoryDriver","#modelName","#requestedOperation","#prepared","#codec","isPlainRecord","rewritten","#schema","#engine","#relations","#registry","#prepareModelOperation","#wrapOfficialCachedRead","#extensionOmitResolvers","#createClient","#transact","#createViewProxy","#createView","#resolveClientOmit","#createRootView","#withCache"],"sources":["../src/client/raw.ts","../src/extensions/methods.ts","../src/extensions/request.ts","../src/query-engine/query-engine.ts","../src/drivers/positional-result.ts","../src/query-engine/batch-error-attribution.ts","../src/query-engine/bind-budget.ts","../src/sql/slot.ts","../src/query-engine/raptor3/shared/decimal.ts","../src/query-engine/raptor3/shared/identifier.ts","../src/validation/primitives/raw-record.ts","../src/query-engine/raptor3/shared/parse-boundary.ts","../src/query-engine/raptor3/shared/storage.ts","../src/query-engine/raptor3/shared/schema.ts","../src/query-engine/raptor3/shared/query.ts","../src/query-engine/raptor3/shared/transport-attempt.ts","../src/query-engine/raptor3/shared/operation-context.ts","../src/query-engine/raptor3/shared/projected.ts","../src/query-engine/raptor3/commands/assignments.ts","../src/query-engine/raptor3/commands/command-attempt.ts","../src/query-engine/raptor3/commands/selection.ts","../src/query-engine/raptor3/commands/execution.ts","../src/query-engine/raptor3/commands/relation-body.ts","../src/query-engine/raptor3/commands/commands.ts","../src/query-engine/raptor3/commands/index.ts","../src/query-engine/raptor3/route/client-route.ts","../src/extensions/array-admission.ts","../src/client/array-transaction-failures.ts","../src/client/array-transaction-native-batch.ts","../src/client/array-transaction-legacy.ts","../src/client/array-transaction-native.ts","../src/client/array-transaction.ts","../src/client/omit.ts","../src/client/unique-where-guard.ts","../src/client/client.ts"],"sourcesContent":["/**\n * Raw SQL client surface — Prisma-shaped, safe by construction.\n *\n * Four methods, two families:\n *\n * - `$queryRaw` / `$executeRaw` are TAGGED TEMPLATES. Every interpolation\n * becomes a bound parameter rendered in the driver's own placeholder style\n * ($1, ?, :1), so a value can never reach the statement as text. They also\n * accept a prebuilt `Sql` fragment (`sql`/`join`/`empty`/`raw`).\n * - `$queryRawUnsafe` / `$executeRawUnsafe` take a hand-written statement\n * string plus positional parameters. The caller owns the escaping.\n *\n * `$queryRaw*` answers the ROWS (`T[]`); `$executeRaw*` answers the AFFECTED\n * COUNT (`number`) — Prisma's split, not a `QueryResult` envelope.\n *\n */\n\nimport { markVerbatimBatchQuery } from \"@drivers/driver-batch-query-kind\";\nimport type {\n AnyDriver,\n QueryExecutionContext,\n QueryResult,\n} from \"@drivers/exports\";\nimport { transferPreparedStatement } from \"@drivers/prepared-statement-provenance\";\nimport { validateRawParameters } from \"@drivers/provider-parameter-snapshot\";\nimport {\n InvalidTransactionInputError,\n QueryError,\n retainWriteOutcomeFailure,\n VibORMErrorCode,\n} from \"@errors\";\nimport {\n lookupResolvedExtensionHandlers,\n type ResolvedExtensionHandler,\n} from \"@extensions/chain\";\nimport { observeOperation } from \"@extensions/observation\";\nimport {\n executePreparedQuery,\n type QueryInterceptionMode,\n type RawQueryKind,\n type WriteOutcomeNotifications,\n} from \"@extensions/query\";\nimport {\n createOperationExecutionContext,\n createRawOperationInstrumentationFacts,\n observeTransactionBatchPhase,\n withOperationErrorContext,\n} from \"@query-engine/execution-context\";\nimport { PendingExecution } from \"@query-engine/pending-execution\";\nimport type { QueryEngine } from \"@query-engine/query-engine\";\nimport { snapshotQueryInput } from \"@query-engine/query-inspection\";\nimport {\n registerTransactionOperationOwner,\n type TransactionOperation,\n type TransactionOperationOwner,\n} from \"@query-engine/transaction-operation\";\nimport { isSql, Sql } from \"@sql\";\n\n/** The four raw methods, spelled exactly as a caller types them. */\nexport type RawMethodName =\n | \"$executeRaw\"\n | \"$executeRawUnsafe\"\n | \"$queryRaw\"\n | \"$queryRawUnsafe\";\n\n/** The exact runtime inventory used by client routing and extension lookup. */\nexport const RAW_METHOD_NAMES = Object.freeze({\n $executeRaw: true,\n $executeRawUnsafe: true,\n $queryRaw: true,\n $queryRawUnsafe: true,\n} satisfies Readonly<Record<RawMethodName, true>>);\n\n/** The execute families are the only raw calls that publish write outcomes. */\nfunction isRawWrite(method: RawMethodName): boolean {\n return method === \"$executeRaw\" || method === \"$executeRawUnsafe\";\n}\n\n/** What a safe raw call accepts as its first argument. */\nexport type RawQueryInput = Sql | TemplateStringsArray;\n\n/**\n * The raw surface, on the client and on an interactive transaction client.\n */\nexport interface RawSurface {\n /**\n * Run a SELECT and get the rows. Interpolations are bound parameters.\n *\n * @example\n * ```ts\n * const rows = await client.$queryRaw<{ id: string }>`\n * SELECT id FROM \"user\" WHERE age >= ${18}\n * `;\n * ```\n */\n $queryRaw<T = unknown>(query: RawQueryInput): RawOperation<T[]>;\n $queryRaw<T = unknown>(\n query: TemplateStringsArray,\n ...values: unknown[]\n ): RawOperation<T[]>;\n /**\n * Run a hand-written SELECT string with positional parameters. The statement\n * text is used verbatim — never build it from user input.\n */\n $queryRawUnsafe<T = unknown>(\n query: string,\n ...values: unknown[]\n ): RawOperation<T[]>;\n /**\n * Run a statement and get the affected row count. Interpolations are bound\n * parameters.\n */\n $executeRaw(query: RawQueryInput): RawOperation<number>;\n $executeRaw(\n query: TemplateStringsArray,\n ...values: unknown[]\n ): RawOperation<number>;\n /**\n * Run a hand-written statement string with positional parameters. The\n * statement text is used verbatim — never build it from user input.\n */\n $executeRawUnsafe(query: string, ...values: unknown[]): RawOperation<number>;\n}\n\nexport interface RawSurfaceOptions {\n /** The engine owns both the target driver and transaction-operation scope. */\n engine: QueryEngine;\n}\n\nfunction isTemplateStringsArray(value: unknown): value is TemplateStringsArray {\n // A tagged template hands its callee the cooked strings array carrying a\n // `raw` sibling array — the one shape a plain string or Sql never has.\n return Array.isArray(value) && Array.isArray(Reflect.get(value, \"raw\"));\n}\n\nfunction rawInputError(\n method: RawMethodName,\n message: string,\n parameterIndex?: number\n): QueryError {\n return new QueryError(`${method} ${message}`, {\n code: VibORMErrorCode.INVALID_INPUT,\n meta:\n parameterIndex === undefined ? { method } : { method, parameterIndex },\n });\n}\n\nfunction copyIndexedValues(values: readonly unknown[]): unknown[] {\n const copy = new Array<unknown>(values.length);\n for (let index = 0; index < values.length; index += 1) {\n if (Object.hasOwn(values, index)) copy[index] = values[index];\n }\n return copy;\n}\n\nfunction copySqlStrings(strings: readonly string[]): string[] {\n const copy = new Array<string>(strings.length);\n for (let index = 0; index < strings.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(strings, index);\n if (\n descriptor === undefined ||\n !(\"value\" in descriptor) ||\n typeof descriptor.value !== \"string\"\n ) {\n throw new TypeError(\"Sql fragment strings must be plain string values\");\n }\n copy[index] = descriptor.value;\n }\n return copy;\n}\n\nfunction createOperationSql(query: Sql): Sql {\n return new Sql(\n copySqlStrings(query.strings),\n copyIndexedValues(query.values)\n );\n}\n\nfunction validateRawParametersBeforeInterception(\n method: RawMethodName,\n params: readonly unknown[]\n): void {\n validateRawParameters(params, {\n invalidDate: (parameterIndex) =>\n rawInputError(\n method,\n `received an invalid Date as bound parameter ${parameterIndex}. An invalid Date names no instant, so a provider either refuses the statement after dispatch or binds it as null.`,\n parameterIndex\n ),\n unsupportedArray: (parameterIndex) =>\n rawInputError(\n method,\n `received raw array parameter ${parameterIndex} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,\n parameterIndex\n ),\n });\n}\n\ntype CapturedRawQuery =\n | {\n readonly family: \"safe\";\n readonly query: RawQueryInput;\n readonly values: readonly unknown[];\n }\n | {\n readonly family: \"unsafe\";\n readonly query: unknown;\n readonly values: readonly unknown[];\n };\n\ntype ResolvedRawQuery =\n | { readonly kind: \"fragment\"; readonly query: Sql }\n | {\n readonly kind: \"verbatim\";\n readonly sql: string;\n readonly params: readonly unknown[];\n };\n\ntype RawRow<T> = T extends (infer Row)[] ? Row : unknown;\n\nfunction captureValues(values: readonly unknown[]): readonly unknown[] {\n return Object.freeze(copyIndexedValues(values));\n}\n\n/**\n * The nominal marker that separates a raw operation from a bare promise. It is\n * `declare`d, so it exists only in the type system: nothing is added to the\n * value at runtime and the packed public surface gains no export.\n */\ndeclare const RAW_OPERATION: unique symbol;\n\n/**\n * A lazy raw statement that remains assignable to `Promise<T>`.\n *\n * The brand is load-bearing. Without it this interface is STRUCTURALLY\n * identical to `Promise<T>`, so `$transaction([Promise.resolve(1)])`\n * typechecked and then threw `InvalidTransactionInputError` at runtime: an\n * array member has to be an object the transaction-operation owner registry\n * recognises (`readTransactionOperation`), which a bare promise is not. The\n * type now refuses what the implementation refuses.\n */\nexport interface RawOperation<T> extends Promise<T> {\n readonly [RAW_OPERATION]: true;\n}\n\nconst rawOperationConstruction = Object.freeze({});\n\ntype CreateDeferredRawOperation = <T>(\n engine: QueryEngine,\n method: RawMethodName,\n captured: CapturedRawQuery,\n parse: (raw: QueryResult<RawRow<T>>) => T\n) => DeferredRawOperation<T>;\n\nlet createDeferredRawOperation: CreateDeferredRawOperation;\n\nlet rawTransactionOwner: TransactionOperationOwner<\n DeferredRawOperation<unknown>\n>;\n\nclass DeferredRawOperation<T>\n implements RawOperation<T>, TransactionOperation<T>\n{\n // Type-only: the brand has no runtime representation, and the registry - not\n // this field - is what authenticates an array member.\n declare readonly [RAW_OPERATION]: true;\n\n readonly [Symbol.toStringTag] = \"Promise\";\n\n readonly #engine: QueryEngine;\n readonly #execution: PendingExecution<T>;\n readonly #context: QueryExecutionContext;\n readonly #method: RawMethodName;\n readonly #captured: CapturedRawQuery;\n readonly #parse: (raw: QueryResult<RawRow<T>>) => T;\n readonly #queryHandlers: readonly ResolvedExtensionHandler[] | undefined;\n #resolved: ResolvedRawQuery | undefined;\n #observationCommitCertainty: \"committed\" | \"may-have-committed\" | undefined;\n\n static {\n createDeferredRawOperation = <T>(\n engine: QueryEngine,\n method: RawMethodName,\n captured: CapturedRawQuery,\n parse: (raw: QueryResult<RawRow<T>>) => T\n ) =>\n new DeferredRawOperation<T>(\n rawOperationConstruction,\n engine,\n method,\n captured,\n parse\n );\n rawTransactionOwner = Object.freeze({\n clientId: (operation) => operation.#engine.clientId,\n scopeId: (operation) => operation.#engine.scopeId,\n model: () => \"$raw\",\n operation: (operation) => operation.#method,\n context: (operation) => operation.#context,\n requiresInterception: (operation) =>\n operation.#queryHandlers !== undefined &&\n operation.#queryHandlers.length > 0,\n prepareAdmission: (operation) => {\n operation.#resolve();\n },\n stagePackageWriteOutcomes: () => undefined,\n startInterception: (operation, child, outcomes, control) => {\n const handlers = operation.#queryHandlers;\n if (handlers === undefined || handlers.length === 0) return child();\n const query = operation.#resolve();\n return executePreparedQuery<unknown, Record<string, unknown>>(\n operation.#queryContext(\"array\", query),\n handlers,\n child,\n isRawWrite(operation.#method),\n outcomes,\n control\n );\n },\n executeCore: (operation, driver, notifications) =>\n operation.#execution.executeReserved(() =>\n operation.#runResolved(driver, operation.#resolve(), notifications)\n ),\n isWrite: (operation) => isRawWrite(operation.#method),\n hasObservation: (operation) =>\n (operation.#engine.extensionChain?.observe.length ?? 0) > 0,\n observe: (operation, child, readCompletionFacts) => {\n const observers = operation.#engine.extensionChain?.observe;\n if (observers === undefined || observers.length === 0) return child();\n return observeOperation(\n observers,\n operation.#method,\n undefined,\n child,\n readCompletionFacts,\n operation.#readInstrumentationFacts()\n );\n },\n reserveWith: (operation, driver) => {\n operation.#execution.reserveWith(driver);\n },\n executeWith: (operation, driver) => {\n const execute = () =>\n operation.#runResolved(driver, operation.#resolve());\n const observers = operation.#engine.extensionChain?.observe;\n if (observers === undefined || observers.length === 0) {\n return operation.#execution.executeWith(driver, execute);\n }\n return operation.#execution.executeWith(driver, () =>\n observeOperation(\n observers,\n operation.#method,\n undefined,\n execute,\n () =>\n operation.#observationCommitCertainty === undefined\n ? undefined\n : {\n commitCertainty: operation.#observationCommitCertainty,\n },\n operation.#readInstrumentationFacts()\n )\n );\n },\n prepare: (operation, driver = operation.#engine.driver) => {\n const query = operation.#resolve();\n if (query.kind === \"verbatim\") {\n return markVerbatimBatchQuery({\n sql: query.sql,\n params: [...query.params],\n context: operation.#context,\n });\n }\n const prepared = driver._prepare(query.query, operation.#context);\n return transferPreparedStatement(prepared, {\n sql: prepared.sql,\n params: prepared.params ? [...prepared.params] : [],\n context: operation.#context,\n });\n },\n prepareBatch: async () => undefined,\n parseResult: (operation, raw) => operation.#parse(raw),\n observeBatchPhase: (operation, driver, execute) =>\n observeTransactionBatchPhase(operation.#context, driver, execute),\n } satisfies TransactionOperationOwner<DeferredRawOperation<unknown>>);\n registerTransactionOperationOwner(\n DeferredRawOperation.prototype,\n (value): value is DeferredRawOperation<unknown> => #engine in value,\n rawTransactionOwner\n );\n Object.freeze(DeferredRawOperation.prototype);\n }\n\n private constructor(\n construction: typeof rawOperationConstruction,\n engine: QueryEngine,\n method: RawMethodName,\n captured: CapturedRawQuery,\n parse: (raw: QueryResult<RawRow<T>>) => T\n ) {\n if (construction !== rawOperationConstruction) {\n throw new InvalidTransactionInputError();\n }\n this.#engine = engine;\n this.#method = method;\n this.#captured = captured;\n this.#parse = parse;\n this.#queryHandlers = lookupResolvedExtensionHandlers(\n engine.extensionChain,\n \"query\",\n undefined,\n method\n );\n this.#execution = new PendingExecution<T>(\"$raw\", method);\n this.#context = createOperationExecutionContext(\n \"$raw\",\n method,\n engine.extensionChain\n );\n Object.freeze(this);\n }\n\n #resolve(): ResolvedRawQuery {\n if (this.#resolved) return this.#resolved;\n\n // Refusing before memoizing keeps a rejected statement rejected however\n // many times admission, interception, and execution ask for it.\n const resolved = this.#resolveQuery();\n validateRawParametersBeforeInterception(\n this.#method,\n resolved.kind === \"fragment\" ? resolved.query.values : resolved.params\n );\n this.#resolved = resolved;\n return resolved;\n }\n\n #resolveQuery(): ResolvedRawQuery {\n const method = this.#method;\n const { query, values } = this.#captured;\n if (this.#captured.family === \"unsafe\") {\n if (typeof query === \"string\") {\n return { kind: \"verbatim\", sql: query, params: [...values] };\n }\n } else if (isTemplateStringsArray(query)) {\n return { kind: \"fragment\", query: new Sql(query, values) };\n } else if (isSql(query)) {\n if (values.length > 0) {\n throw rawInputError(\n method,\n \"received an Sql fragment together with extra values. The fragment already carries its parameters — interpolate them into it instead.\"\n );\n }\n return { kind: \"fragment\", query: createOperationSql(query) };\n }\n throw rawInputError(\n method,\n `expects a tagged template (${method}\\`SELECT ...\\`) or an Sql fragment built with sql\\`...\\`. Received a value that is neither.`\n );\n }\n\n #queryContext(mode: QueryInterceptionMode, query: ResolvedRawQuery) {\n return Object.freeze({\n mode,\n kind: this.#method.slice(1) as RawQueryKind,\n model: undefined,\n operation: this.#method,\n input: snapshotQueryInput(\n query.kind === \"fragment\"\n ? { query: query.query }\n : { sql: query.sql, params: [...query.params] }\n ),\n });\n }\n\n #run(driver: AnyDriver): Promise<T> {\n return withOperationErrorContext(this.#context, () =>\n this.#runAttributed(driver)\n );\n }\n\n #runAttributed(driver: AnyDriver): Promise<T> {\n const handlers = this.#queryHandlers;\n if (handlers === undefined || handlers.length === 0) {\n return this.#runResolved(\n driver,\n this.#resolve(),\n this.#withObservationNotifications()\n );\n }\n let query: ResolvedRawQuery;\n try {\n query = this.#resolve();\n } catch (error) {\n return Promise.reject(error);\n }\n return executePreparedQuery<T, Record<string, unknown>>(\n this.#queryContext(\n this.#engine.transactionWriteOutcomes ? \"transaction\" : \"direct\",\n query\n ),\n handlers,\n (notifications) =>\n this.#runResolved(\n driver,\n query,\n this.#withObservationNotifications(notifications)\n ),\n isRawWrite(this.#method),\n this.#engine.transactionWriteOutcomes\n );\n }\n\n async #runResolved(\n driver: AnyDriver,\n query: ResolvedRawQuery,\n notifications?: WriteOutcomeNotifications\n ): Promise<T> {\n const writeNotifications = isRawWrite(this.#method)\n ? notifications\n : undefined;\n let raw: QueryResult<RawRow<T>>;\n try {\n raw =\n query.kind === \"fragment\"\n ? await driver._execute<RawRow<T>>(query.query, this.#context)\n : await driver._executeRaw<RawRow<T>>(\n query.sql,\n [...query.params],\n this.#context\n );\n } catch (error) {\n try {\n await writeNotifications?.mayHaveCommitted();\n } catch (outcomeFailure) {\n throw retainWriteOutcomeFailure(error, outcomeFailure);\n }\n throw error;\n }\n\n let parseOutcome:\n | { readonly status: \"success\"; readonly value: T }\n | { readonly status: \"failure\"; readonly error: unknown };\n try {\n parseOutcome = { status: \"success\", value: this.#parse(raw) };\n } catch (error) {\n parseOutcome = { status: \"failure\", error };\n }\n try {\n await writeNotifications?.committed();\n } catch (outcomeFailure) {\n if (parseOutcome.status === \"failure\") {\n throw retainWriteOutcomeFailure(parseOutcome.error, outcomeFailure);\n }\n throw outcomeFailure;\n }\n if (parseOutcome.status === \"failure\") throw parseOutcome.error;\n return parseOutcome.value;\n }\n\n #getPromise(): Promise<T> {\n return this.#execution.executeDefault(() => {\n const observers = this.#engine.extensionChain?.observe;\n if (observers === undefined || observers.length === 0) {\n return this.#run(this.#engine.driver);\n }\n return observeOperation(\n observers,\n this.#method,\n undefined,\n () => this.#run(this.#engine.driver),\n () =>\n this.#observationCommitCertainty === undefined\n ? undefined\n : { commitCertainty: this.#observationCommitCertainty },\n this.#readInstrumentationFacts()\n );\n });\n }\n\n #readInstrumentationFacts() {\n return createRawOperationInstrumentationFacts(\n this.#engine.driver,\n this.#context,\n this.#method\n );\n }\n\n #withObservationNotifications(\n notifications?: WriteOutcomeNotifications\n ): WriteOutcomeNotifications | undefined {\n if (\n this.#engine.transactionWriteOutcomes !== undefined ||\n (this.#engine.extensionChain?.observe.length ?? 0) === 0\n ) {\n return notifications;\n }\n const publish = async (\n certainty: \"committed\" | \"may-have-committed\",\n notify: (() => Promise<void>) | undefined\n ): Promise<void> => {\n let notificationFailed = false;\n let notificationFailure: unknown;\n try {\n await notify?.();\n } catch (error) {\n notificationFailed = true;\n notificationFailure = error;\n }\n if (\n certainty === \"committed\" ||\n this.#observationCommitCertainty === undefined\n ) {\n this.#observationCommitCertainty = certainty;\n }\n if (notificationFailed) throw notificationFailure;\n };\n return Object.freeze({\n committed: () => publish(\"committed\", notifications?.committed),\n mayHaveCommitted: () =>\n publish(\"may-have-committed\", notifications?.mayHaveCommitted),\n });\n }\n\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): Promise<TResult1 | TResult2> {\n return this.#getPromise().then(onfulfilled, onrejected);\n }\n\n catch<TResult = never>(\n onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null\n ): Promise<T | TResult> {\n return this.#getPromise().catch(onrejected);\n }\n\n finally(onfinally?: (() => void) | null): Promise<T> {\n return this.#getPromise().finally(onfinally);\n }\n}\n\n/**\n * Build the four raw methods bound to one query-engine scope.\n *\n * Inside an interactive transaction the engine carries the transaction-bound\n * driver and scope identity, so raw and model operations share both ownership\n * checks and execution.\n */\nexport function createRawSurface(options: RawSurfaceOptions): RawSurface {\n const { engine } = options;\n // The RawSurface interface owns the overloads; a name fixes the family\n // (the `Unsafe` suffix) and the answer (rows, or the affected count). The\n // computed key gives each function its public `.name` (`$queryRaw`, ...).\n const method = (name: RawMethodName) =>\n ({\n [name]: (query: unknown, ...values: unknown[]) =>\n createDeferredRawOperation<unknown>(\n engine,\n name,\n {\n family: name.endsWith(\"Unsafe\") ? \"unsafe\" : \"safe\",\n query,\n values: captureValues(values),\n } as CapturedRawQuery,\n isRawWrite(name) ? (raw) => raw.rowCount : (raw) => raw.rows\n ),\n })[name];\n return {\n $executeRaw: method(\"$executeRaw\"),\n $executeRawUnsafe: method(\"$executeRawUnsafe\"),\n $queryRaw: method(\"$queryRaw\"),\n $queryRawUnsafe: method(\"$queryRawUnsafe\"),\n } as RawSurface;\n}\n","import type { TransactionClient, VibORMConfig } from \"@client/client\";\nimport { RAW_METHOD_NAMES, type RawSurface } from \"@client/raw\";\nimport type { ClientSchema } from \"@client/schema-links\";\nimport type {\n Client,\n ClientRowsContext,\n Operations,\n StampedOperation,\n StampedOperations,\n} from \"@client/types\";\nimport { ClientInitializationError } from \"@errors\";\nimport { ROUTED_OPERATIONS } from \"@query-engine/routed-operations\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport type { OfficialCacheControls } from \"../cache/capability\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport type { ResolvedExtensionChain } from \"./chain\";\nimport type {\n DefinitionControls,\n DefinitionData,\n NoControls,\n RowsModels,\n} from \"./controls\";\nimport { extensionError } from \"./definition\";\n\ntype NoMethods = Record<never, never>;\ntype ExtensionMethod = (this: void, ...args: never[]) => unknown;\nexport type ExtensionMethodRecord = Readonly<Record<string, ExtensionMethod>>;\n\nexport type RuntimeExtensionMethodFunction = (...args: never[]) => unknown;\nexport type RuntimeClientMethodContribution = RuntimeExtensionMethodFunction;\nexport type RuntimeModelMethodContribution = Readonly<\n Record<string, RuntimeExtensionMethodFunction>\n>;\n\ndeclare const extensionCacheState: unique symbol;\nexport interface ExtensionCacheState {\n readonly [extensionCacheState]: true;\n}\ndeclare const extensionResultConsumerState: unique symbol;\nexport interface ExtensionResultConsumerState {\n readonly [extensionResultConsumerState]: true;\n}\n\n/** The only static facts accumulated while extensions are chained. */\nexport interface ClientExtensionState<\n ClientMethods extends object = NoMethods,\n ModelMethods extends object = NoMethods,\n CacheState extends ExtensionCacheState | undefined = undefined,\n ResultConsumerState extends\n | ExtensionResultConsumerState\n | undefined = undefined,\n Controls extends object = NoControls,\n RowModels extends string = never,\n Data = never,\n> {\n readonly client: ClientMethods;\n readonly models: ModelMethods;\n readonly cache: CacheState;\n readonly resultConsumer: ResultConsumerState;\n /** The controls the chain declares: each one's values and placement. */\n readonly controls: Controls;\n /** The models the chain's `rows` can hide from a relation read. */\n readonly rows: RowModels;\n /** The fields the chain's `data` writes, which a caller no longer writes. */\n readonly data: Data;\n}\n\nexport type EmptyClientExtensionState = ClientExtensionState;\n\n/** Internal constraint for either the absent or enabled nominal cache bit. */\nexport type ExtensionStateConstraint = ClientExtensionState<\n object,\n object,\n ExtensionCacheState | undefined,\n ExtensionResultConsumerState | undefined,\n object,\n string,\n unknown\n>;\n\n/** Whether the current type-state includes the official cache capability. */\nexport type HasExtensionCache<X extends ExtensionStateConstraint> = [\n X[\"cache\"],\n] extends [ExtensionCacheState]\n ? true\n : false;\n\n/**\n * Add the official cache capability without carrying its runtime config. Its\n * one control, `cache` on every write, joins the chain's controls as its\n * definition declares it.\n */\nexport type EnableExtensionCache<X extends ExtensionStateConstraint> =\n ClientExtensionState<\n X[\"client\"],\n X[\"models\"],\n ExtensionCacheState,\n X[\"resultConsumer\"],\n X[\"controls\"] &\n DefinitionControls<{ readonly controls: OfficialCacheControls }>,\n X[\"rows\"],\n X[\"data\"]\n >;\n\n/** Whether an earlier extension was typed against result-bearing delegates. */\nexport type HasResultConsumingExtension<X extends ExtensionStateConstraint> = [\n X[\"resultConsumer\"],\n] extends [undefined]\n ? false\n : [X[\"resultConsumer\"]] extends [ExtensionResultConsumerState]\n ? true\n : false;\n\ntype MethodsForModel<\n X extends ExtensionStateConstraint,\n ModelName extends PropertyKey,\n> = ModelName extends keyof X[\"models\"] ? X[\"models\"][ModelName] : NoMethods;\n\n/**\n * One model's delegate after the chain's methods and controls. On a chain\n * that declares create `data`, its writes may leave out the fields the chain\n * writes on a create.\n */\nexport type ExtensionModelDelegate<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n ModelName extends keyof ClientSchema<C>,\n> = ([X[\"data\"]] extends [never]\n ? Client<C, ClientRowsContext<C, X[\"rows\"]>, X[\"controls\"]>[ModelName]\n : Omit<\n Client<C, ClientRowsContext<C, X[\"rows\"]>, X[\"controls\"]>[ModelName],\n StampedOperation\n > &\n StampedOperations<\n C,\n ClientRowsContext<C, X[\"rows\"]>,\n X[\"controls\"],\n X[\"data\"],\n ModelName\n >) &\n MethodsForModel<X, ModelName>;\n\n/**\n * Model delegates after the methods contributed by the current chain. The\n * always-true test is deliberate: for a client generic over its config it\n * stays deferred, so the model map adds no index signature to that client and\n * its `$` members stay reachable inside a body generic over `C`.\n */\nexport type ExtensionModelClient<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = [keyof C[\"schema\"]] extends [PropertyKey]\n ? {\n [ModelName in keyof ClientSchema<C>]: ExtensionModelDelegate<\n C,\n X,\n ModelName\n >;\n }\n : unknown;\n\n/** The surface given to one client-method factory. */\nexport type ExtensionClientScope<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = ExtensionModelClient<C, X> &\n RawSurface &\n X[\"client\"] & {\n readonly $schema: ClientSchema<C>;\n readonly $transaction: TransactionClient<C, X>[\"$transaction\"];\n /**\n * The client this scope's methods are called on, its calls admitting\n * these values of this extension's own controls as if passed (a\n * `bound: true` control only from here). Its type is that client's,\n * which only the method knows: declare it with a `this` parameter,\n * `$with<Self>(this: Self, value: Value): Self`, outside the returned\n * literal (inside it, the factory's contextual type makes `Self` void).\n */\n readonly $bind: (values: Readonly<Record<string, unknown>>) => unknown;\n };\n\ntype NonFunctionKeys<Methods extends object> = {\n [Key in keyof Methods]: Methods[Key] extends CallableFunction ? never : Key;\n}[keyof Methods];\n\ntype InvalidClientMethodKeys<\n Methods extends object,\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> =\n | Exclude<keyof Methods, `$${string}`>\n | Extract<\n keyof Methods,\n | keyof RawSurface\n | \"$driver\"\n | \"$schema\"\n | \"$transaction\"\n | \"$connect\"\n | \"$disconnect\"\n | \"$withCache\"\n | \"$invalidate\"\n | \"$extends\"\n | keyof X[\"client\"]\n >\n | (string extends keyof C[\"schema\"]\n ? never\n : Extract<keyof Methods, keyof C[\"schema\"]>)\n | NonFunctionKeys<Methods>;\n\ntype GuardMethodFactory<\n Factory,\n Forbidden extends PropertyKey,\n> = Factory extends (...args: infer Params) => infer Methods\n ? Methods extends object\n ? (...args: Params) => Methods & Record<Forbidden, never>\n : (...args: Params) => never\n : never;\n\ntype ClientFactoryGuard<\n Definition,\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = Definition extends { readonly client: infer Factory }\n ? Factory extends (...args: never[]) => infer Methods\n ? Methods extends object\n ? {\n readonly client: GuardMethodFactory<\n Factory,\n InvalidClientMethodKeys<Methods, C, X>\n >;\n }\n : { readonly client: never }\n : { readonly client: never }\n : unknown;\n\n/**\n * What every model factory may not return: a core operation or `then`. That\n * each returned member is a function is the definition's own factory type\n * (`ModelMethodFactory` returns an `ExtensionMethodRecord`), not this guard;\n * `object` only keeps the all-optional key list from being a weak type, which\n * would refuse every return that names none of those keys. Stated as a target\n * shape, not a conditional over the factory, so a factory map generic over the\n * client is checked rather than deferred. A method a prior extension put on\n * the model cannot be named here for a client generic over its extension\n * state: the runtime refuses that replacement when the extension is applied.\n */\ntype ModelFactoryGuard = (...args: never[]) => object & {\n readonly [Name in Operations | \"then\"]?: never;\n};\n\n/**\n * Model keys outside the schema are refused by the definition's own `model`\n * type (its per-schema factory table); this guard checks each factory's\n * methods.\n */\ntype ModelFactoriesGuard<Definition> = Definition extends {\n readonly model: infer Factories;\n}\n ? {\n readonly model: {\n readonly [ModelName in keyof Factories]: ModelFactoryGuard;\n };\n }\n : unknown;\n\nexport type ExtensionMethodDefinitionGuard<\n Definition,\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = ClientFactoryGuard<Definition, C, X> & ModelFactoriesGuard<Definition>;\n\ntype ClientMethodsOf<Definition> = Definition extends {\n readonly client: (...args: never[]) => infer Methods;\n}\n ? Methods extends object\n ? Methods\n : NoMethods\n : NoMethods;\n\ntype ModelMethodsOf<Definition> = Definition extends {\n readonly model: infer Factories;\n}\n ? Factories extends object\n ? {\n readonly [ModelName in keyof Factories]: Factories[ModelName] extends (\n ...args: never[]\n ) => infer Methods\n ? Methods extends object\n ? Methods\n : NoMethods\n : NoMethods;\n }\n : NoMethods\n : NoMethods;\n\nexport type MergeModelMethods<Left extends object, Right extends object> = {\n readonly [ModelName in\n | keyof Left\n | keyof Right]: (ModelName extends keyof Left\n ? Left[ModelName]\n : NoMethods) &\n (ModelName extends keyof Right ? Right[ModelName] : NoMethods);\n};\n\nexport type ResultConsumerContextOf<Definition> = Definition extends\n | { readonly client: unknown }\n | { readonly model: unknown }\n ? \"result-consuming\"\n : Definition extends { readonly query: infer Query }\n ? Query extends CallableFunction\n ? \"result-independent\"\n : \"result-consuming\"\n : \"result-independent\";\n\n/** Incoming facts keep their nominal bit derivation inside this named state. */\nexport interface ExtensionContributionState<\n ClientMethods extends object,\n ModelMethods extends object,\n Controls extends object,\n RowModels extends string,\n Data,\n ConsumerContext extends string,\n> extends ExtensionStateConstraint {\n readonly client: ClientMethods;\n readonly models: ModelMethods;\n readonly cache: undefined;\n readonly resultConsumer: ConsumerContext extends \"result-consuming\"\n ? ExtensionResultConsumerState\n : undefined;\n readonly controls: Controls;\n readonly rows: RowModels;\n readonly data: Data;\n}\n\n/** Retain contribution facts, never the factory's contextual argument surface. */\nexport type ExtensionStateContributionOf<Definition> = [Definition] extends [\n unknown,\n]\n ? ExtensionContributionState<\n ClientMethodsOf<Definition>,\n ModelMethodsOf<Definition>,\n DefinitionControls<Definition>,\n RowsModels<Definition>,\n DefinitionData<Definition>,\n ResultConsumerContextOf<Definition>\n >\n : never;\n\n/** Accumulate the same seven facts lazily, without retaining callback definitions. */\nexport interface AccumulatedExtensionState<\n X extends ExtensionStateConstraint,\n Contribution extends ExtensionStateConstraint,\n> extends ExtensionStateConstraint {\n readonly client: X[\"client\"] & Contribution[\"client\"];\n readonly models: MergeModelMethods<X[\"models\"], Contribution[\"models\"]>;\n readonly cache: X[\"cache\"];\n readonly resultConsumer: HasResultConsumingExtension<Contribution> extends true\n ? ExtensionResultConsumerState\n : X[\"resultConsumer\"];\n readonly controls: X[\"controls\"] & Contribution[\"controls\"];\n readonly rows: X[\"rows\"] | Contribution[\"rows\"];\n readonly data: X[\"data\"] | Contribution[\"data\"];\n}\n\n/** Public compatibility surface: the incoming argument remains a definition. */\nexport type MergeExtensionState<\n X extends ExtensionStateConstraint,\n Definition,\n> = AccumulatedExtensionState<X, ExtensionStateContributionOf<Definition>>;\n\ntype MethodRecord = Readonly<Record<string, RuntimeExtensionMethodFunction>>;\n\n/**\n * The methods a view answers after some prefix of its chain: its client\n * methods, and one model's. Each is computed the first time it is read.\n */\nexport interface ExtensionMethods {\n readonly client: () => MethodRecord;\n readonly model: (model: string) => MethodRecord;\n}\n\nconst NO_METHODS: MethodRecord = Object.freeze(Object.create(null));\nconst NO_LAYER: ExtensionMethods = Object.freeze({\n client: () => NO_METHODS,\n model: () => NO_METHODS,\n});\n\nconst CORE_CLIENT_METHODS = new Set([\n \"$driver\",\n \"$schema\",\n \"$transaction\",\n \"$connect\",\n \"$disconnect\",\n \"$withCache\",\n \"$invalidate\",\n \"$extends\",\n]);\n\nfunction readMethodRecord(\n value: unknown,\n label: string,\n extension: string\n): Record<string, RuntimeExtensionMethodFunction> {\n if (!isRecord(value)) {\n extensionError(\n `Extension \"${extension}\" ${label} factory must return an object.`,\n extension\n );\n }\n const methods: Record<string, RuntimeExtensionMethodFunction> =\n Object.create(null);\n let names: PropertyKey[];\n try {\n names = Reflect.ownKeys(value);\n } catch (cause) {\n throw new ClientInitializationError(\n `Extension \"${extension}\" ${label} methods could not be inspected.`,\n { cause: errorCause(cause), meta: { extension } }\n );\n }\n for (const name of names) {\n if (typeof name !== \"string\") {\n extensionError(\n `Extension \"${extension}\" ${label} returned a non-string method key.`,\n extension\n );\n }\n let method: unknown;\n try {\n method = value[name];\n } catch (cause) {\n throw new ClientInitializationError(\n `Extension \"${extension}\" ${label} method \"${name}\" could not be read.`,\n { cause: errorCause(cause), meta: { extension } }\n );\n }\n if (!isFunction(method)) {\n extensionError(\n `Extension \"${extension}\" ${label} method \"${name}\" must be a function.`,\n extension\n );\n }\n methods[name] = bindExtensionMethod(method);\n }\n return methods;\n}\n\nfunction invokeFactory(\n factory: RuntimeExtensionMethodFunction,\n argument: unknown,\n label: string,\n extension: string\n): unknown {\n try {\n return Reflect.apply(factory, undefined, [argument]);\n } catch (cause) {\n throw new ClientInitializationError(\n `Extension \"${extension}\" ${label} factory failed.`,\n { cause: errorCause(cause), meta: { extension } }\n );\n }\n}\n\nfunction bindExtensionMethod(\n method: RuntimeExtensionMethodFunction\n): RuntimeExtensionMethodFunction {\n return (...args: never[]) => Reflect.apply(method, undefined, args);\n}\n\n/** The methods before one extension with its own added, each name checked. */\nfunction addMethods(\n previous: MethodRecord,\n added: MethodRecord,\n check: (name: string, taken: boolean) => void\n): MethodRecord {\n const methods: Record<string, RuntimeExtensionMethodFunction> =\n Object.create(null);\n Object.assign(methods, previous);\n for (const [name, method] of Object.entries(added)) {\n check(name, Object.hasOwn(methods, name));\n methods[name] = method;\n }\n return Object.freeze(methods);\n}\n\n/**\n * The methods of one view's chain. Extension `i`'s factories are invoked\n * against the scope `createScope` builds over the methods of the extensions\n * before it, the first time a method they return could be read, one model at\n * a time: a view costs the factories it uses. `force` invokes every factory\n * in chain order, where a root view surfaces an extension's faults.\n */\nexport function bindExtensionMethods(\n chain: ResolvedExtensionChain,\n createScope: (prior: ExtensionMethods, extension: string) => object\n): ExtensionMethods & { readonly force: () => void } {\n const layers: ExtensionMethods[] = [NO_LAYER];\n for (const {\n name,\n client: clientFactory,\n model: modelFactories,\n } of chain.extensions) {\n const prior = layers.at(-1)!;\n let scope: object | undefined;\n const scopeOf = () => (scope ??= createScope(prior, name));\n let client: MethodRecord | undefined;\n const models = new Map<string, MethodRecord>();\n layers.push({\n client: () =>\n (client ??=\n clientFactory === undefined\n ? prior.client()\n : addMethods(\n prior.client(),\n readMethodRecord(\n invokeFactory(clientFactory, scopeOf(), \"client\", name),\n \"client\",\n name\n ),\n (method, taken) => {\n if (!method.startsWith(\"$\")) {\n extensionError(\n `Extension \"${name}\" client method \"${method}\" must be dollar-prefixed.`,\n name\n );\n }\n if (\n taken ||\n CORE_CLIENT_METHODS.has(method) ||\n Object.hasOwn(RAW_METHOD_NAMES, method)\n ) {\n extensionError(\n `Extension \"${name}\" client method \"${method}\" collides with the existing client surface.`,\n name\n );\n }\n }\n )),\n model: (model) => {\n let methods = models.get(model);\n if (methods === undefined) {\n const factory = modelFactories?.[model];\n const label = `model.${model}`;\n methods =\n factory === undefined\n ? prior.model(model)\n : addMethods(\n prior.model(model),\n readMethodRecord(\n invokeFactory(\n factory,\n Reflect.get(scopeOf(), model),\n label,\n name\n ),\n label,\n name\n ),\n (method, taken) => {\n if (\n taken ||\n method === \"then\" ||\n ROUTED_OPERATIONS.has(method)\n ) {\n extensionError(\n `Extension \"${name}\" model method \"${model}.${method}\" collides with the existing model surface.`,\n name\n );\n }\n }\n );\n models.set(model, methods);\n }\n return methods;\n },\n });\n }\n const view = layers.at(-1)!;\n return {\n client: view.client,\n model: view.model,\n force: () => {\n for (const [index, { model }] of chain.extensions.entries()) {\n const layer = layers[index + 1]!;\n layer.client();\n for (const name of Object.keys(model ?? {})) layer.model(name);\n }\n },\n };\n}\n","import type { OperationPayload, Operations, Schema } from \"@client/types\";\nimport { QueryError } from \"@errors\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { isError } from \"../errors/diagnostic-safety\";\nimport type { ResolvedOperationHandler } from \"./chain\";\nimport { type AdmittedControls, controlsOwnedBy } from \"./controls\";\n\n/** Frozen runtime contribution after hostile definition normalization. */\ntype RuntimeRequestFunction = (...args: never[]) => unknown;\nexport type RuntimeRequestContribution =\n | RuntimeRequestFunction\n | Readonly<Record<string, Readonly<Record<string, RuntimeRequestFunction>>>>;\n\ntype ResultShapeKey =\n | \"select\"\n | \"include\"\n | \"omit\"\n | \"_count\"\n | \"_avg\"\n | \"_sum\"\n | \"_min\"\n | \"_max\"\n | \"by\";\n\nconst resultShapeKeys = <const Keys extends readonly ResultShapeKey[]>(\n ...keys: Keys\n): Readonly<Keys> => Object.freeze(keys);\n\n/**\n * The single operation-specific owner of request properties that determine the\n * public result type. A future projection spelling extends this table; runtime\n * detachment and the handler input/patch types then change together.\n */\nconst RESULT_SHAPE_KEYS_BY_OPERATION = Object.freeze({\n findFirst: resultShapeKeys(\"select\", \"include\", \"omit\"),\n findMany: resultShapeKeys(\"select\", \"include\", \"omit\"),\n findUnique: resultShapeKeys(\"select\", \"include\", \"omit\"),\n findUniqueOrThrow: resultShapeKeys(\"select\", \"include\", \"omit\"),\n findFirstOrThrow: resultShapeKeys(\"select\", \"include\", \"omit\"),\n create: resultShapeKeys(\"select\", \"include\", \"omit\"),\n update: resultShapeKeys(\"select\", \"include\", \"omit\"),\n delete: resultShapeKeys(\"select\", \"include\", \"omit\"),\n upsert: resultShapeKeys(\"select\", \"include\", \"omit\"),\n createMany: resultShapeKeys(\"select\", \"omit\"),\n updateMany: resultShapeKeys(\"select\", \"omit\"),\n deleteMany: resultShapeKeys(\"select\", \"omit\"),\n count: resultShapeKeys(\"select\"),\n aggregate: resultShapeKeys(\"_count\", \"_avg\", \"_sum\", \"_min\", \"_max\"),\n groupBy: resultShapeKeys(\"by\", \"_count\", \"_avg\", \"_sum\", \"_min\", \"_max\"),\n exist: resultShapeKeys(),\n} satisfies Readonly<Record<Operations, readonly ResultShapeKey[]>>);\n\ntype ResultShapeKeyFor<Operation extends Operations> =\n (typeof RESULT_SHAPE_KEYS_BY_OPERATION)[Operation][number];\n\n/** The operation input visible to an ordinary request transform. */\nexport type RequestTransformInput<\n Operation extends Operations,\n Input extends object,\n> = Omit<Input, ResultShapeKeyFor<Operation>>;\n\n/**\n * A shallow patch over the non-projection input. The optional `never`\n * properties make protected keys fail structurally, including held values.\n */\nexport type RequestTransformPatch<\n Operation extends Operations,\n Input extends object,\n> = Partial<RequestTransformInput<Operation, Input>> & {\n readonly [Key in ResultShapeKeyFor<Operation>]?: never;\n};\n\nexport interface RequestTransformContext<\n Operation extends Operations,\n Input extends object,\n> {\n readonly model: string;\n readonly operation: Operation;\n readonly input: Readonly<RequestTransformInput<Operation, Input>>;\n /** The call's controls this handler's extension declares, and only those. */\n readonly controls?: AdmittedControls;\n}\n\nexport interface GenericRequestContext {\n readonly model: string;\n readonly operation: Operations;\n readonly input: Readonly<\n RequestTransformPatch<Operations, Record<string, unknown>>\n >;\n /** The call's controls this handler's extension declares, and only those. */\n readonly controls?: AdmittedControls;\n}\n\ntype GenericRequestHandlerCall = (\n context: GenericRequestContext\n) => Readonly<RequestTransformPatch<Operations, Record<string, unknown>>>;\n\ndeclare const officialRequestHandlerIdentity: unique symbol;\n\n/** Public ordinary request handler; official identities cannot be erased into it. */\nexport type GenericRequestHandler = GenericRequestHandlerCall & {\n readonly [officialRequestHandlerIdentity]?: never;\n};\n\n/** Internal nominal call shape used by official request-based capabilities. */\nexport type OfficialGenericRequestHandler = GenericRequestHandlerCall & {\n readonly [officialRequestHandlerIdentity]: true;\n};\n\ntype RequestOperationInput<\n S extends Schema,\n ModelName extends keyof S,\n OperationName extends Operations,\n> = Extract<\n Exclude<OperationPayload<OperationName, S[ModelName]>, undefined>,\n object\n>;\n\nexport type RequestHandlerMap<S extends Schema> = {\n readonly [ModelName in keyof S]?: {\n readonly [OperationName in Operations]?: (context: {\n readonly model: ModelName;\n readonly operation: OperationName;\n readonly input: Readonly<\n RequestTransformInput<\n OperationName,\n RequestOperationInput<S, ModelName, OperationName>\n >\n >;\n /** The call's controls this handler's extension declares, and only those. */\n readonly controls?: AdmittedControls;\n }) => RequestTransformPatch<\n OperationName,\n RequestOperationInput<S, ModelName, OperationName>\n >;\n };\n};\n\n/** One already-selected request transform in extension application order. */\nexport type RequestTransform<\n Operation extends Operations,\n Input extends object,\n> = ResolvedOperationHandler<\n (\n context: RequestTransformContext<Operation, Input>\n ) => RequestTransformPatch<Operation, Input>\n>;\n\ninterface DescriptorEntry {\n readonly key: PropertyKey;\n readonly descriptor: PropertyDescriptor;\n}\n\ntype DescriptorState = DescriptorEntry[];\n\nconst EMPTY_REQUEST_INPUT: Readonly<Record<string, never>> = Object.freeze({});\n\n/** What request transforms are told about the chain's controls. */\nexport interface RequestControls {\n /** Every control name on the chain: no patch may name one. */\n readonly names: ReadonlySet<string>;\n /** This call's admitted controls; each owner sees its own. */\n readonly admitted: AdmittedControls | undefined;\n}\n\nfunction hasRequestTransforms(\n transforms: readonly ResolvedOperationHandler[] | undefined\n): transforms is readonly [\n ResolvedOperationHandler,\n ...ResolvedOperationHandler[],\n] {\n return transforms !== undefined && transforms.length > 0;\n}\n\n/**\n * Apply an operation's synchronous request transforms without validating the\n * resulting operation input. Validation remains the next boundary's owner.\n *\n * The undefined/empty-handler branch is deliberately first and returns the\n * original value by identity: an unextended operation allocates and inspects\n * nothing here. A handled operation always materializes the descriptors that\n * were captured before the first handler ran, so a handler cannot mutate its\n * closed-over caller input and make that mutation authoritative.\n */\nexport function applyRequestTransforms<\n Operation extends Operations,\n Input extends object,\n>(\n model: string,\n operation: Operation,\n input: Input | undefined,\n transforms: readonly RequestTransform<Operation, Input>[] | undefined,\n controls?: RequestControls\n): Input | Record<string, unknown> | undefined;\nexport function applyRequestTransforms(\n model: string,\n operation: Operations,\n input: object | undefined,\n transforms: readonly ResolvedOperationHandler[] | undefined,\n controls?: RequestControls\n): Record<string, unknown> | undefined;\nexport function applyRequestTransforms<\n Operation extends Operations,\n Input extends object,\n>(\n model: string,\n operation: Operation,\n input: Input | undefined,\n transforms:\n | readonly RequestTransform<Operation, Input>[]\n | readonly ResolvedOperationHandler[]\n | undefined,\n controls?: RequestControls\n): Input | Record<string, unknown> | undefined {\n if (!hasRequestTransforms(transforms)) return input;\n const firstTransform = transforms[0];\n\n const descriptors = readOwnDescriptors(\n input ?? EMPTY_REQUEST_INPUT,\n firstTransform,\n model,\n operation\n );\n let handlerInput = materializeHandlerInput<Operation, Input>(\n descriptors,\n operation\n );\n for (const [index, transform] of transforms.entries()) {\n const context: RequestTransformContext<Operation, Input> = Object.freeze(\n transform.controls === undefined\n ? { model, operation, input: handlerInput }\n : {\n model,\n operation,\n input: handlerInput,\n controls: controlsOwnedBy(controls?.admitted, transform.controls),\n }\n );\n const patch = invokeTransform(transform, context, model, operation);\n if (\n mergePatch(\n descriptors,\n patch,\n transform.extension,\n model,\n operation,\n controls?.names\n ) &&\n index + 1 < transforms.length\n ) {\n handlerInput = materializeHandlerInput<Operation, Input>(\n descriptors,\n operation\n );\n }\n }\n\n return materializeResult(descriptors);\n}\n\nfunction invokeTransform<Operation extends Operations, Input extends object>(\n transform: ResolvedOperationHandler,\n context: RequestTransformContext<Operation, Input>,\n model: string,\n operation: Operation\n): unknown {\n try {\n return Reflect.apply(transform.handler, undefined, [context]);\n } catch (cause) {\n throw transformFailure(\n transform.extension,\n model,\n operation,\n \"threw\",\n normalizeThrown(cause)\n );\n }\n}\n\nfunction mergePatch(\n state: DescriptorState,\n patch: unknown,\n extension: string,\n model: string,\n operation: Operations,\n controlNames: ReadonlySet<string> | undefined\n): boolean {\n let isAsync: boolean;\n try {\n isAsync = isPromiseLike(patch);\n } catch (cause) {\n throw transformFailure(\n extension,\n model,\n operation,\n \"returned an unreadable patch\",\n normalizeThrown(cause)\n );\n }\n\n if (isAsync) {\n throw transformFailure(\n extension,\n model,\n operation,\n \"returned a promise\",\n new TypeError(\"Request transforms must return synchronously\")\n );\n }\n if (!isRecord(patch)) {\n throw transformFailure(\n extension,\n model,\n operation,\n \"returned a non-record patch\",\n new TypeError(\"Request transforms must return an object\")\n );\n }\n\n let keys: PropertyKey[];\n try {\n keys = Reflect.ownKeys(patch);\n } catch (cause) {\n throw transformFailure(\n extension,\n model,\n operation,\n \"returned an unreadable patch\",\n normalizeThrown(cause)\n );\n }\n // Decided from the key alone, before any descriptor is read: a control left\n // the arguments before any handler ran, and no patch puts one back.\n for (const key of keys) {\n if (typeof key === \"string\" && controlNames?.has(key)) {\n throw transformFailure(\n extension,\n model,\n operation,\n `named control \"${key}\"`,\n new TypeError(\"Request patches cannot set extension controls\")\n );\n }\n }\n try {\n let changed = false;\n for (const key of keys) {\n // Decide from the key alone. A malicious getter behind a protected key is\n // never read or copied into the trusted operation input.\n if (isResultShapeKey(operation, key)) continue;\n const descriptor = Object.getOwnPropertyDescriptor(patch, key);\n if (!descriptor) continue;\n const existingIndex = state.findIndex((entry) => entry.key === key);\n if (existingIndex === -1) {\n state.push({ key, descriptor });\n } else {\n state[existingIndex] = { key, descriptor };\n }\n changed = true;\n }\n return changed;\n } catch (cause) {\n throw transformFailure(\n extension,\n model,\n operation,\n \"returned an unreadable patch\",\n normalizeThrown(cause)\n );\n }\n}\n\nfunction readOwnDescriptors<Operation extends Operations>(\n value: object,\n transform: ResolvedOperationHandler,\n model: string,\n operation: Operation\n): DescriptorState {\n try {\n const state: DescriptorState = [];\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined) continue;\n state.push({ key, descriptor });\n }\n return state;\n } catch (cause) {\n throw transformFailure(\n transform.extension,\n model,\n operation,\n \"could not inspect request input\",\n normalizeThrown(cause)\n );\n }\n}\n\nfunction materializeHandlerInput<\n Operation extends Operations,\n Input extends object,\n>(\n descriptors: DescriptorState,\n operation: Operation\n): Readonly<RequestTransformInput<Operation, Input>>;\nfunction materializeHandlerInput(\n descriptors: DescriptorState,\n operation: Operations\n): Readonly<Record<string, unknown>> {\n const input = materializeDescriptors(descriptors, operation);\n return input === undefined ? EMPTY_REQUEST_INPUT : Object.freeze(input);\n}\n\nfunction materializeResult(\n descriptors: DescriptorState\n): Record<string, unknown> {\n return materializeDescriptors(descriptors) ?? {};\n}\n\nfunction materializeDescriptors(\n state: DescriptorState,\n operation?: Operations\n): Record<string, unknown> | undefined {\n let value: Record<string, unknown> | undefined;\n for (const { key, descriptor } of state) {\n if (operation !== undefined && isResultShapeKey(operation, key)) continue;\n value ??= {};\n Object.defineProperty(value, key, descriptor);\n }\n return value;\n}\n\nfunction isResultShapeKey(operation: Operations, key: PropertyKey): boolean {\n if (typeof key !== \"string\") return false;\n const protectedKeys: readonly string[] =\n RESULT_SHAPE_KEYS_BY_OPERATION[operation];\n return protectedKeys.includes(key);\n}\n\nfunction isPromiseLike(value: unknown): boolean {\n return isRecord(value) && \"then\" in value && isFunction(value.then);\n}\n\nfunction normalizeThrown(thrown: unknown): Error {\n return isError(thrown)\n ? thrown\n : new Error(\"Request transform threw a non-Error value\");\n}\n\nfunction transformFailure(\n extension: string,\n model: string,\n operation: Operations,\n failure: string,\n cause: Error\n): QueryError {\n return new QueryError(\n `Extension \"${extension}\" request handler for ${model}.${operation} ${failure}.`,\n {\n cause,\n meta: { model, operation },\n }\n );\n}\n","import type { AnyDriver } from \"@drivers/exports\";\nimport type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type { AdmittedControls } from \"@extensions/controls\";\nimport type { TransactionWriteOutcomes } 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 { ClientOperationRoute } from \"./raptor3/route/client-route\";\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 readonly transactionWriteOutcomes: TransactionWriteOutcomes | undefined;\n /**\n * The control 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: AdmittedControls | 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: ClientOperationRoute;\n\n constructor(\n driver: AnyDriver,\n route: ClientOperationRoute,\n clientId = Symbol(\"viborm.client\"),\n scopeId = Symbol(\"viborm.scope\"),\n extensionChain?: ResolvedExtensionChain,\n transactionWriteOutcomes?: TransactionWriteOutcomes,\n bound?: AdmittedControls\n ) {\n this.driver = driver;\n this.route = route;\n this.extensionChain = extensionChain;\n this.transactionWriteOutcomes = transactionWriteOutcomes;\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: AdmittedControls): QueryEngine {\n return new QueryEngine(\n this.driver,\n this.route,\n this.clientId,\n this.scopeId,\n this.extensionChain,\n this.transactionWriteOutcomes,\n bound\n );\n }\n\n bind(\n driver: AnyDriver,\n extensionChain: ResolvedExtensionChain | undefined = this.extensionChain,\n transactionWriteOutcomes: TransactionWriteOutcomes | undefined = this\n .transactionWriteOutcomes\n ): QueryEngine {\n return new QueryEngine(\n driver,\n this.route,\n this.clientId,\n Symbol(\"viborm.scope\"),\n extensionChain,\n transactionWriteOutcomes,\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}\" returned malformed positional rows for operation \"${context.operation}\".`,\n { meta: createNormalizedResultMeta(context) }\n );\n }\n }\n}\n\n/** A changed execution/parser surface must see the usual keyed provider rows. */\nexport function borrowPositionalResult(\n response: PositionalQueryResult\n): QueryResult<unknown> {\n const rows = response.rows.map((row) =>\n Object.fromEntries(\n response.columns.map((column, index) => [column, row[index]])\n )\n );\n return { rows, rowCount: rows.length };\n}\n","import { batchMayContainAssertionCollision } from \"@drivers/error-mapping\";\nimport type { AnyDriver, QueryExecutionContext } from \"@drivers/exports\";\nimport {\n ForbiddenError,\n ForeignKeyError,\n NESTED_WRITE_ASSERTION_FLOOR_MESSAGE,\n NestedWriteAssertionError,\n NestedWriteError,\n NotFoundError,\n TransactionError,\n VibORMErrorCode,\n} from \"@errors\";\nimport type { PreparedBatchGuard, PreparedGuardFailure } from \"./types\";\n\n/**\n * Materialize a guard's declared {@link PreparedGuardFailure} as its typed\n * error — the ONE failure-to-error construction, which the engine's own\n * referential refusal reuses when it runs outside a package\n * (`Commands.restrictFailure`). A `notFound` failure rebuilds\n * its sentence from the model and verb, so the declared message is never\n * user-facing for that kind; the `raceable` mark is what lets the routed retry\n * re-plan and converge, so it survives every arm.\n */\nexport function createFailureError(\n failure: PreparedGuardFailure,\n model: string,\n operation: string\n): Error {\n if (failure.kind === \"foreignKey\") {\n return new ForeignKeyError(failure.message, { meta: { model, operation } });\n }\n if (failure.kind === \"nestedWrite\") {\n const error = new NestedWriteError(failure.message, failure.relation ?? \"\");\n if (failure.raceable) {\n error.meta.raceable = true;\n }\n return error;\n }\n if (failure.kind === \"notFound\") {\n return new NotFoundError(model, operation);\n }\n if (failure.kind === \"forbidden\") {\n return new ForbiddenError(model, operation);\n }\n const error = new TransactionError(failure.message, {\n meta: { model, operation },\n });\n if (failure.raceable) {\n error.meta.raceable = true;\n }\n return error;\n}\n\n/**\n * Attribute a native-batch assertion failure to the guard that raised it (P6\n * pure-leaf extraction, consumed by the client's shared-batch path): a\n * `NestedWriteAssertionError` carries the index of the offending statement when\n * the driver surfaces it, else each guard's probe is re-run to locate the\n * violated precondition. The attributed error reconstructs the guard's typed\n * failure with the correct model/operation.\n *\n * The re-probe runs AFTER the atomic batch rolled back, which makes it blind to\n * one whole class: a premise broken by a SIBLING statement inside the same batch\n * is restored by that rollback and probes clean, so no guard is blamed. When\n * every guard in the batch would raise the same failure for the same\n * model/operation, that blindness costs nothing — whichever fired, the error is\n * the same one — but only once it is established that a guard fired AT ALL.\n *\n * That last part is not free. A native batch is normalized against the JOINED\n * SQL, so one assertion statement anywhere arms the detector\n * (`src/drivers/error-mapping.ts`) for every statement in the batch: an ordinary\n * statement that raises the same provider signature — `n / 0` from a literal\n * `divide: 0` on Postgres, a malformed-JSON argument on MySQL/SQLite — arrives\n * as a `NestedWriteAssertionError` no guard caused. Blaming a guard for it\n * asserts something false about the database (a `NotFoundError`/P2025 for a row\n * that is still there, which Prisma callers branch on). So the reconstruction\n * runs only when NO ordinary statement in the batch could have produced the\n * signature — viborm built every statement, so it can tell — and the raw\n * driver-mapped error stands whenever the failure cannot be tied to a guard.\n * A batch carrying guards that DISAGREE about what went wrong likewise stays\n * un-attributable.\n */\nexport async function attributeOperationBatchError(\n error: unknown,\n guards: readonly PreparedBatchGuard[],\n driver: AnyDriver,\n statements: readonly {\n readonly sql: string;\n readonly context?: QueryExecutionContext;\n }[] = []\n): Promise<unknown> {\n if (!(error instanceof NestedWriteAssertionError)) return error;\n const statementIndex = error.meta.statementIndex;\n if (typeof statementIndex === \"number\") {\n const guard = guards.find(\n (candidate) => candidate.queryIndex === statementIndex\n );\n if (guard) {\n return createFailureError(guard.failure, guard.model, guard.operation);\n }\n return error;\n }\n if (\n guards.length > 0 &&\n batchMayContainAssertionCollision(\n statements,\n driver.dialect,\n new Set(guards.map((guard) => guard.queryIndex))\n )\n ) {\n // A failed premise after rollback does not identify which statement failed.\n return error;\n }\n for (const guard of guards) {\n const result = await driver._execute(\n guard.probe,\n statements[guard.queryIndex]?.context\n );\n const exists = result.rows.length > 0;\n if (guard.premise === \"exists\" ? !exists : exists) {\n return createFailureError(guard.failure, guard.model, guard.operation);\n }\n }\n const [candidate] = guards;\n if (candidate) {\n const attributable = guards.every((guard) =>\n sameAttribution(guard, candidate)\n );\n return attributable\n ? createFailureError(\n candidate.failure,\n candidate.model,\n candidate.operation\n )\n : error;\n }\n return new NestedWriteError(NESTED_WRITE_ASSERTION_FLOOR_MESSAGE, \"\", {\n code: VibORMErrorCode.NESTED_WRITE_ASSERTION_FAILED,\n cause: error,\n });\n}\n\n/**\n * Two guards that would produce the SAME error: same model, same operation, and\n * a failure identical in every field the reconstruction below reads.\n */\nfunction sameAttribution(\n guard: PreparedBatchGuard,\n other: PreparedBatchGuard\n): boolean {\n return (\n guard.model === other.model &&\n guard.operation === other.operation &&\n guard.failure.kind === other.failure.kind &&\n guard.failure.message === other.failure.message &&\n guard.failure.relation === other.failure.relation &&\n guard.failure.raceable === other.failure.raceable\n );\n}\n","import type { Sql } from \"@sql\";\n\nexport { normalizedBindParameterLimit } from \"@drivers/bind-parameter-capacity\";\n\nexport interface CompiledBindBudgetChunk {\n /** Inclusive semantic-item offset. */\n readonly start: number;\n /** Exclusive semantic-item offset. */\n readonly end: number;\n readonly statement: Sql;\n}\n\n/**\n * Compile the largest contiguous semantic-item ranges that fit a verified bind\n * budget. The compiled SQL is the meter; callers do not estimate binds from\n * item count or shape. `compile` must be monotonic for a growing prefix, as\n * INSERT value tuples and exact-key predicate lists are.\n *\n * Unknown capacity preserves the original one-statement shape. One item that\n * exceeds a known budget stays indivisible so the executor's final capacity\n * check can refuse it before I/O.\n */\nexport function compileBindBudgetChunks(\n itemCount: number,\n maxBindParametersPerStatement: number | undefined,\n compile: (start: number, end: number) => Sql\n): CompiledBindBudgetChunk[] {\n if (itemCount === 0) return [];\n const whole = compile(0, itemCount);\n if (\n maxBindParametersPerStatement === undefined ||\n whole.values.length <= maxBindParametersPerStatement ||\n itemCount === 1\n ) {\n return [{ start: 0, end: itemCount, statement: whole }];\n }\n\n const chunks: CompiledBindBudgetChunk[] = [];\n let start = 0;\n while (start < itemCount) {\n let lower = start + 1;\n let upper = Math.min(itemCount, start + 1);\n let largest: CompiledBindBudgetChunk | undefined;\n // Probe geometrically from this window, never from the entire remaining\n // suffix. Oversized compilation stays proportional to a window's size.\n while (true) {\n const statement = compile(start, upper);\n if (statement.values.length > maxBindParametersPerStatement) break;\n largest = { start, end: upper, statement };\n if (upper === itemCount) break;\n lower = upper + 1;\n upper = Math.min(itemCount, start + (upper - start) * 2);\n }\n if (largest?.end !== itemCount) {\n upper -= 1;\n while (lower <= upper) {\n const end = lower + Math.floor((upper - lower) / 2);\n const statement = compile(start, end);\n if (statement.values.length <= maxBindParametersPerStatement) {\n largest = { start, end, statement };\n lower = end + 1;\n } else upper = end - 1;\n }\n }\n const chunk = largest ?? {\n start,\n end: start + 1,\n statement: compile(start, start + 1),\n };\n chunks.push(chunk);\n start = chunk.end;\n }\n return chunks;\n}\n","import { Sql } from \"./sql\";\n\n/**\n * A fragment whose text its statement decides once the statement is whole,\n * between two forms known where it is placed: the provisional one until\n * {@link settle}, which the statement's owner calls before anything renders\n * it (rendering a fragment keeps its text, {@link Sql.peek} does not).\n */\nexport class SqlSlot extends Sql {\n constructor(provisional: Sql) {\n super([\"\", \"\"], [provisional]);\n }\n settle(content: Sql): void {\n SqlSlot.fill(this, content);\n }\n}\n","/**\n * The engine's decimal seam: every place Raptor 3 hands a value to the\n * central decimal codec, in one decimal-named module.\n *\n * The codec owns what an exact decimal is. This module owns what the engine\n * adds when it asks: which codec entry a traversal takes (a bound literal, a\n * list member, a widened `_sum`, an internal or a public result), the\n * provider's representation with its one default, and the engine's sentence\n * for a value the codec refuses. The query owner reaches the codec only\n * through here, so the census that reads every decimal module in full reads\n * this one, and the owner's integer, date and JSON readers stay outside a\n * decimal region — the shape the retired engine kept with its\n * `decimal-result-decode` and `decimal-field` modules.\n */\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { QueryEngineError } from \"@errors\";\nimport type { ScalarState } from \"@schema/scalars/common\";\nimport {\n canonicalizeDecimal,\n type DecimalDescriptor,\n decodePhysicalDecimal,\n decodePhysicalDecimalList,\n decodePhysicalWidenedSum,\n encodePhysicalDecimalListMembers,\n logicalToCoefficient,\n materializePhysicalDecimal,\n materializePhysicalWidenedSum,\n sameDecimalDescriptor,\n toDecimal,\n} from \"@validation/primitives/decimal-codec\";\n\nexport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\n\n/** The provider's result contract, where its decimal spellings are declared. */\ntype ResultContract = DatabaseAdapter[\"result\"];\n\n/**\n * The declared domain of an exact decimal COLUMN, or `undefined` when the state\n * is not one. A list answers `undefined`: its members live in a container and\n * the scalar comparison this domain governs is not one a list has.\n */\nexport function exactDecimalDomain(\n state: ScalarState\n): DecimalDescriptor | undefined {\n return state.type === \"decimal\" && state.array !== true\n ? state.decimal\n : undefined;\n}\n\n/** The declared domain a decimal field must carry before a value can bind. */\nexport function requireDecimal(\n state: ScalarState,\n field: string\n): DecimalDescriptor {\n if (!state.decimal)\n throw new QueryEngineError(\n `Decimal field '${field}' has no declared precision and scale, so it has no exact value to bind.`\n );\n return state.decimal;\n}\n\n/** One bound decimal, canonical, or the binder's refusal. */\nexport function canonicalDecimal(value: unknown, field: string): string {\n const canonical = canonicalizeDecimal(value);\n if (canonical === undefined)\n throw new QueryEngineError(\n `Decimal field '${field}' received a value that is not an exact decimal.`\n );\n return canonical;\n}\n\n/** The members of a bound decimal list, in the provider's list spelling. */\nexport function decimalMembers(\n state: ScalarState,\n values: readonly unknown[],\n field: string,\n result: ResultContract\n): string[] {\n const members = encodePhysicalDecimalListMembers(\n values,\n requireDecimal(state, field),\n result.decimalListRepresentation ?? \"text\"\n );\n if (members === undefined)\n throw new QueryEngineError(\n `Decimal list '${field}' received a member that is not an exact decimal.`\n );\n return members;\n}\n\n/** Whether an arithmetic operand is the exact zero no provider may divide by. */\nexport function dividesByZero(by: unknown): boolean {\n return canonicalizeDecimal(by) === \"0\";\n}\n\n/** Two exact decimal columns compare only in one declared domain. */\nexport function sameDecimalDomain(\n own: DecimalDescriptor,\n other: DecimalDescriptor\n): boolean {\n return sameDecimalDescriptor(own, other);\n}\n\n/**\n * A `having` `_sum` operand: its canonical form and its coefficient at the\n * domain's scale, or `undefined` when the value is not an exact decimal.\n */\nexport function decimalSumOperand(\n value: unknown,\n domain: DecimalDescriptor\n): { readonly canonical: string; readonly coefficient: string } | undefined {\n const canonical = canonicalizeDecimal(value);\n if (canonical === undefined) return undefined;\n return {\n canonical,\n coefficient: logicalToCoefficient(canonical, domain.scale),\n };\n}\n\n/**\n * One decimal result cell: a widened `_sum` keeps the field scale and drops\n * its precision; an internal read keeps the codec's form, a public one\n * materializes the Decimal. `undefined` is the codec's refusal.\n */\nexport function decodeDecimalScalar(\n value: unknown,\n descriptor: DecimalDescriptor,\n widened: boolean,\n internal: boolean,\n result: ResultContract\n): unknown {\n const representation = result.decimalRepresentation ?? \"text\";\n if (widened)\n return internal\n ? decodePhysicalWidenedSum(value, descriptor, representation)\n : materializePhysicalWidenedSum(value, descriptor, representation);\n return internal\n ? decodePhysicalDecimal(value, descriptor, representation)\n : materializePhysicalDecimal(value, descriptor, representation);\n}\n\n/** One decimal list result cell; `undefined` is the codec's refusal. */\nexport function decodeDecimalList(\n value: unknown,\n descriptor: DecimalDescriptor,\n internal: boolean,\n result: ResultContract\n): unknown[] | undefined {\n const members = decodePhysicalDecimalList(\n value,\n descriptor,\n result.decimalListRepresentation ?? \"text\"\n );\n if (members === undefined) return undefined;\n return internal ? members : members.map((member) => toDecimal(member));\n}\n","/**\n * The engine's identifier seam: every place Raptor 3 hands a value to the\n * identifier codec, in one identifier-named module — the sibling of\n * `decimal.ts`, and for the same reason.\n *\n * Two facts, asked together because no seam needs one without the other. The\n * DOMAIN — declared by a named format, or derived by L5 from the key a foreign\n * key references — says which strings a column holds and what their canonical\n * spelling is (`idDomainOf`). The REPRESENTATION says what the column\n * physically holds for one, and it is the ADAPTER's answer\n * (`result.idRepresentation`, derived from the one storage owner\n * `idStorageOf`): `bytea` on PostgreSQL and `BINARY(16)` on MySQL are the same\n * ULID, and the engine is not allowed to know which dialect it is building for.\n *\n * This module knows no format's bytes and spells no SQL of its own: the codec\n * (`validation/primitives/id-codec.ts`) owns the bytes, and every expression\n * below is an adapter member. A field with no domain answers `undefined` from\n * {@link identifierColumn}, and every path stays the one it was.\n */\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport type { AnyModel } from \"@schema/model\";\nimport { idDomainOf } from \"@schema/validation/id-domains\";\nimport type { ResolvedRelationIndex } from \"@schema/validation/relation-resolution\";\nimport type { Sql } from \"@sql\";\nimport {\n decodePhysicalId,\n describeIdDomain,\n encodePhysicalId,\n type IdDomain,\n type IdRepresentation,\n sameIdDomain,\n} from \"@validation/primitives/id-codec\";\nimport type { PhysicalField } from \"./storage\";\n\n/** One identifier column: what it admits, and what it physically holds. */\nexport interface IdentifierColumn {\n readonly domain: IdDomain;\n readonly representation: IdRepresentation;\n}\n\n/**\n * The domain and representation of one stored column, or `undefined` when it\n * holds no identifier domain.\n *\n * A declared scalar is its own key. A PRIVATE column — a polymorphic row\n * carrier's id column — holds no field of its own: it holds some model key's\n * values, and that key's domain may be DERIVED (the one-to-one child whose\n * primary key is its parent foreign key), and derivation is keyed by (model,\n * field), never by a scalar instance two models may share. So the private\n * column NAMES the key it stands in for (`PhysicalField.reference`) and is\n * resolved through the same lookup, against that key; the type discriminator\n * names none. A junction side needs no such name: every binding of it already\n * goes through the referenced key (`Queries.junctionWhere`).\n */\nexport function identifierColumn(\n adapter: DatabaseAdapter,\n index: ResolvedRelationIndex,\n model: AnyModel,\n field: string,\n physical: PhysicalField\n): IdentifierColumn | undefined {\n const key =\n model[\"~\"].state.scalars[field] === undefined\n ? physical.reference\n : { model, field };\n if (key === undefined) return undefined;\n const domain = idDomainOf(key.model, key.field, index);\n if (domain === undefined) return undefined;\n const representation =\n adapter.result.idRepresentation?.(\n domain,\n key.model[\"~\"].state.scalars[key.field]?.[\"~\"].nativeType\n ) ?? \"text\";\n return { domain, representation };\n}\n\n/**\n * Whether the column holds something other than the public string itself —\n * payload bytes, or a PostgreSQL `uuid`. A text-stored domain is NOT compact:\n * it binds, projects, collates and aggregates exactly as any string column.\n */\nexport function isCompact(\n column: IdentifierColumn | undefined\n): column is IdentifierColumn {\n return column !== undefined && column.representation !== \"text\";\n}\n\n/**\n * The physical value ONE compact identifier binds as.\n *\n * INVARIANT, not a refusal (N4): every value that reaches a binding of an\n * identifier column crossed the field's validation schema, which admitted and\n * canonicalized it into the domain — a payload, a `{ set }`, a filter operand,\n * a cursor, a unique selector, a connect key — or is a captured row key, which\n * the decoder returned as the canonical public string. A `Sql` operand never\n * reaches here: it is the caller's physical fragment.\n */\nexport function encodeIdentifier(\n column: IdentifierColumn,\n value: unknown\n): string | Uint8Array {\n return encodePhysicalId(\n value as string,\n column.domain,\n column.representation\n )!;\n}\n\n/** The public string one physical identifier value stands for, or `undefined`. */\nexport function decodeIdentifier(\n column: IdentifierColumn,\n value: unknown\n): string | undefined {\n return decodePhysicalId(value, column.domain, column.representation);\n}\n\n/**\n * One compact identifier expression, spelled for TRANSPORT: lowercase hex for\n * a byte column, the column itself otherwise.\n *\n * A byte column travels as hex in a flat select exactly as inside a JSON\n * carrier. JSON cannot hold binary at all, so the carrier has no choice;\n * making the flat read take the same spelling keeps ONE physical promise per\n * column — the decoder reads the same text whether the row came back from a\n * top-level select or three levels inside an `include`, and the drivers' many\n * binary shapes stop being a variable.\n *\n * `nullable` is a fact about the EXPRESSION, not only about the column: a\n * `MIN()` over no rows is null however the column is declared. The guard is a\n * measured requirement, not symmetry: SQLite's `hex(NULL)` is the EMPTY\n * STRING, so without it a null identifier reads as a zero-byte one.\n */\nexport function transportedIdentifier(\n adapter: DatabaseAdapter,\n column: IdentifierColumn | undefined,\n expression: Sql,\n nullable: boolean\n): Sql {\n if (column?.representation !== \"bytes\") return expression;\n const hex = adapter.expressions.blobToHex(expression);\n return nullable\n ? adapter.expressions.caseWhen(\n [\n {\n when: adapter.operators.isNull(expression),\n then: adapter.literals.null(),\n },\n ],\n hex\n )\n : hex;\n}\n\n/**\n * What `MIN`/`MAX` run OVER for one compact identifier: its transported TEXT.\n *\n * Two facts force it, either alone decisive: PostgreSQL has no `min(uuid)`\n * and no `max(bytea)`, and JSON — the aggregate carrier — cannot hold binary.\n * The answer is the same: every compact format's canonical text is\n * fixed-width and lowercase, so its text order IS its byte order. The null\n * guard travels INSIDE the aggregate, where SQLite's `hex(NULL)` would\n * otherwise be the empty string that wins every `MIN`.\n */\nexport function aggregatedIdentifier(\n adapter: DatabaseAdapter,\n column: IdentifierColumn | undefined,\n expression: Sql\n): Sql {\n if (column?.representation === \"uuid\")\n return adapter.expressions.cast(expression, \"text\");\n return transportedIdentifier(adapter, column, expression, true);\n}\n\n/** One phrase naming a column's identifier storage, for the refusal below. */\nfunction describeStorage(column: IdentifierColumn | undefined): string {\n if (column === undefined) return \"plain string text\";\n const stored =\n column.representation === \"text\"\n ? \"as its own text\"\n : column.representation === \"uuid\"\n ? \"as a uuid payload\"\n : \"as payload bytes\";\n return `${describeIdDomain(column.domain)}, stored ${stored}`;\n}\n\n/**\n * The comparability of two columns a FIELD REFERENCE puts side by side, or\n * the refusal's sentence when one public value would not have one physical\n * spelling in both.\n *\n * Admission cannot ask it: the interned filter schemas are model-blind and\n * see two strings. Two text columns compare whatever their domains — each\n * holds the whole public string — and two compact columns compare only inside\n * one domain in one storage.\n */\nexport function incomparableIdentifiers(\n own: IdentifierColumn | undefined,\n other: IdentifierColumn | undefined,\n ownField: string,\n otherField: string\n): string | undefined {\n const representation = own?.representation ?? \"text\";\n if (representation === (other?.representation ?? \"text\")) {\n if (representation === \"text\") return undefined;\n if (sameIdDomain(own?.domain, other?.domain)) return undefined;\n }\n return (\n `'${ownField}' is ${describeStorage(own)} and '${otherField}' is ` +\n `${describeStorage(other)}. Two columns compare only when one value has the ` +\n \"same physical spelling in both.\"\n );\n}\n","import type { VibSchema } from \"../types\";\nimport { isRecord } from \"../value-guards\";\nimport { createSchema, fail, ok } from \"./helpers\";\n\n// =============================================================================\n// Raw Record Schema (identity-preserving object leaf)\n// =============================================================================\n\nexport interface RawRecordSchema\n extends VibSchema<Record<string, unknown>, Record<string, unknown>> {\n readonly type: \"rawRecord\";\n}\n\n/**\n * An object leaf that asserts OBJECT-NESS and NOTHING ELSE, and hands the SAME\n * object back — `output === input`, by reference.\n *\n * Every other object leaf in this layer is a transform: {@link object} materializes a\n * new record from its per-key validators, {@link record} rebuilds one from validated\n * entries. That is right wherever the schema owns the value's shape. It is wrong\n * wherever a schema must assert the shape of a payload some OTHER parse still owns —\n * and `upsert` is that case: its `create` / `update` arms are handed to\n * `CreateOperation` / `UpdateOperation` sub-ops which parse the RAW payload FRESH, so\n * the envelope must not have transformed it on the way past. Re-parsing a transformed\n * payload regresses on any non-idempotent transform (measured: a nested `createMany`\n * whose second parse answers `Expected string`).\n *\n * Reference equality is the property, not an implementation detail: it is what makes\n * \"validate the envelope\" and \"leave the arms alone\" the same sentence. It is asserted\n * directly, and a copy — however faithful — fails that assertion.\n *\n * The rejected shapes carry the SAME NAMED FACT as {@link record}'s own type check,\n * word for word, so the two object leaves cannot describe the same wrong input two\n * ways: `Expected object, received array` for an array, and the `typeof` for anything\n * else (`null` reads as `object`, exactly as `record` reports it — the two leaves are\n * wrong together or right together, never split).\n *\n * `undefined` is rejected here, and the enclosing {@link object} never asks: an\n * explicitly-`undefined` key is treated as ABSENT on every path (the Prisma-parity\n * dense-path rule), so a required key spelled `undefined` answers `Missing required\n * field: <key>` from the object schema and an optional one is simply skipped. This\n * leaf therefore sees a value only when the payload really carries one.\n */\nexport interface AnyValueSchema extends VibSchema<unknown, unknown> {\n readonly type: \"anyValue\";\n}\n\n/**\n * The other identity leaf: it accepts ANY value and hands it back unchanged.\n *\n * A STRICT object schema needs an entry for every key it admits, and an ENVELOPE\n * schema admits keys whose values a LATER schema owns. `upsert`'s five optional keys\n * are exactly that: `select` / `include` / `omit` are validated one step on by the\n * projection schema (which owns how `omit` composes with `select`),\n * and `targetWhere` / `setWhere` by the conditional-filter parse. Declaring them here\n * with a shape of their own would MOVE those decisions, not remove them — measured:\n * a non-object `targetWhere` is accepted today, and an object leaf here would start\n * refusing it.\n *\n * So this leaf admits the KEY and owns nothing about the VALUE. What it buys is the\n * unknown-key rejection the strict object gives the envelope, with no other change.\n */\nexport function anyValue(): AnyValueSchema {\n return createSchema<unknown, unknown>(\"anyValue\", (input) =>\n ok(input)\n ) as AnyValueSchema;\n}\n\nexport function rawRecord(): RawRecordSchema {\n return createSchema<Record<string, unknown>, Record<string, unknown>>(\n \"rawRecord\",\n (input) => {\n if (!isRecord(input)) {\n return fail(\n `Expected object, received ${\n Array.isArray(input) ? \"array\" : typeof input\n }`\n );\n }\n return ok(input);\n }\n ) as RawRecordSchema;\n}\n","import { ValidationError } from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport { type InferOutput, parse, type VibSchema } from \"@validation\";\nimport { readValidationFailureCause } from \"@validation/parse-failure\";\n// The two leaves below are imported from their own modules rather than through the `v`\n// namespace: this module is a transitive dependency of the schema builder, and the\n// barrel is what the recorded import cycle runs through.\nimport { object } from \"@validation/primitives/object\";\nimport { anyValue, rawRecord } from \"@validation/primitives/raw-record\";\nimport type { Operation } from \"../../types\";\n\n/**\n * THE typed parse boundary (X2 — one home for validation). Every seam that turns a\n * user payload (or a sub-payload: a `where`, a `select`, a nested `create`) into a\n * validated value flows through here. It runs the schema, converts a validation\n * failure into V1's byte-identical {@link ValidationError} (operation name +\n * dotted issue path), and returns the schema's INFERRED output type — the `TOutput`\n * the `ObjectSchema` already computes — instead of erasing it to\n * `Record<string, unknown>`.\n *\n * The lone `as InferOutput<S>` below is the ONLY assertion the engine needs and the\n * ONLY one allowed outside a genuinely untyped I/O edge: after the issues guard the\n * schema has PROVEN `value` matches `S`, but `parse`'s conditional result type keeps\n * `value` erased, so the inferred output is re-attached here — the one place\n * inference cannot reach on its own. This is what makes the in-engine re-validation\n * branches (the `isRecord(result.value)` / `requireRecord` / `requires a … object`\n * guards this boundary replaced) dead: the schema layer already guarantees the shape.\n * The structural gate (parse-boundary-gate.core.test.ts) fails loudly if a future phase\n * reintroduces such a branch or an `as Record<string, unknown>` on a validated path.\n *\n * @param schema a concrete operation/core schema (its `TOutput` is the return type)\n * @param value the raw payload to validate\n * @param operation the operation name carried on the {@link ValidationError}\n * @param path the dotted prefix for issue paths (\"\" for a whole-args validate;\n * a field name like \"where\"/\"select\"/\"createMany\" for a sub-payload)\n * @param model the model the operation addresses, named in the error's\n * `meta.model`, its source and its message subject (`user.create`)\n */\nexport function parseValidated<S extends VibSchema>(\n schema: S,\n value: unknown,\n operation: Operation,\n path: string,\n model: AnyModel\n): InferOutput<S> {\n const result = parse(schema, value);\n if (result.issues) {\n const prefix = path ? [path] : [];\n throw new ValidationError(\n operation,\n result.issues.map((issue) => ({\n path:\n [...prefix, ...(issue.path?.map(String) ?? [])].join(\".\") || \"root\",\n message: issue.message,\n })),\n {\n cause: readValidationFailureCause(result),\n meta: { model: model[\"~\"].names.ts! },\n }\n );\n }\n return result.value as InferOutput<S>;\n}\n\n/**\n * The `upsert` ENVELOPE, and only the envelope.\n *\n * `upsert` was the one write operation whose front line lived in the engine: a key gate\n * (`assertUpsertKeys`) plus three `requireRecord` narrowings. X2 kept them deliberately,\n * and its two reasons were sound — but both are about the ARMS, not the envelope:\n *\n * · the arms are handed to `CreateOperation` / `UpdateOperation` sub-ops that parse the\n * RAW payload FRESH, so a schema that TRANSFORMED them on the way past would make the\n * second parse see the first parse's output (measured: a nested `createMany` whose\n * re-parse answers `Expected string`);\n * · an untaken arm's content must not run arm-specific validation, so a schema\n * that descended into the arms would reject trees that never execute.\n *\n * This schema does neither. It is MODEL-BLIND — three required keys, five optional ones,\n * the object-ness of the three, and nothing else. No transform (the arms come back by\n * REFERENCE through {@link rawRecord}), no descent (the arms' contents are unread), and\n * no shape for the optional five ({@link anyValue}), whose own schemas own them one step\n * later. What is left is a SHAPE CHECK, and a shape check has one home.\n *\n * The key set mirrors the deleted `assertUpsertKeys` exactly, including the five optional\n * names. `cache` is absent from both: the client strips it before the engine\n * (`client.ts`), so it never arrives.\n */\nexport const upsertEnvelopeSchema = object(\n {\n where: rawRecord(),\n create: rawRecord(),\n update: rawRecord(),\n select: anyValue(),\n include: anyValue(),\n omit: anyValue(),\n targetWhere: anyValue(),\n setWhere: anyValue(),\n },\n { atLeast: [\"where\", \"create\", \"update\"] }\n);\n","import type { AnyModel } from \"@schema/model\";\nimport type { ClearableMembership } from \"@schema/relation/clearability\";\nimport type { ResolvedJunctionSide } from \"@schema/relation/junction-topology\";\nimport type { PolymorphicStorageColumn } from \"@schema/relation/polymorphic\";\nimport type { RelationSlot } from \"@schema/relation/types\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport type {\n ResolvedSlot,\n ResolvedStoredReference,\n} from \"@schema/validation/relation-resolution\";\nimport type { RowJudgement } from \"./row-scope\";\nimport type { EngineSchema } from \"./schema\";\n\nexport type Membership = {\n scope: Pick<ResolvedSlot, \"edge\" | \"member\">;\n clearability: ClearableMembership;\n name: string;\n source: AnyModel;\n target: AnyModel;\n many: boolean;\n discriminator?: { side: \"source\" | \"target\"; field: string; value: string };\n} & (\n | {\n kind: \"reference\";\n owner: \"source\" | \"target\";\n pairs: readonly { source: string; target: string }[];\n reference?: ResolvedStoredReference;\n }\n | {\n kind: \"junction\";\n table: string;\n sourceSide: ResolvedJunctionSide;\n targetSide: ResolvedJunctionSide;\n uniqueSide?: \"source\" | \"target\";\n }\n);\n\nexport type PhysicalField = {\n readonly name: string;\n readonly scalar: Scalar;\n readonly nullable: boolean;\n /**\n * The KEY a private column stands in for — a polymorphic row carrier's id\n * column — which is what its identifier domain is resolved against\n * (`identifier.ts`). A declared scalar is its own key and carries none.\n */\n readonly reference?: PolymorphicStorageColumn[\"reference\"];\n};\n\n/**\n * What the row a link through `edge` reaches is judged at when the link\n * changes on it (R3): the key fields it holds and its own side of the\n * relation, so a join judges both endpoints, the source by its own data.\n * `undefined` where the source holds the key: the target's row does not\n * change, and is only read.\n */\nexport function linkJudgement(edge: Membership): RowJudgement | undefined {\n if (edge.kind === \"reference\" && edge.owner === \"source\") return undefined;\n const resolved = edge.scope.edge;\n const writes =\n edge.kind === \"reference\" && resolved.kind === \"foreignKey\"\n ? edge.pairs.map((pair) => pair.target)\n : [];\n const own = (slot: RelationSlot) =>\n slot.source === edge.source && slot.field === edge.name;\n const inverse =\n resolved.kind === \"foreignKey\" || resolved.kind === \"junction\"\n ? resolved.endpoints.find((end) => !own(end))\n : own(resolved.carrier)\n ? edge.scope.member?.inverse\n : resolved.carrier;\n if (inverse) writes.push(inverse.field);\n return { verb: \"update\", writes };\n}\n\n/** Orient the already resolved storage once; no declaration getter or inverse search. */\nexport function bindMembership(\n schema: EngineSchema,\n source: AnyModel,\n name: string,\n variant?: string\n): Membership {\n return schema.membership(source, name, variant);\n}\n\n/**\n * One variant-carrier member: the slot's own bound member, or the arm the\n * caller named. A carrier addressed with no variant names every arm at once,\n * which this one-membership view cannot represent; the caller addresses an arm\n * or composes the arms itself (g4/unit02/note.md §10.3).\n *\n * INVARIANT, not a refusal (N4 row 49). Every caller reads the slot first: a\n * bound inverse carries `resolved.member`, a carrier slot is walked arm by arm\n * over `edge.members`, and the one arm name a payload supplies is the tagged\n * grammar's `type`, which validation pins to a literal union of the configured\n * public variants before the engine sees it.\n */\nfunction variantMember<T>(resolved: T | undefined, tagged: T | undefined): T {\n return (resolved ?? tagged)!;\n}\n\nexport function buildMembershipView(\n schema: EngineSchema,\n source: AnyModel,\n name: string,\n variant?: string\n): Membership {\n const resolved = schema.index.get(source)!.get(name)!;\n const edge = resolved.edge;\n const clearability = schema.clearability(resolved);\n const many =\n source[\"~\"].state.relations[name]![\"~\"].state.cardinality === \"many\";\n if (edge.kind === \"variantRowCarrier\") {\n const member = variantMember(\n resolved.member,\n edge.members.find((member) => member.variant === variant)\n );\n const direct = resolved.member === undefined;\n return {\n scope: Object.freeze({ edge, member }),\n clearability,\n name: direct ? `${name}.${member.variant}` : name,\n source,\n many,\n target: direct ? member.targetModel : edge.carrier.source,\n kind: \"reference\",\n owner: direct ? \"source\" : \"target\",\n pairs: [\n {\n source: direct ? edge.storage.idColumn.name : member.referencedField,\n target: direct ? member.referencedField : edge.storage.idColumn.name,\n },\n ],\n discriminator: {\n side: direct ? \"source\" : \"target\",\n field: edge.storage.typeColumn.name,\n value: member.entry.storedValue,\n },\n };\n }\n if (edge.kind === \"variantJunctionCarrier\") {\n const member = variantMember(\n resolved.member,\n edge.members.find((member) => member.variant === variant)\n );\n const direct = resolved.member === undefined;\n return {\n scope: Object.freeze({ edge, member }),\n clearability,\n name: direct ? `${name}.${member.variant}` : name,\n source,\n many,\n target: direct\n ? member.topology.target.model\n : member.topology.source.model,\n kind: \"junction\",\n table: member.topology.table,\n sourceSide: direct ? member.topology.source : member.topology.target,\n targetSide: direct ? member.topology.target : member.topology.source,\n uniqueSide: member.uniqueTarget\n ? direct\n ? \"target\"\n : \"source\"\n : undefined,\n };\n }\n const endpoint = edge.endpoints[0];\n const opposite =\n endpoint.source === source && endpoint.field === name\n ? edge.endpoints[1]\n : endpoint;\n const base = {\n scope: resolved,\n clearability,\n name,\n source,\n target: opposite.source,\n many,\n };\n if (edge.kind === \"foreignKey\") {\n const owns = edge.owner.source === source && edge.owner.field === name;\n return {\n ...base,\n kind: \"reference\",\n owner: owns ? \"source\" : \"target\",\n reference: edge.reference,\n pairs: edge.reference.members.map((pair) => ({\n source: owns ? pair.foreignField : pair.referencedField,\n target: owns ? pair.referencedField : pair.foreignField,\n })),\n };\n }\n const topology = edge.topology;\n // The SLOT decides, not the model: a self junction names one model on both\n // sides and only its two fields tell the directions apart. `opposite` above\n // already resolved that identity, and `endpoints[0]`/`endpoints[1]` are the\n // slots `topology.source`/`topology.target` were built from.\n const forward = opposite === edge.endpoints[1];\n return {\n ...base,\n kind: \"junction\",\n table: topology.table,\n sourceSide: forward ? topology.source : topology.target,\n targetSide: forward ? topology.target : topology.source,\n };\n}\n\nexport function freezeMembershipView(view: Membership): Membership {\n if (view.kind === \"reference\") {\n for (const pair of view.pairs) Object.freeze(pair);\n Object.freeze(view.pairs);\n if (view.discriminator) Object.freeze(view.discriminator);\n }\n return Object.freeze(view);\n}\n\n/** Private carrier columns are resolved schema fields, never public scalar declarations. */\nexport function physicalField(\n schema: EngineSchema,\n model: AnyModel,\n field: string\n): PhysicalField {\n return schema.physicalField(model, field);\n}\n\n/**\n * The private `(type, id)` columns this model's variant ROW carriers store, in\n * declaration order. ONE enumeration of them, so what a field resolves to and\n * what {@link buildStoredFieldsView} says the row stores cannot drift apart.\n */\nfunction carrierColumns(\n schema: EngineSchema,\n model: AnyModel\n): PolymorphicStorageColumn[] {\n const columns: PolymorphicStorageColumn[] = [];\n for (const { edge, member } of schema.index.get(model)!.values())\n if (edge.kind === \"variantRowCarrier\" && !member)\n columns.push(edge.storage.typeColumn, edge.storage.idColumn);\n return columns;\n}\n\n/**\n * INVARIANT, not a refusal (N4 row 48): a model stores its declared scalars and\n * its row carriers' columns, and nothing asks this owner for anything else. A\n * field name arrives from admission, which matched it against the model's\n * declared scalar keys, or from the resolved topology itself — a membership\n * pair, a carrier discriminator, a junction side's referenced field, a row key,\n * or {@link buildStoredFieldsView}, which enumerates exactly those two sets.\n */\nexport function buildPhysicalFieldView(\n schema: EngineSchema,\n model: AnyModel,\n field: string\n): PhysicalField {\n const scalar = model[\"~\"].state.scalars[field];\n if (scalar)\n return {\n name: model[\"~\"].getFieldName(field).sql,\n scalar,\n nullable: scalar[\"~\"].state.nullable === true,\n };\n return carrierColumns(schema, model).find(\n (candidate) => candidate.name === field\n )!;\n}\n\nexport function storedFields(\n schema: EngineSchema,\n model: AnyModel\n): readonly string[] {\n return schema.storedFields(model);\n}\n\nexport function buildStoredFieldsView(\n schema: EngineSchema,\n model: AnyModel\n): string[] {\n return [\n ...model[\"~\"].scalarFieldNames,\n ...carrierColumns(schema, model).map((column) => column.name),\n ];\n}\n","import type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport type { AnyDriver } from \"@drivers/exports\";\nimport { UnsupportedOperationError } from \"@errors\";\nimport { hydrateSchemaNames, type Schema } from \"@schema/hydration\";\nimport { type AnyModel, getModelKeyCatalog } from \"@schema/model\";\nimport {\n type ClearableMembership,\n clearableMembership,\n} from \"@schema/relation/clearability\";\nimport { resolveSchemaOrThrow } from \"@schema/validation\";\nimport {\n foreignKeyOnDelete,\n junctionOnDelete,\n type ResolvedSlot,\n} from \"@schema/validation/relation-resolution\";\nimport { createResolvedSchemaRegistry } from \"@validation/builder\";\nimport type { NormalizedRecurrence } from \"@validation/relations/recurrence\";\nimport type { VibSchema } from \"@validation/types\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { parseValidated, upsertEnvelopeSchema } from \"./parse-boundary\";\nimport type { Leaf, PreparedProjection } from \"./query\";\nimport {\n buildMembershipView,\n buildPhysicalFieldView,\n buildStoredFieldsView,\n freezeMembershipView,\n type Membership,\n type PhysicalField,\n} from \"./storage\";\n\nexport type Input = Record<string, unknown>;\nexport type ReadOperation =\n | \"findMany\"\n | \"findUnique\"\n | \"findFirst\"\n | \"count\"\n | \"exist\"\n | \"aggregate\"\n | \"groupBy\";\nexport type Operation =\n | \"create\"\n | \"createMany\"\n | \"update\"\n | \"upsert\"\n | \"updateMany\"\n | \"delete\"\n | \"deleteMany\"\n | ReadOperation;\n\nconst READ_OPERATIONS: ReadonlySet<string> = new Set<ReadOperation>([\n \"findMany\",\n \"findUnique\",\n \"findFirst\",\n \"count\",\n \"exist\",\n \"aggregate\",\n \"groupBy\",\n]);\n\n/** One classification of an admitted operation; a read allocates no write work. */\nexport function isReadOperation(\n operation: Operation\n): operation is ReadOperation {\n return READ_OPERATIONS.has(operation);\n}\n/**\n * The client's already-resolved schema views. A client that composed them once\n * hands them over by identity; the candidate never re-hydrates or re-validates\n * a schema a caller already resolved (g4/unit03/note.md B-3).\n */\nexport interface ResolvedSchemaViews {\n readonly index: ReturnType<typeof resolveSchemaOrThrow>;\n /**\n * Declared as the one member {@link EngineSchema} reads. A client hands over\n * its full resolved registry; anything carrying `getModelSchemas` satisfies\n * this, nothing is widened, and no consumer here reads `proxy`.\n */\n readonly registry: Pick<\n ReturnType<typeof createResolvedSchemaRegistry>,\n \"getModelSchemas\"\n >;\n}\nexport interface EngineConfig {\n schema: Schema;\n driver: AnyDriver;\n resolved?: ResolvedSchemaViews;\n}\nexport interface Arguments extends Input {\n data: Input;\n create?: Input;\n update?: Input;\n where?: Input;\n targetWhere?: Input;\n setWhere?: Input;\n select?: Input;\n include?: Input;\n orderBy?: Input | Input[];\n take?: number;\n skip?: number;\n cursor?: Input;\n distinct?: string[];\n by?: string[];\n having?: Input;\n limit?: number;\n omit?: Input;\n recurse?: NormalizedRecurrence;\n skipDuplicates?: boolean;\n _count?: true | Input;\n _avg?: Input;\n _sum?: Input;\n _min?: Input;\n _max?: Input;\n}\n\n/**\n * The two update operators whose result a provider ROUNDS — the ones an exact\n * decimal row key cannot carry portably, and the ones phase 2 made reachable.\n */\nconst ROUNDING_KEY_UPDATES: readonly string[] = [\"multiply\", \"divide\"];\n\n/**\n * Every operation a key update may name, in the shipped engine's own order\n * (`operations/mutation-identity.ts` `assertPortablePrimaryKeyUpdateInput`),\n * because the refusal sentence lists them in it.\n */\nconst KEY_UPDATE_OPERATIONS = [\n \"set\",\n \"increment\",\n \"decrement\",\n \"multiply\",\n \"divide\",\n] as const;\n\n/** These casts attach the existing admission schema's dynamic model correlation. */\nexport function record(value: unknown): Input {\n return value as Input;\n}\nexport function entries(value: unknown): Input[] {\n return Array.isArray(value) ? value : [record(value)];\n}\n/** `key`'s view in `views`, created on its first use and kept as long as `views`. */\nexport function memo<K, V>(\n views: { get(key: K): V | undefined; set(key: K, value: V): unknown },\n key: K,\n create: () => V\n): V {\n let view = views.get(key);\n if (view === undefined) {\n view = create();\n views.set(key, view);\n }\n return view;\n}\n\n/**\n * What this engine resolves once per (adapter, model) and never again.\n *\n * Both members are a pure function of the schema and the dialect, which is why\n * they may be shared at all (rule 1): a scalar leaf is the field's declared\n * type, nullability and the adapter's own `dateTime` representation; the\n * DEFAULT projection is `scalarFieldNames` minus the model's own `omit`, and an\n * operation-level `omit` never reaches the projection owner — admission\n * desugars it into `select`, which takes the per-operation path. Nothing\n * admitted and nothing a provider answered is stored (rule 5).\n *\n * The two member types are the query owner's, imported for their names only:\n * `import type` adds no runtime edge, so `shared/query.ts` keeps its one\n * runtime import of this file and this file keeps none of it.\n */\nexport type QueryViews = {\n readonly leaves: WeakMap<AnyModel, Map<string, Leaf>>;\n readonly defaultProjections: WeakMap<AnyModel, PreparedProjection>;\n};\n\nconst createQueryViews = (): QueryViews => ({\n leaves: new WeakMap(),\n defaultProjections: new WeakMap(),\n});\n\nexport class EngineSchema {\n readonly index;\n readonly registry;\n readonly #membershipViews = new WeakMap<\n AnyModel,\n Map<string, Map<string | undefined, Membership>>\n >();\n readonly #physicalFields = new WeakMap<\n AnyModel,\n Map<string, PhysicalField>\n >();\n readonly #storedFieldLists = new WeakMap<AnyModel, readonly string[]>();\n readonly #clearabilityViews = new WeakMap<\n ResolvedSlot,\n ClearableMembership\n >();\n readonly #restrictingSlotViews = new WeakMap<AnyModel, readonly string[]>();\n readonly schema: Schema;\n constructor(schema: Schema, resolved?: ResolvedSchemaViews) {\n this.schema = schema;\n if (resolved) {\n this.index = resolved.index;\n this.registry = resolved.registry;\n return;\n }\n hydrateSchemaNames(schema);\n this.index = resolveSchemaOrThrow(schema);\n this.registry = createResolvedSchemaRegistry(schema, this.index);\n }\n admit(model: AnyModel, operation: Operation, raw: unknown): Arguments {\n const admitted =\n operation === \"upsert\"\n ? this.#upsert(model, raw)\n : this.#admitArguments(model, operation, raw);\n // WHERE the shipped engine states the key's portability contract, mirrored:\n // `update`/`updateMany` assert at admission (`assertPortablePrimaryKeyUpdateInput`\n // from their own validator); an `upsert` asserts on its FOUND arm and only\n // when the update payload names relations, which `Commands` attaches there.\n if (operation === \"update\" || operation === \"updateMany\") {\n const refusal = this.keyPortabilityRefusal(model, admitted.data);\n if (refusal) throw refusal;\n }\n return admitted;\n }\n #admitArguments(\n model: AnyModel,\n operation: Operation,\n raw: unknown\n ): Arguments {\n const schema = this.registry.getModelSchemas(model).args[operation];\n const input =\n operation === \"update\" && isRecord(raw) && isRecord(raw.data)\n ? {\n ...raw,\n data: Object.fromEntries(\n Object.entries(raw.data).sort(([left], [right]) => {\n const isVariant = (name: string) =>\n model[\"~\"].state.relations[name]?.[\"~\"].state.target.kind ===\n \"variants\";\n return Number(isVariant(left)) - Number(isVariant(right));\n })\n ),\n }\n : raw;\n return parseValidated(schema, input, operation, \"\", model) as Arguments;\n }\n /**\n * Does this payload name a relation of the model? One spelling, asked by the\n * upsert's create arm below and by the found-arm key-portability gate in\n * `commands.ts`.\n */\n namesRelation(model: AnyModel, data: Input): boolean {\n return model[\"~\"].relationNames.some((name) => data[name] !== undefined);\n }\n /**\n * The row key's PORTABILITY contract for the two operators phase 2 made\n * reachable, as one refusal the caller raises where the shipped engine raises\n * it — never a second walker, never a second sentence.\n *\n * A key's post-update value has to be NAMEABLE: a non-returning readback and\n * every dependent's key transition address the row by it. `multiply` and\n * `divide` carry a provider-chosen rounding on a `number` or `decimal` key\n * that no engine can name portably, and a `divide` by zero has no value at\n * all, so the shipped engine refuses both from its own validator\n * (`assertPortablePrimaryKeyUpdateInput`). Until phase 2 implemented the two\n * operators the candidate answered \"not implemented\" for every one of these\n * payloads; implementing them is what brought the shapes within reach, so the\n * refusals arrive with them, in the shipped engine's own sentences.\n *\n * WHAT it says is the shipped assertion with exactly ONE adopted divergence,\n * R-D2 (a) (Arnaud, 2026-09-15): an EXACT-DOMAIN arithmetic update of a\n * `decimal` key — `increment` / `decrement` — is supported, because it is\n * exact in coefficient space, and the registered G3 witness\n * `tests/raptor3/g3/review-execution-boundaries.test.ts` pins that capability.\n * `multiply` / `divide` on the same key still carry the provider's rounding,\n * so they stay refused. Everything else is parity: R-D2 (b), a `number` key\n * under any arithmetic, and R-D2 (c), `set` beside another operation, answer\n * the shipped sentences (they used to be divergences, pinned on both engines;\n * the decision reverted them). The shipped non-finite-operand arm is\n * deliberately NOT mirrored — after the rules below it is reachable only for\n * an `int`/`bigint` key, whose validation refuses a non-finite operand, so it\n * would be a guard whose unique coverage cannot be named.\n *\n * WHERE it is raised belongs to each caller, because the shipped engine does\n * not raise it in one place: `admit` raises it for `update`/`updateMany`, and\n * the upsert's found arm carries it (`commands.ts`) exactly when the update\n * payload names relations — the shipped gate, note §R3.1. A wider placement\n * refuses requests the shipped engine performs, including an upsert that\n * CREATES a row the arithmetic never touches.\n */\n keyPortabilityRefusal(model: AnyModel, data: unknown): Error | undefined {\n if (!isRecord(data)) return undefined;\n for (const keyField of this.keys(model)) {\n const update = data[keyField];\n if (!isRecord(update)) continue;\n const named = KEY_UPDATE_OPERATIONS.filter(\n (operation) => update[operation] !== undefined\n );\n if (named.length !== 1)\n return new UnsupportedOperationError(\n `Primary key field '${keyField}' accepts exactly one update operation; received ${named.join(\", \") || \"none\"}.`\n );\n const operation = named[0]!;\n if (operation === \"set\") continue;\n const scalarType = model[\"~\"].state.scalars[keyField]?.[\"~\"].state.type;\n if (\n scalarType === \"number\" ||\n (scalarType === \"decimal\" && ROUNDING_KEY_UPDATES.includes(operation))\n )\n return new UnsupportedOperationError(\n `Arithmetic updates are not portable for ${scalarType} primary key field '${keyField}'. Use an explicit set value.`\n );\n if (update.divide === 0 || update.divide === 0n)\n return new UnsupportedOperationError(\n `Cannot divide primary key field '${keyField}' by zero.`\n );\n }\n return undefined;\n }\n /**\n * The key TRANSITION's own refusal — the shipped engine's THIRD key owner,\n * and a different question from {@link keyPortabilityRefusal}.\n *\n * A child-held relation written beside a key update forces the parent's\n * POST-transition key value to be named at ANALYSIS: the child rows this\n * payload writes reference it, and the compiler builds their FK before any\n * row is located. The shipped engine names it in\n * `RecordUpdateCompilerState.interpretReferencedKeyTransition`\n * (`write-engine/RecordUpdateCompiler.ts:3319` ->\n * `operations/mutation-identity.ts:357`), reached from the `UpsertOperation`\n * CONSTRUCTOR (`:480`) — so for an upsert it runs before either arm is\n * selected, and a payload whose post-value cannot be computed is refused\n * with the transition's own sentence rather than the validator's, before\n * either arm writes anything. Two payloads cannot be computed, and they are\n * the two `getSafeUpdatedScalarValue` refuses (`mutation-identity.ts:298`,\n * `:336`): a key naming anything other than exactly one operation, which is\n * R-D2 (c)'s `set`-beside-an-operator shape and answers `:187`'s sentence,\n * and a `divide` by zero, which has no value at all.\n *\n * Its three structural conditions are the shipped ones, measured\n * (`upsert-key-portability.test.ts`, the third describe):\n *\n * - the relation is CHILD-held and references the key being rewritten. That\n * fact is NOT re-derived here: the command tree already records it while it\n * expands the payload (`RelationBody.relation` ->\n * `RecordCommand.transitions`), and this method reads that list. A\n * parent-held relation beside the same `divide` builds no transition, and\n * both engines answer the validator's sentence;\n * - the reference key has exactly ONE member (`RecordUpdateCompiler.ts:3310`\n * `referencedFields.length === 1`, whose comment is explicit that \"a\n * compound one falls through to the per-member compile-time source rather\n * than borrowing member zero's answer\") — a compound reference key reaches\n * the validator's sentence on both engines;\n * - the locator's DISCRIMINATOR pins the pre-value as a literal, which is\n * what makes the transition nameable at analysis. `pinned` is the prepared\n * selector's `facts.keys` — the `key: true` columns, which are the shipped\n * `pinnedTargetValues` entries (`write-engine/shared.ts:154-166`) — never\n * its `facts.equals`, which also collects an extended `where`'s filter half\n * and its `AND`/`OR`/`NOT` arms.\n *\n * A payload naming exactly one computable operation — `set`, or an\n * arithmetic one the provider can carry — builds its transition and is not\n * this owner's business; the found arm's {@link keyPortabilityRefusal} is\n * what still judges the operator's portability, exactly as shipped.\n */\n keyTransitionRefusal(\n model: AnyModel,\n data: unknown,\n pinned: ReadonlyMap<string, unknown>,\n transitions: readonly Extract<Membership, { kind: \"reference\" }>[]\n ): Error | undefined {\n if (!isRecord(data)) return undefined;\n for (const keyField of this.keys(model)) {\n if (!pinned.has(keyField)) continue;\n const update = data[keyField];\n if (!isRecord(update)) continue;\n if (\n !transitions.some(\n (edge) =>\n edge.pairs.length === 1 && edge.pairs[0]!.source === keyField\n )\n )\n continue;\n const named = KEY_UPDATE_OPERATIONS.filter(\n (operation) => update[operation] !== undefined\n );\n if (named.length !== 1)\n return new UnsupportedOperationError(\n `Cannot determine the updated primary key for model '${model[\"~\"].names.ts!}' because field '${keyField}' uses an unsupported operation.`\n );\n if (update.divide === 0 || update.divide === 0n)\n return new UnsupportedOperationError(\n \"Cannot divide a primary key by zero.\"\n );\n }\n return undefined;\n }\n #upsert(model: AnyModel, raw: unknown): Arguments {\n const envelope = parseValidated(\n upsertEnvelopeSchema,\n raw,\n \"upsert\",\n \"\",\n model\n );\n const schemas = this.registry.getModelSchemas(model);\n const createHasRelations = this.namesRelation(model, envelope.create);\n const updateScalars = Object.fromEntries(\n Object.entries(envelope.update).filter(\n ([name]) => !model[\"~\"].relationNames.includes(name)\n )\n );\n const where = parseValidated(\n schemas.core.whereUniqueExtended,\n envelope.where,\n \"upsert\",\n \"where\",\n model\n );\n const scalarCreate = createHasRelations\n ? undefined\n : parseValidated(\n schemas.core.scalarCreate,\n envelope.create,\n \"upsert\",\n \"create\",\n model\n );\n const update = parseValidated(\n schemas.core.scalarUpdate,\n updateScalars,\n \"upsert\",\n \"update\",\n model\n );\n const projection = parseValidated(\n schemas.core.upsertProjection,\n {\n select: envelope.select,\n include: envelope.include,\n omit: envelope.omit,\n },\n \"upsert\",\n \"\",\n model\n );\n const conditions: Pick<Arguments, \"targetWhere\" | \"setWhere\"> = {\n targetWhere: undefined,\n setWhere: undefined,\n };\n for (const field of [\"targetWhere\", \"setWhere\"] as const) {\n const input = envelope[field];\n if (input === undefined) continue;\n const parsed = parseValidated(\n schemas.core.where,\n input,\n \"upsert\",\n field,\n model\n );\n if (isRecord(parsed) && Object.keys(parsed).length)\n conditions[field] = record(parsed);\n }\n const create = createHasRelations\n ? parseValidated(\n schemas.core.create,\n envelope.create,\n \"create\",\n \"data\",\n model\n )\n : scalarCreate;\n const admittedUpdate = this.update(\n model,\n envelope.update,\n false,\n record(update)\n );\n // Operation dispatch supplies the correlation: upsert owns create/update, not data.\n return record({\n ...envelope,\n ...record(projection),\n ...conditions,\n where,\n create,\n update: admittedUpdate,\n }) as Arguments;\n }\n /**\n * Scalar values admitted as a create admits them, field by field through\n * each field's own create schema: a partial source (the fields a stamp\n * writes), so the model's required fields are not asked for, and a field a\n * create takes but an update refuses (`s.dateTime().now()`) is admitted.\n */\n createValues(model: AnyModel, source: Input): Input {\n const scalars = this.registry.getModelSchemas(model).scalars as Record<\n string,\n { readonly create: VibSchema }\n >;\n const admitted: Input = {};\n for (const [field, value] of Object.entries(source))\n admitted[field] = parseValidated(\n scalars[field]!.create,\n value,\n \"create\",\n field,\n model\n );\n return admitted;\n }\n update(\n model: AnyModel,\n source: Input,\n captured: boolean,\n envelope?: Input\n ): Input {\n const schemas = this.registry.getModelSchemas(model);\n if (captured)\n return record(\n parseValidated(schemas.core.update, source, \"updateMany\", \"data\", model)\n );\n const admitted = { ...(envelope ?? source) };\n const names = Object.keys(source).filter((name) =>\n model[\"~\"].relationNames.includes(name)\n );\n const isVariant = (name: string) =>\n model[\"~\"].state.relations[name]![\"~\"].state.target.kind === \"variants\";\n // Admission phases are ordinary relations then carriers, retaining raw order within each.\n for (const name of names.sort(\n (a, b) => Number(isVariant(a)) - Number(isVariant(b))\n )) {\n if (source[name] !== undefined) {\n admitted[name] = parseValidated(\n (isVariant(name)\n ? schemas.polymorphic[name]!\n : schemas.relations[name]!\n ).update,\n source[name],\n \"update\",\n `data.${name}`,\n model\n );\n }\n }\n return admitted;\n }\n member(model: AnyModel, relation: string, source: Input): Input {\n const schema =\n this.registry.getModelSchemas(model).relations[relation]!.update;\n const parsed = record(\n parseValidated(\n schema,\n { updateMany: { data: source } },\n \"update\",\n `data.${relation}`,\n model\n )\n );\n return record(entries(parsed.updateMany)[0]!.data);\n }\n keys(model: AnyModel): readonly string[] {\n return getModelKeyCatalog(model).rowKey!.fields;\n }\n identity(model: AnyModel, row: Input): Input {\n return Object.fromEntries(\n this.keys(model).map((field) => [field, row[field]])\n );\n }\n membership(model: AnyModel, name: string, variant?: string): Membership {\n const modelViews = memo(this.#membershipViews, model, () => new Map());\n const slotViews = memo(modelViews, name, () => new Map());\n return memo(slotViews, variant, () =>\n freezeMembershipView(buildMembershipView(this, model, name, variant))\n );\n }\n /**\n * The slots through which the database refuses a hard delete of a `model` row\n * while a member exists: an incoming foreign key, or the junction key on this\n * model's side, whose ON DELETE is `restrict` or `noAction`. The actions are\n * the schema's own answer (`foreignKeyOnDelete`, `junctionOnDelete`), the one\n * the migration spells. A polymorphic carrier stores no constraint.\n */\n restrictingSlots(model: AnyModel): readonly string[] {\n return memo(this.#restrictingSlotViews, model, () => {\n const found: string[] = [];\n for (const [name, resolved] of this.index.get(model) ?? []) {\n const edge = resolved.edge;\n if (edge.kind !== \"foreignKey\" && edge.kind !== \"junction\") continue;\n const view = this.membership(model, name);\n const action =\n view.kind === \"junction\"\n ? junctionOnDelete(view.sourceSide)\n : edge.kind === \"foreignKey\" && view.owner === \"target\"\n ? foreignKeyOnDelete(edge)\n : undefined;\n if (action === \"restrict\" || action === \"noAction\") found.push(name);\n }\n return Object.freeze(found);\n });\n }\n clearability(resolved: ResolvedSlot): ClearableMembership {\n return memo(this.#clearabilityViews, resolved, () => {\n const view = clearableMembership(resolved);\n if (view.kind === \"columns\") Object.freeze(view.fields);\n return Object.freeze(view);\n });\n }\n physicalField(model: AnyModel, field: string): PhysicalField {\n let fields = this.#physicalFields.get(model);\n if (!fields) {\n fields = new Map();\n this.#physicalFields.set(model, fields);\n }\n let descriptor = fields.get(field);\n if (!descriptor) {\n descriptor = Object.freeze(buildPhysicalFieldView(this, model, field));\n fields.set(field, descriptor);\n }\n return descriptor;\n }\n /**\n * One adapter's {@link QueryViews}, created on its first use.\n *\n * `EngineSchema` already owns the lazy immutable per-model views this engine\n * resolves from the schema alone, but these two are also a fact of the\n * DIALECT — a scalar leaf carries the adapter's own `dateTime`\n * representation — and a `Queries` instance is per-operation for writes, so\n * neither owner alone can hold them. The adapter is the second key and it is\n * held weakly, so a view store lives exactly as long as the adapter it\n * describes. What it may hold is what every view here may hold: facts\n * derived from the schema and the dialect, never an admitted input, an\n * alias, an operation demand or a provider row (rule 5).\n *\n * The accessor names its one fact, like every other view on this class, so\n * the store cannot be reached for a second shape: an anonymous\n * `scope(adapter, create)` would hand a second caller the first caller's\n * object under the second caller's type, and the cast would hide it.\n */\n readonly #queryViewsByAdapter = new WeakMap<DatabaseAdapter, QueryViews>();\n queryViews(adapter: DatabaseAdapter): QueryViews {\n return memo(this.#queryViewsByAdapter, adapter, createQueryViews);\n }\n storedFields(model: AnyModel): readonly string[] {\n return memo(this.#storedFieldLists, model, () =>\n Object.freeze(buildStoredFieldsView(this, model))\n );\n }\n /**\n * The admitted payload's scalar fields, in the model's own scalar order.\n *\n * One pass into one object. The model's scalar order is already memoised by\n * the model itself (`schema/model/model.ts`, `_scalarFieldNames ??=`), so the\n * only per-call cost left was the three intermediates\n * `Object.fromEntries(names.filter(…).map(…))` built — on a normalization\n * every row of every `createMany` crosses (`g4/cutover/perf-diagnosis.md`\n * §4.2). Same keys, same order, same values.\n */\n scalars(model: AnyModel, admitted: Input): Input {\n const values: Input = {};\n for (const field of model[\"~\"].scalarFieldNames) {\n const value = admitted[field];\n if (value !== undefined) values[field] = value;\n }\n return values;\n }\n}\n","import type { ArithmeticTarget } from \"@adapters/adapter-core-types\";\nimport { assembleAdapterSelect } from \"@adapters/adapter-internals\";\nimport type { DatabaseAdapter, GeoPointSql } from \"@adapters/database-adapter\";\nimport type { DriverResultParser } from \"@drivers/exports\";\nimport {\n FeatureNotSupportedError,\n QueryEngineError,\n TransactionError,\n UnsupportedOperationError,\n ValidationError,\n VibORMError,\n} from \"@errors\";\nimport {\n DISTANCE_SELECTED_TWICE,\n selectedArm,\n} from \"@query-engine/result/result-shape\";\nimport {\n CURSOR_CARRIER_PREFIX,\n EMPTY_ROW_RESULT_KEY,\n gateResultKey,\n POLYMORPHIC_COLLECTION_ORPHANS_KEY,\n} from \"@query-engine/result-aliases\";\nimport { fieldRefPayload, formatFieldRef, isFieldRef } from \"@schema/field-ref\";\nimport { jsonNullKindOf } from \"@schema/json-null\";\nimport {\n type AnyModel,\n findAddressableKey,\n getModelKeyCatalog,\n type OrderedModelKey,\n} from \"@schema/model\";\nimport { slotMayBeEmpty } from \"@schema/relation/clearability\";\nimport type { ResolvedJunctionSide } from \"@schema/relation/junction-topology\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport type { ScalarState } from \"@schema/scalars/common\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport type {\n ResolvedSlot,\n ResolvedVariantEdge,\n} from \"@schema/validation/relation-resolution\";\nimport { Sql, sql } from \"@sql\";\nimport { projectableScalarNames } from \"@validation/model/core/projection\";\nimport { normalizeBinaryValue } from \"@validation/primitives/binary-shapes\";\nimport {\n type DateTimePhysicalForm,\n decodePhysicalDateTime,\n decodeProviderTimestamp,\n} from \"@validation/primitives/datetime-physical-codec\";\nimport {\n isDateTimeClock,\n isDateTimeInstant,\n} from \"@validation/primitives/datetime-values\";\nimport { geoBoundsForDistance } from \"@validation/primitives/geo-area-codec\";\nimport { validateGeoPoint } from \"@validation/primitives/geo-point-codec\";\nimport type { GeoArea, GeoPoint } from \"@validation/primitives/geo-values\";\nimport {\n validateIsoDate,\n validateIsoTime,\n validateIsoTimestamp,\n} from \"@validation/primitives/iso\";\nimport {\n carriesRepeatedKey,\n DEFAULT_MAX_OCCURRENCES,\n type NormalizedRecurrence,\n} from \"@validation/relations/recurrence\";\nimport { SqlSlot } from \"../../../sql/slot\";\nimport type { Operation } from \"../../types\";\nimport {\n canonicalDecimal,\n type DecimalDescriptor,\n decimalMembers,\n decimalSumOperand,\n decodeDecimalList,\n decodeDecimalScalar,\n dividesByZero,\n exactDecimalDomain,\n requireDecimal,\n sameDecimalDomain,\n} from \"./decimal\";\nimport {\n aggregatedIdentifier,\n decodeIdentifier,\n encodeIdentifier,\n type IdentifierColumn,\n identifierColumn,\n incomparableIdentifiers,\n isCompact,\n transportedIdentifier,\n} from \"./identifier\";\nimport { unreachable } from \"./invariant\";\nimport {\n type CallScope,\n type CallValues,\n Condition,\n Existence,\n type LazyRelations,\n type ModelVerbs,\n OuterColumn,\n Parameter,\n type RowDomain,\n type RowJudgement,\n type RowPurpose,\n} from \"./row-scope\";\nimport {\n type Arguments,\n type EngineSchema,\n entries,\n type Input,\n memo,\n type QueryViews,\n type ReadOperation,\n record,\n} from \"./schema\";\nimport {\n bindMembership,\n type Membership,\n type PhysicalField,\n physicalField,\n} from \"./storage\";\n\n/**\n * `Object.freeze`, named once: this module freezes every prepared structure it\n * builds, and one local name minifies where 92 member reads do not. Declared\n * ahead of every module-level use.\n */\nconst freeze = Object.freeze;\n\nexport type Leaf = {\n kind: \"scalar\";\n type: string;\n nullable: boolean;\n /**\n * The DECLARING scalar, for consumers that compile a value codec from it.\n *\n * The fields beside it are a projection of this object's state, which SQL\n * lowering and row decoding read; a codec owner such as\n * `result/cache-value-codecs.ts` is addressed by the object itself and must\n * never re-dispatch on `type`, which would be a second scalar-meaning\n * authority (g4/unit03/note.md FU.6 B-1c). Absent on the leaves no declared\n * scalar produces — `_count`, `exist`, a non-decimal `_avg`, `_distance` —\n * whose meaning is the aggregate's, not a column's.\n */\n scalar?: Scalar;\n /** A list column: the container decodes once, then each member as `type`. */\n list?: boolean;\n decimal?: DecimalDescriptor;\n /**\n * A `_sum` answering outside the field's domain: a decimal keeps the field\n * scale and drops its precision, a bigint may leave the int64 range, a\n * number may be `±Infinity`, and an int past 2^53 is the nearest double, as\n * a number sum is; `#splitSum` states which travel as two parts.\n */\n widened?: boolean;\n /** The declared physical timestamp spelling of this column. */\n dateTime?: DateTimePhysicalForm;\n /**\n * The column's identifier domain and what it physically holds, resolved\n * once per (adapter, model, field) — a foreign key's DERIVED domain and a\n * private carrier column's referenced key included (`identifier.ts`).\n */\n id?: IdentifierColumn;\n enumValues?: ReadonlySet<string>;\n dimension?: number;\n};\nexport type ProjectionShape =\n | {\n kind: \"object\";\n /**\n * `false` where the statement ALWAYS builds this document and says so —\n * a relation `_count` carrier. A provider `null` there is a malformed\n * row, not an absent relation. Left unset (nullable) everywhere a row\n * may genuinely be absent: a to-one relation, a variant arm. An\n * aggregate carrier (`_count`/`_sum`/`_avg`/`_min`/`_max` of\n * `aggregate`/`groupBy`) is always built too but is left unset, so a\n * provider `null` there publishes `null`: a compatibility answer\n * `tests/raptor3/result-decoder.test.ts` pins, not a stated contract.\n */\n nullable?: boolean;\n fields: Record<string, ProjectionShape | Leaf>;\n /**\n * Read-gated members (K5): each is present only where its gate, one of\n * `gates`, reads true; where it reads false the member is left out, or,\n * when the caller named it, the read fails at `refused`.\n */\n gated?: Readonly<Record<string, GatedMember>>;\n /** The boolean members the row carries for `gated`, never published. */\n gates?: readonly string[];\n }\n | CollectionShape\n | {\n kind: \"variants\";\n /** The public slot, for the refusal that names it. */\n relation: string;\n many: false;\n arms: Record<string, ProjectionShape>;\n }\n | {\n kind: \"variants\";\n relation: string;\n /** A junction-carried slot: each arm is a collection of its rows. */\n many: true;\n arms: Record<string, CollectionShape>;\n }\n | {\n kind: \"recursive\";\n relation: string;\n many: boolean;\n optional: boolean;\n recurrence: NormalizedRecurrence;\n row: ProjectionShape;\n identity: readonly Leaf[];\n };\ntype Shape = ProjectionShape;\n/** One read-gated member of a document: its gate, and the path a caller named it at. */\nexport interface GatedMember {\n readonly gate: string;\n readonly refused?: string;\n}\n/** A to-many relation's rows. */\ntype CollectionShape = {\n kind: \"collection\";\n /** A negative `take` runs a reversed window; the decoder restores it. */\n reversed?: boolean;\n row: ProjectionShape;\n};\n/**\n * A physical value's provider continuation ({@link Queries.fieldReader}),\n * bound to one execution's driver and adapter.\n */\ntype FieldReader = (value: unknown) => unknown;\n/**\n * One placement of the projection language, compiled for one decoded batch\n * ({@link Queries.compileReader}): it reads the provider's value there and\n * answers the public one.\n */\ntype Reader = (value: unknown) => unknown;\ntype RelationProjectionArguments = Pick<\n Partial<Arguments>,\n \"orderBy\" | \"take\" | \"skip\" | \"cursor\" | \"distinct\"\n> & {\n readonly selector?: Pick<PreparedSelector, \"model\" | \"predicate\">;\n};\ninterface PreparedRelationProjection {\n readonly edge: Membership;\n readonly arguments: RelationProjectionArguments;\n readonly projection: PreparedProjection;\n readonly recurrence?: NormalizedRecurrence;\n}\n/** One counted slot: its memberships, and the filter that narrows them. */\nexport type PreparedCount = {\n readonly relation: string;\n /** Every membership the slot counts: one edge, or every variant arm. */\n readonly edges: readonly Membership[];\n readonly selector?: Pick<PreparedSelector, \"model\" | \"predicate\">;\n /** A tagged `isNot` counts the arm's members the selector does NOT match. */\n readonly negated?: true;\n};\nexport type PreparedProjectionField =\n | { readonly kind: \"scalar\"; readonly name: string }\n | {\n /**\n * The sentinel column of an EMPTY default projection. A model whose\n * every scalar is omitted still has rows, and `SELECT FROM …` is a\n * syntax error, so one constant column carries the row's existence. It\n * is not in the decoder's shape, so the caller reads `{}`.\n */\n readonly kind: \"sentinel\";\n readonly name: string;\n }\n | {\n readonly kind: \"counts\";\n readonly name: string;\n readonly counts: readonly PreparedCount[];\n }\n | {\n /**\n * A declared projection key (K5): per row, whether each named\n * predicate holds beside the layer's `read`, or, `ordered`, the last\n * name that does.\n */\n readonly kind: \"evidence\";\n readonly name: string;\n readonly evidence: DeclaredEvidence;\n readonly names: readonly (readonly [string, Input])[];\n }\n | {\n /** A read-gated member's gate (K5): a boolean the decoder reads. */\n readonly kind: \"gate\";\n readonly name: string;\n readonly gate: FieldGate;\n }\n | {\n readonly kind: \"distance\";\n readonly name: string;\n readonly field: string;\n readonly specification: Input;\n }\n | ({\n readonly kind: \"relation\";\n readonly name: string;\n } & PreparedRelationProjection)\n | {\n readonly kind: \"variants\";\n readonly name: string;\n readonly many: boolean;\n readonly arms: readonly ({\n readonly variant: string;\n } & PreparedRelationProjection)[];\n /**\n * Every CONFIGURED member of a junction-carried slot, selected or not:\n * the subjects of the integrity probe (Arnaud's D-26). `only` selects\n * what is READ, never what is TRUE, so this list is not the arms'.\n */\n readonly memberships: readonly {\n readonly variant: string;\n readonly edge: Extract<Membership, { kind: \"junction\" }>;\n }[];\n };\nexport interface PreparedProjection {\n readonly model: AnyModel;\n readonly fields: readonly PreparedProjectionField[];\n readonly shape: Extract<ProjectionShape, { kind: \"object\" }>;\n}\n\n/**\n * May this prepared projection ride a mutation's `RETURNING`?\n *\n * The projection owner answers, because the answer is a property of how each\n * field LOWERS: a scalar is a column of the mutated row, while a relation\n * carrier, a variant slot and a `_count` all read OTHER rows through a\n * correlated subquery, which no `RETURNING` carries. A physical owner asking\n * \"does this name a relation?\" was the same question answered a second time.\n *\n * This is the RELOCATION of that one kind-test into the module that owns the\n * kinds — not a new per-field fact and not a wider rule. A `_distance` is an\n * expression over the mutated row's own columns and could ride a `RETURNING`,\n * but no provider in the qualified set declares the distance tier, so nothing\n * can witness that arm; it stays outside the gate until one can.\n */\nexport function returningSafeProjection(\n projection: PreparedProjection\n): boolean {\n return projection.fields.every(\n (field) => field.kind === \"scalar\" || field.kind === \"sentinel\"\n );\n}\nexport interface Query {\n sql: Sql;\n shape: Shape;\n expectedRows?: {\n readonly count: number;\n readonly missing: Error;\n };\n}\n/** One statement plus the operation's own cardinality and public shape. */\nexport interface Read {\n readonly query: Query;\n /**\n * Does this verb publish ONE value rather than the row set? Stated here, by\n * the owner that decides the cardinality, so no consumer re-derives it.\n */\n readonly single: boolean;\n /**\n * The PUBLIC value's own shape — which is not always the row shape\n * `query.shape` decodes: `count` publishes a number and `exist` a boolean\n * over a row of `{_count}`, and `findMany`/`groupBy` publish the set of rows.\n */\n readonly value: ProjectionShape | Leaf;\n result(rows: Input[]): unknown;\n}\nexport interface SelectorFacts {\n fields: Set<string>;\n equals: Map<string, unknown>;\n /**\n * The admitted unique selector's DISCRIMINATOR pins: the literal equality of\n * every `key: true` prepared column, which is exactly what the shipped\n * `partitionWhereUnique` files under `entries`\n * (`write-engine/shared.ts:154-166`). An extended `where`'s filter half, an\n * `AND`/`OR`/`NOT` arm and every entry of a selector admitted as a filter are\n * absent by construction — they are `equals` and not a pin.\n */\n keys: Map<string, unknown>;\n exact: boolean;\n reads: SelectorRead[];\n}\nexport interface SelectorRead {\n readonly model: AnyModel;\n readonly path: readonly Membership[];\n readonly fields: Set<string>;\n readonly equals: Map<string, unknown>;\n readonly exact: boolean;\n}\n/** Expressions compared as one: a row value, or the expression itself alone. */\nfunction rowValue(items: Sql[]): Sql {\n return items.length === 1 ? items[0]! : sql`(${sql.join(items, \", \")})`;\n}\nfunction newSelectorFacts(exact = true): SelectorFacts {\n return {\n fields: new Set(),\n equals: new Map(),\n keys: new Map(),\n exact,\n reads: [],\n };\n}\ntype PreparedScalar = {\n readonly model: AnyModel;\n readonly field: string;\n readonly physical: PhysicalField;\n};\ntype PreparedOperand =\n | { readonly kind: \"value\"; readonly value: unknown }\n | {\n readonly kind: \"field\";\n readonly scalar: PreparedScalar;\n /** An enclosing row's column: how many relation bodies above (`$row`). */\n readonly up?: number;\n }\n /**\n * A call value of a domain predicate, read at lowering; `spread` when it is\n * a whole `in`/`notIn` list, one value operand per member once read.\n */\n | {\n readonly kind: \"parameter\";\n readonly parameter: Parameter;\n readonly spread?: true;\n }\n | {\n readonly kind: \"sql\";\n readonly strings: readonly string[];\n readonly operands: readonly Extract<\n PreparedOperand,\n { kind: \"value\" | \"field\" }\n >[];\n };\n/** An operand as lowering reads it: every parameter's value read. */\ntype BoundOperand = Exclude<PreparedOperand, { kind: \"parameter\" }>;\n/**\n * What a prepared operator compares. A physical column, a JSON value addressed\n * inside one, and an aggregate over a column are three targets of the SAME\n * operator vocabulary — `where` and `having` never interpret operators twice.\n */\n/** A scalar column's declared state, as the lowering reads it. */\ntype ScalarStateOf = PreparedScalar[\"physical\"][\"scalar\"][\"~\"][\"state\"];\ntype PreparedTarget =\n | {\n readonly kind: \"column\";\n readonly scalar: PreparedScalar;\n readonly path?: readonly string[];\n /**\n * The column is addressed as a member of a unique `where`'s DISCRIMINATOR\n * rather than as a filter, so the comparison is the CONSTRAINT's, not the\n * engine's text contract: it names the row the provider's own unique\n * index holds under this value.\n *\n * A byte-exact conjunct here would ask a stricter question than the index\n * that answers it — on a case-insensitive collation a probe could report\n * a key free and the very next INSERT be rejected for duplicating it —\n * so the shipped engine spells exactly this half with the dialect's plain\n * equality (`buildUniqueEquality`, `builders/where-unique-builder.ts:213`)\n * and leaves the extended `where`'s filter half to `buildWhere`.\n */\n readonly key?: true;\n }\n | {\n readonly kind: \"aggregate\";\n readonly aggregate: Aggregate;\n readonly scalar?: PreparedScalar;\n };\n/** A recursive relation filter's range ({@link PreparedPredicate}). */\ntype Closure = { readonly depth: number | false; readonly self: boolean };\ntype PreparedPredicate =\n | {\n readonly kind: \"and\" | \"or\";\n readonly predicates: readonly PreparedPredicate[];\n }\n | { readonly kind: \"not\"; readonly predicate: PreparedPredicate }\n | { readonly kind: \"always\"; readonly value: boolean }\n /** A test of a call value that reads no column. */\n | { readonly kind: \"condition\"; readonly condition: Condition }\n | {\n /**\n * Whether some row of `model` the call may see holds `predicate` (any\n * row without one): reads no column of the row it judges, so it is\n * the same everywhere in a statement (`$exists`).\n */\n readonly kind: \"exists\";\n readonly model: AnyModel;\n readonly predicate?: PreparedPredicate;\n }\n | {\n /**\n * One layer's domain predicate for `model`, the unit R6 judges: per\n * call, its conditions fold (kept per outcome in `folded`), then a value\n * it still reads that is absent makes it false where its control is\n * required on `model` and drops it otherwise. While it lowers, its\n * relation reads take every other layer at its default and never this\n * one (R5).\n */\n readonly kind: \"layer\";\n readonly layer: number;\n readonly model: string;\n readonly predicate: PreparedPredicate;\n readonly conditions: readonly Condition[];\n readonly folded: Map<string, Folded>;\n }\n | {\n readonly kind: \"operation\";\n readonly operator: string;\n readonly target: PreparedTarget;\n readonly operand?: PreparedOperand;\n readonly operands?: readonly PreparedOperand[];\n readonly value?: unknown;\n readonly insensitive?: boolean;\n /**\n * Set on a bounded GeoPoint `distance` filter in POSITIVE polarity: the\n * comparison implies the bounding box of its smallest finite upper\n * bound, so the box is a conjunct the provider can answer from the\n * spatial index. Under a negation the box would be part of what is\n * negated, which is why polarity is a preparation fact and not a\n * lowering guess.\n */\n readonly probe?: true;\n }\n | {\n readonly kind: \"relation\";\n readonly edge: Membership;\n readonly quantifier: string;\n readonly predicate?: PreparedPredicate;\n /**\n * The relation is correlated by membership alone: the predicate states\n * which members count itself, so the lowering `Queries`' domain never\n * joins it (a premise that names its own visibility).\n */\n readonly unscoped?: true;\n /**\n * The quantifier ranges over the edge's CLOSURE from the parent row: the\n * rows 1..`depth` hops away (every hop when `depth` is false), and the\n * parent itself when `self` holds. The cycle policy is deliberately not\n * carried: a set does not depend on the paths that reach it.\n */\n readonly closure?: Closure;\n }\n | {\n /** The first `limit` rows of `selector` in key order ({@link Queries.window}). */\n readonly kind: \"window\";\n readonly selector: PreparedSelector;\n readonly limit: number;\n }\n | {\n /** The rows whose key is at most `last`'s ({@link Queries.through}). */\n readonly kind: \"through\";\n readonly model: AnyModel;\n readonly last: Input;\n };\ntype OperationPredicate = Extract<PreparedPredicate, { kind: \"operation\" }>;\n/** An operation as lowering reads it ({@link Queries.lowerOperation}). */\ntype BoundOperation = Omit<OperationPredicate, \"operand\" | \"operands\"> & {\n readonly operand?: BoundOperand;\n readonly operands?: readonly BoundOperand[];\n};\n/**\n * A conjunction of nothing states nothing; every other prepared predicate is a\n * condition. This is the one reading of \"this arm built no condition\" that the\n * shipped builders express by answering `undefined`\n * (`builders/where-builder.ts:217-308`, `operations/groupby-having.ts:77-173`).\n */\nfunction states(predicate: PreparedPredicate): boolean {\n if (predicate.kind === \"layer\") return states(predicate.predicate);\n return predicate.kind !== \"and\" || predicate.predicates.some(states);\n}\n/** A layer's predicate under one outcome of its conditions. */\ninterface Folded {\n readonly predicate: PreparedPredicate;\n /** The parameters it still reads, `spread` where one is a whole list. */\n readonly parameters: readonly (readonly [Parameter, boolean])[];\n}\nconst ALWAYS_TRUE: PreparedPredicate = freeze({ kind: \"always\", value: true });\n/**\n * `predicate` with every condition replaced by its outcome and the logical\n * combinators simplified, so a false condition removes its arm with every\n * parameter inside it. A relation keeps its quantifier over a folded body.\n */\nfunction foldConditions(\n predicate: PreparedPredicate,\n holds: (condition: Condition) => boolean\n): PreparedPredicate {\n switch (predicate.kind) {\n case \"condition\":\n return holds(predicate.condition) ? ALWAYS_TRUE : VACUOUS_FALSE;\n case \"and\":\n case \"or\": {\n const conjunction = predicate.kind === \"and\";\n const kept: PreparedPredicate[] = [];\n for (const member of predicate.predicates) {\n const folded = foldConditions(member, holds);\n if (folded.kind !== \"always\") kept.push(folded);\n else if (folded.value !== conjunction) return folded;\n }\n if (kept.length === 0) return conjunction ? ALWAYS_TRUE : VACUOUS_FALSE;\n return kept.length === predicate.predicates.length &&\n kept.every((member, index) => member === predicate.predicates[index])\n ? predicate\n : freeze({ kind: predicate.kind, predicates: freeze(kept) });\n }\n case \"not\": {\n const folded = foldConditions(predicate.predicate, holds);\n if (folded.kind === \"always\")\n return folded.value ? VACUOUS_FALSE : ALWAYS_TRUE;\n return folded === predicate.predicate\n ? predicate\n : freeze({ kind: \"not\", predicate: folded });\n }\n case \"relation\": {\n if (!predicate.predicate) return predicate;\n const folded = foldConditions(predicate.predicate, holds);\n return folded === predicate.predicate\n ? predicate\n : freeze({ ...predicate, predicate: folded });\n }\n case \"exists\": {\n if (!predicate.predicate) return predicate;\n const folded = foldConditions(predicate.predicate, holds);\n // No row matches a false body; a true one still needs a row to exist.\n if (folded.kind === \"always\" && !folded.value) return VACUOUS_FALSE;\n if (folded === predicate.predicate) return predicate;\n return freeze({\n kind: \"exists\",\n model: predicate.model,\n ...(folded.kind !== \"always\" && { predicate: folded }),\n });\n }\n default:\n return predicate;\n }\n}\n/**\n * `predicate` over a produced row whose fields' nullness the write states\n * (`nulls`: field to whether its value is null), each null test of such a\n * field replaced by its outcome and the combinators simplified as\n * {@link foldConditions} does: the values a write sets fold into its\n * judgement (permissions plan §11.2 F2), so an arm on a key it leaves null does not\n * reach the statement. Only the row's own columns: a relation reads other\n * rows, and is kept as it is.\n */\nfunction foldKnownNulls(\n predicate: PreparedPredicate,\n nulls: ReadonlyMap<string, boolean>\n): PreparedPredicate {\n switch (predicate.kind) {\n case \"operation\": {\n const { target, operand } = predicate;\n if (\n predicate.operator !== \"equals\" ||\n target.kind !== \"column\" ||\n target.path !== undefined ||\n operand?.kind !== \"value\" ||\n operand.value !== null ||\n target.scalar.physical.scalar[\"~\"].state.type === \"json\"\n )\n return predicate;\n const known = nulls.get(target.scalar.field);\n if (known === undefined) return predicate;\n return known ? ALWAYS_TRUE : VACUOUS_FALSE;\n }\n case \"and\":\n case \"or\": {\n const conjunction = predicate.kind === \"and\";\n const kept: PreparedPredicate[] = [];\n for (const member of predicate.predicates) {\n const folded = foldKnownNulls(member, nulls);\n if (folded.kind !== \"always\") kept.push(folded);\n else if (folded.value !== conjunction) return folded;\n }\n if (kept.length === 0) return conjunction ? ALWAYS_TRUE : VACUOUS_FALSE;\n return kept.length === predicate.predicates.length &&\n kept.every((member, index) => member === predicate.predicates[index])\n ? predicate\n : freeze({ kind: predicate.kind, predicates: freeze(kept) });\n }\n case \"not\": {\n const folded = foldKnownNulls(predicate.predicate, nulls);\n if (folded.kind === \"always\")\n return folded.value ? VACUOUS_FALSE : ALWAYS_TRUE;\n return folded === predicate.predicate\n ? predicate\n : freeze({ kind: \"not\", predicate: folded });\n }\n default:\n return predicate;\n }\n}\n/**\n * Whether `predicate`, judged over a row of `model`, may read one of\n * `fields` of that row: an operation's column or field operand, a\n * relation's own side of its link (a junction's: the row's keys). Anything\n * it cannot answer for (an aggregate, a window) reads them all. A row that\n * differs from another only outside what a predicate reads gets the same\n * answer from it, against the same rows.\n */\nfunction readsAny(\n predicate: PreparedPredicate,\n fields: ReadonlySet<string>,\n keys: readonly string[]\n): boolean {\n switch (predicate.kind) {\n case \"and\":\n case \"or\":\n return predicate.predicates.some((member) =>\n readsAny(member, fields, keys)\n );\n case \"not\":\n case \"layer\":\n return readsAny(predicate.predicate, fields, keys);\n case \"always\":\n case \"condition\":\n return false;\n case \"exists\":\n return (\n predicate.predicate !== undefined &&\n readsAbove(predicate.predicate, fields, 1)\n );\n case \"operation\": {\n if (predicate.target.kind !== \"column\") return true;\n const operands = [predicate.operand, ...(predicate.operands ?? [])];\n return (\n fields.has(predicate.target.scalar.field) ||\n operands.some(\n (operand) =>\n (operand?.kind === \"field\" && fields.has(operand.scalar.field)) ||\n (operand?.kind === \"sql\" &&\n operand.operands.some(\n (member) =>\n member.kind === \"field\" && fields.has(member.scalar.field)\n ))\n )\n );\n }\n case \"relation\": {\n const { edge } = predicate;\n const own =\n edge.kind === \"reference\"\n ? [\n ...edge.pairs.map((pair) => pair.source),\n ...(edge.discriminator?.side === \"source\"\n ? [edge.discriminator.field]\n : []),\n ]\n : keys;\n return (\n own.some((field) => fields.has(field)) ||\n (predicate.predicate !== undefined &&\n readsAbove(predicate.predicate, fields, 1))\n );\n }\n default:\n return true;\n }\n}\n/**\n * Whether a relation body `depth` bodies below the judged row compares one of\n * `fields` of that row (`{ $row, up: depth }`): the row's new value changes\n * its answer as surely as a column of its own does. An `$exists` body is a\n * root of its own and reads no row outside it.\n */\nfunction readsAbove(\n predicate: PreparedPredicate,\n fields: ReadonlySet<string>,\n depth: number\n): boolean {\n switch (predicate.kind) {\n case \"and\":\n case \"or\":\n return predicate.predicates.some((member) =>\n readsAbove(member, fields, depth)\n );\n case \"not\":\n case \"layer\":\n return readsAbove(predicate.predicate, fields, depth);\n case \"relation\":\n case \"exists\":\n return (\n predicate.predicate !== undefined &&\n readsAbove(predicate.predicate, fields, depth + 1)\n );\n case \"operation\":\n return [predicate.operand, ...(predicate.operands ?? [])].some(\n (operand) =>\n operand?.kind === \"field\" &&\n operand.up === depth &&\n fields.has(operand.scalar.field)\n );\n case \"always\":\n case \"condition\":\n return false;\n default:\n return true;\n }\n}\n/** Every parameter and condition a layer's predicate reads. */\nfunction callReads(\n predicate: PreparedPredicate,\n parameters: Map<Parameter, boolean>,\n conditions: Set<Condition>\n): void {\n switch (predicate.kind) {\n case \"condition\":\n conditions.add(predicate.condition);\n return;\n case \"and\":\n case \"or\":\n for (const member of predicate.predicates)\n callReads(member, parameters, conditions);\n return;\n case \"not\":\n callReads(predicate.predicate, parameters, conditions);\n return;\n case \"relation\":\n case \"exists\":\n if (predicate.predicate)\n callReads(predicate.predicate, parameters, conditions);\n return;\n case \"operation\":\n for (const operand of [predicate.operand, ...(predicate.operands ?? [])])\n if (operand?.kind === \"parameter\")\n parameters.set(operand.parameter, operand.spread === true);\n if (\n predicate.value instanceof Parameter &&\n !parameters.has(predicate.value)\n )\n parameters.set(predicate.value, false);\n return;\n default:\n return;\n }\n}\n/**\n * An `OR` whose every arm is one value equality on the same plain column, as\n * that column's `in` (platform-15): the same three-valued answer, so a long\n * chain binds as the one list `in` binds instead of one arm per expression\n * level. A JSON, list, point or vector column compares by its own rules, a\n * folded or referenced operand is not a member, and `null` is `IS NULL`.\n */\nfunction sameColumnIn(\n arms: readonly PreparedPredicate[]\n): PreparedPredicate | undefined {\n const operands: PreparedOperand[] = [];\n let target: Extract<PreparedTarget, { kind: \"column\" }> | undefined;\n for (let arm of arms) {\n while (arm.kind === \"and\" && arm.predicates.length === 1)\n arm = arm.predicates[0]!;\n const operand = arm.kind === \"operation\" ? arm.operand : undefined;\n if (\n arm.kind !== \"operation\" ||\n arm.operator !== \"equals\" ||\n arm.insensitive ||\n arm.target.kind !== \"column\" ||\n arm.target.path ||\n operand?.kind !== \"value\" ||\n operand.value === null ||\n operand.value instanceof Sql ||\n (target &&\n (arm.target.scalar.model !== target.scalar.model ||\n arm.target.scalar.field !== target.scalar.field ||\n arm.target.key !== target.key))\n )\n return;\n target ??= arm.target;\n operands.push(operand);\n }\n const state = target?.scalar.physical.scalar[\"~\"].state;\n if (\n !target ||\n state?.array === true ||\n state?.type === \"json\" ||\n state?.type === \"point\" ||\n state?.type === \"vector\"\n )\n return;\n return freeze({\n kind: \"operation\",\n operator: \"in\",\n target,\n operands: freeze(operands),\n insensitive: false,\n });\n}\n/** Does the predicate read another row: a relation subquery anywhere in it? */\nfunction readsRelation(predicate: PreparedPredicate): boolean {\n switch (predicate.kind) {\n case \"relation\":\n case \"exists\":\n return true;\n case \"and\":\n case \"or\":\n return predicate.predicates.some(readsRelation);\n case \"not\":\n case \"layer\":\n return readsRelation(predicate.predicate);\n default:\n return false;\n }\n}\n/**\n * The smallest FINITE upper bound a distance filter states, or `undefined`\n * when it states none. A bound of zero or less bounds nothing worth probing:\n * the box degenerates to the point itself.\n */\nfunction distanceUpperBound(value: unknown): number | undefined {\n if (value === null || typeof value !== \"object\") return undefined;\n const { lt, lte } = value as { lt?: unknown; lte?: unknown };\n const bounds = [lt, lte].filter(\n (bound): bound is number => typeof bound === \"number\" && bound > 0\n );\n return bounds.length === 0 ? undefined : Math.min(...bounds);\n}\n/**\n * A membership the parent claims whose row is gone.\n *\n * The statement answers a claimed arm with a document and an unclaimed one\n * with `null`, so an EMPTY document is the claim without the row. The test is\n * the arm's own selected keys — a shape that requests fields and receives none\n * — and never a private carrier column (Arnaud's D-19).\n */\nfunction orphanedArm(carrier: unknown, arm: ProjectionShape): boolean {\n if (arm.kind !== \"object\" || carrier === null || carrier === undefined)\n return false;\n const document = providerJson(carrier);\n if (typeof document !== \"object\" || document === null) return false;\n return (\n Object.keys(document).length === 0 && Object.keys(arm.fields).length > 0\n );\n}\n/**\n * A structured value — a document, a collection, a variant slot, a recursive\n * carrier, or a vector or point scalar — as the provider handed it: a driver\n * that does not parse JSON itself hands back the value's TEXT, which is parsed\n * here once, and any other value is already the parsed structure.\n */\nfunction providerJson(value: unknown): unknown {\n return typeof value === \"string\" ? JSON.parse(value) : value;\n}\n/**\n * The ONE reading of a provider DOCUMENT, whatever carries it: a root row, a\n * relation, `_count` or aggregate carrier, a collection row, a variant slot,\n * its integrity entry and each of its arms, a recursive node row, the\n * recursive carrier and each of its node and edge entries. A document is an\n * object that is not an array, and its members are then read by {@link own}.\n * `null` is answered as itself, because only the placement knows whether its\n * shape permits it; anything else is no document (`undefined`), which the\n * placement refuses in its own registered sentence. The one placement that\n * may be ABSENT is the integrity entry, which a slot without junction\n * memberships does not carry; a present one is refused like any other.\n */\nfunction providerDocument(value: unknown): Input | null | undefined {\n if (value === null) return null;\n return typeof value === \"object\" && !Array.isArray(value)\n ? record(value)\n : undefined;\n}\n/**\n * One member of a provider document, read with OWN-key semantics. An omitted\n * field is absent, whatever `Object.prototype` happens to carry under that\n * name.\n */\nfunction own(source: Record<string, unknown>, key: string): unknown {\n return Object.hasOwn(source, key) ? source[key] : undefined;\n}\n/**\n * The ONE cursor-eligibility sentence, raised from the order walker for a key\n * whose lowering would consult a provider capability, and from\n * {@link Queries.page} for every other non-scalar key.\n */\nconst CURSOR_ORDER_REFUSAL =\n \"Cursor pagination supports direct scalar sort directions only; relation and vector-distance orderBy are not supported.\";\n/** A disjunction of nothing is FALSE; it is the one predicate that says so. */\nconst VACUOUS_FALSE: PreparedPredicate = freeze({\n kind: \"always\",\n value: false,\n});\n/** One normalized sort key; `field` marks a direct scalar a cursor can use. */\ninterface OrderTerm {\n readonly expression: Sql;\n readonly descending: boolean;\n /**\n * The placement the caller spelled. Unspelled is not a placement: the bare\n * direction names the provider's own default, and only a windowed read —\n * whose cursor predicate must read the same total order — states one.\n */\n readonly nulls?: \"first\" | \"last\";\n /**\n * Set when `nulls` belongs to the expression instead of to the caller: a\n * reversed window flips the caller's placement and leaves this one alone,\n * because the shipped engine reverses the input `sort` only\n * (`operations/find-pagination.ts:131-151`) and `buildDistanceOrder` then\n * re-emits `nullsLast(distance, …)` (`builders/sort-order-builder.ts:36-45`).\n */\n readonly expressionNulls?: true;\n readonly nullable: boolean;\n readonly field?: string;\n}\nexport interface PreparedSelector {\n readonly model: AnyModel;\n readonly facts: SelectorFacts;\n readonly uniqueKey?: OrderedModelKey;\n readonly uniqueValues?: ReadonlyMap<string, unknown>;\n readonly predicate?: PreparedPredicate;\n /**\n * A row domain narrowed this selector ({@link Queries.candidates}): it\n * states more than its unique key, so a consumer that would trust the key\n * alone to name the row must not.\n */\n readonly scoped?: true;\n /**\n * The verb a write's candidates were judged at ({@link Queries.candidates}):\n * the row such a write produces is judged at the same predicates\n * ({@link PreparedDomain.produced}).\n */\n readonly judgement?: RowJudgement;\n}\n/** The decoder identifies the invalid value; its operation owns public errors. */\nexport class InvalidScalarResult extends TypeError {\n readonly scalarType: string;\n readonly reason: string;\n constructor(scalarType: string, reason: string) {\n super(`Invalid provider ${scalarType === \"int\" ? \"integer\" : scalarType}`);\n this.scalarType = scalarType;\n this.reason = reason;\n }\n}\n\n/**\n * A recursive projection decoded more occurrences under one outer row than\n * its budget (`recurse.maxOccurrences`). The decoder knows the slot; as for\n * {@link InvalidScalarResult}, its operation owns the public error.\n */\nexport class RecursiveOutputOverBudget extends RangeError {\n readonly relation: string;\n readonly limit: number;\n constructor(relation: string, limit: number) {\n super(`Recursive relation '${relation}' exceeds ${limit} occurrences`);\n this.relation = relation;\n this.limit = limit;\n }\n /** The result-size refusal of `operation`, which ran the projection. */\n refusal(operation: Operation, model: string): UnsupportedOperationError {\n return new UnsupportedOperationError(\n `'${operation}' would return more than ${this.limit} occurrences of recursive relation '${this.relation}' under one row, its output budget; raise recurse.maxOccurrences, lower recurse.depth or filter the relation.`,\n {\n meta: {\n model,\n operation,\n relation: this.relation,\n feature: \"recursive output budget\",\n },\n }\n );\n }\n}\n\n/**\n * A row the read returned lacks the gate of a field the caller named (K5,\n * OD-5): raised while decoding, after the statement and before any result.\n * Like {@link InvalidScalarResult}, its operation owns the public error.\n */\nexport class GatedFieldRefusal extends Error {\n readonly path: string;\n constructor(path: string) {\n super(`The selected field at '${path}' is not readable on a returned row`);\n this.path = path;\n }\n /** The `ValidationError` of `operation`, at the path the caller named. */\n refusal(operation: Operation, model: string): ValidationError {\n return new ValidationError(\n operation,\n [{ path: this.path, message: \"is not readable on a returned row\" }],\n { meta: { model } }\n );\n }\n}\n\n/** The public output name of a `_distance` projection, stated once. */\nconst DISTANCE_FIELD = \"_distance\";\n/**\n * The private recursive carrier's member names, stated once: the one wire\n * vocabulary the recursive lowering writes and `decodeRecursiveCarrier` reads.\n */\nconst RECURSIVE_CARRIER = freeze({\n root: \"__rq_root\",\n nodes: \"__rq_nodes\",\n edges: \"__rq_edges\",\n key: \"__rq_key\",\n row: \"__rq_row\",\n parent: \"__rq_parent\",\n child: \"__rq_child\",\n depth: \"__rq_depth\",\n});\nconst AGGREGATES = [\"_count\", \"_avg\", \"_sum\", \"_min\", \"_max\"] as const;\n/**\n * The aggregate vocabulary as a TYPE, so the lowering switch over it is\n * exhaustive by construction rather than by a sentence (N4, plan §4).\n * {@link isAggregate} is the ONE narrowing of a payload key into it — the same\n * set admission enumerates (`validation/model/args/aggregate.ts`), never a\n * second one.\n */\ntype Aggregate = (typeof AGGREGATES)[number];\nconst AGGREGATE_NAMES: ReadonlySet<string> = new Set(AGGREGATES);\nfunction isAggregate(name: string): name is Aggregate {\n return AGGREGATE_NAMES.has(name);\n}\nconst BOOLEAN_LEAF: Leaf = freeze({\n kind: \"scalar\",\n type: \"boolean\",\n nullable: false,\n});\nconst COUNT_LEAF: Leaf = freeze({\n kind: \"scalar\",\n type: \"int\",\n nullable: false,\n});\nconst QUANTIFIERS: ReadonlySet<string> = new Set([\n \"is\",\n \"isNot\",\n \"some\",\n \"every\",\n \"none\",\n]);\nconst FILTER_OPERATORS: ReadonlySet<string> = new Set([\n \"equals\",\n \"not\",\n \"in\",\n \"notIn\",\n \"lt\",\n \"lte\",\n \"gt\",\n \"gte\",\n \"contains\",\n \"startsWith\",\n \"endsWith\",\n \"mode\",\n \"has\",\n \"hasEvery\",\n \"hasSome\",\n \"isEmpty\",\n \"path\",\n \"string_contains\",\n \"string_starts_with\",\n \"string_ends_with\",\n \"array_contains\",\n \"array_starts_with\",\n \"array_ends_with\",\n \"within\",\n \"distance\",\n]);\n\n/**\n * Whether an admitted object addresses operators rather than being one whole\n * value. Only the two scalars whose own values ARE objects can be ambiguous.\n */\nfunction addressesOperators(\n state: ScalarState | undefined,\n value: Input\n): boolean {\n if (!isOperatorRecord(value)) return false;\n if (state?.type !== \"json\" && state?.type !== \"point\") return true;\n return Object.keys(value).some((key) => FILTER_OPERATORS.has(key));\n}\n\nconst ARITHMETIC_UPDATES = [\n \"increment\",\n \"decrement\",\n \"multiply\",\n \"divide\",\n] as const;\nconst LIST_UPDATES = [\"push\", \"unshift\"] as const;\n\n/** One admitted scalar update payload, interpreted once and lowered twice. */\ntype PreparedUpdate =\n | { readonly kind: \"value\"; readonly value: unknown }\n | {\n readonly kind: \"arithmetic\";\n readonly operator: (typeof ARITHMETIC_UPDATES)[number];\n readonly by: unknown;\n }\n | {\n readonly kind: \"list\";\n readonly operator: (typeof LIST_UPDATES)[number];\n readonly members: readonly unknown[];\n };\n\n/** A plain admitted record, as opposed to one whole value of an object domain. */\nfunction isOperatorRecord(value: object): boolean {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * The ONE answer to \"does this admitted scalar payload name a whole value?\",\n * boxed so `undefined` can mean \"it names an operator instead\".\n *\n * An admitted operator record owns its keys; a `Uint8Array`, `Decimal` or\n * `Date` inherits methods with the same names and is one whole value in EVERY\n * domain, as is a `Sql` fragment. Both consumers read this one answer —\n * {@link Queries.updateValue}'s payload interpreter, which needs to know when\n * the payload is NOT whole, and `commands/assignments.ts`'s symbolic final\n * field, which only needs the value — so the two can never disagree about what\n * `set` names.\n */\nexport function wholeValue(\n value: unknown\n): { readonly value: unknown } | undefined {\n if (value instanceof Sql || value === null || typeof value !== \"object\")\n return { value };\n if (!isOperatorRecord(value)) return { value };\n return Object.hasOwn(value, \"set\") ? { value: record(value).set } : undefined;\n}\n\n/**\n * The ONE interpreter of an admitted scalar update payload.\n *\n * It answers WHICH operator the caller spelled and WHAT its operand is, and\n * nothing about SQL. Two lowerings consume that one answer — the provider's\n * own `SET` assignment ({@link Queries.updateAssignment}) and the same\n * operator named over an already-known value ({@link Queries.updateValue}) —\n * so an operator can never be admitted in one spelling and refused in the\n * other.\n */\nfunction readUpdate(value: unknown): PreparedUpdate {\n const whole = wholeValue(value);\n if (whole) return { kind: \"value\", value: whole.value };\n const operation = record(value);\n for (const operator of ARITHMETIC_UPDATES)\n if (Object.hasOwn(operation, operator))\n return { kind: \"arithmetic\", operator, by: operation[operator] };\n for (const operator of LIST_UPDATES)\n if (Object.hasOwn(operation, operator)) {\n const members = operation[operator];\n return {\n kind: \"list\",\n operator,\n members: Array.isArray(members) ? members : [members],\n };\n }\n // The shipped engine's own last word on an admitted payload that names no\n // operator (`builders/set-builder.ts:217-219`), identity included: the one\n // reachable shape is an empty record, and it is refused here, before any\n // statement of the update is built.\n throw new QueryEngineError(\n `Unknown update operation: ${Object.keys(operation).join(\", \")}`\n );\n}\n\n/** Query scopes and output shapes share no record-identity requirement. */\n/**\n * A temporal operand's WIRE form: what the ADMISSION boundary makes of it.\n *\n * A payload's instant crossed `validation/primitives/iso.ts` before it reached\n * this engine — `Date` in, ISO spelling out — and a value the engine DECODED\n * is the `Date` of that same instant, which is bound BACK whenever an\n * identity, a membership or a premise is built from a row the engine read: a\n * `dateTime` or `date` key captured on a transport without RETURNING answers\n * `UPDATE … WHERE (\"id\" = ? OR \"id\" = ?)`, and no driver binds a `Date`\n * (\"SQLite3 can only bind numbers, strings, bigints, buffers, and null\"). So a\n * captured instant crosses the same boundary the payload did, which spells a\n * `Date` as `Date.prototype.toISOString` produces it (`iso.ts:75`).\n *\n * That spelling addresses the row wherever the column's stored form is\n * INSTANT-valued — SQLite INTEGER/REAL, the PostgreSQL and MySQL timestamp\n * types — and wherever the payload's own spelling was that one. A TEXT-stored\n * `dateTime` admits MORE than one spelling of one instant: the same boundary\n * admits a valid ISO STRING unchanged (`ok(value)`, `iso.ts:94`) and the\n * SQLite adapter keeps that string byte for byte\n * (`sqlite-adapter.ts:288-296`), so a key written `2020-03-01T10:00:00Z` or\n * with a `+02:00` offset is stored as those bytes and `…:00.000Z` names no\n * row of its own. Nothing here re-spells it: a capture of such a column never\n * decodes to a `Date` at all, because the row decoder keeps the PROVIDER's\n * spelling for an INTERNAL read and materializes the `Date` only for a public\n * one ({@link Queries.decodeScalar}, the split the decimal arm beside it\n * already takes). A string reaches this function only to pass through, so the\n * captured identity binds the stored bytes and the spelling still has exactly\n * one owner (FC-02B, which repaired `g4/release/n5/note.md` §6's residual).\n * Every other value passes through untouched. The other captured domains bind\n * as they are — measured: `bigint`, `decimal` and `time` are already\n * provider-bindable, and `blob`, `json`, `point` and `vector` can be neither a\n * key nor a unique, so no identity carries one.\n */\nfunction admittedTemporal(\n value: unknown,\n admit: (value: unknown) => { value: string } | { issues: unknown }\n): unknown {\n if (!(value instanceof Date)) return value;\n const admitted = admit(value);\n return \"value\" in admitted ? admitted.value : value;\n}\n\n/**\n * The selection a query that writes no `select` asks for: every scalar the\n * default projection's one owner (`projectableScalarNames`) keeps.\n */\nfunction defaultSelection(model: AnyModel): Record<string, true> {\n const selection: Record<string, true> = {};\n for (const field of projectableScalarNames(model)) selection[field] = true;\n return selection;\n}\n\nfunction rowSet(query: Query): ProjectionShape {\n return { kind: \"collection\", row: query.shape };\n}\n\nfunction firstRow(rows: Input[]): Input | null {\n return rows[0] ?? null;\n}\n\nfunction aggregateRow(rows: Input[]): Input {\n return rows[0] ?? {};\n}\n\nfunction rowIdentity(rows: Input[]): Input[] {\n return rows;\n}\n\nfunction reversedRows(rows: Input[]): Input[] {\n return rows.reverse();\n}\n\n/** A filter read's controls: it takes the root domain's rows. */\nconst ROOT_CANDIDATES = Object.freeze({ purpose: \"root\" as const });\n\n/**\n * One relation filter body a statement lowers ({@link Queries.relationExists}):\n * its key set's name and query, and each place it was lowered at, with the\n * two texts that place settles to.\n */\ninterface SharedBody {\n readonly name: string;\n readonly query: Sql;\n readonly slots: {\n readonly slot: SqlSlot;\n readonly inline: Sql;\n readonly use: Sql;\n }[];\n}\n/** A statement's relation bodies, by {@link sharedKey}, in lowering order. */\ninterface SharedBodies {\n readonly byKey: Map<string, SharedBody>;\n readonly order: SharedBody[];\n}\n/** An alias the per-statement counter minted, inside an identifier. */\nconst ALIAS_TOKEN = /(?<=[\"_])q(\\d+)(?=[\"_])/g;\n/**\n * A caller's `Sql` operand as lowered, parenthesized ({@link Queries.value}):\n * text the engine did not write, so nothing in it is an alias of the\n * engine's, whatever it spells ({@link sharedKey}).\n */\nclass CallerText extends Sql {}\nconst isCallerText = (fragment: Sql): boolean => fragment instanceof CallerText;\nconst callerText = (fragment: Sql): Sql =>\n new CallerText([\"(\", \")\"], [fragment]);\nconst valueIds = new WeakMap<object, number>();\nlet nextValueId = 0;\n/** A bound value as a key: a primitive by value, a `Date` by its instant, a list by its members, anything else by identity. */\nfunction valueKey(value: unknown): string {\n if (value instanceof Date) return `d${value.getTime()}`;\n if (Array.isArray(value)) return `a${JSON.stringify(value.map(valueKey))}`;\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n )\n return `${typeof value}:${String(value)}`;\n return `o${memo(valueIds, value, () => nextValueId++)}`;\n}\n/**\n * Two bodies are one where their texts are equal once their aliases are\n * renumbered in order of appearance, and their values are equal: the same\n * rows of the same table under the same conditions. A body holding another\n * reads it provisionally, by its key set's name, which equal bodies share.\n * Only the engine's own text holds its aliases: a caller's `Sql` operand\n * ({@link CallerText}) is compared as written, so `'_q1_'` and `'_q2_'` stay\n * two bodies (ENG-4, review 2). Its runs are found on the fragment tree,\n * which no lowering flattens before its statement settles ({@link SqlSlot}).\n */\nfunction sharedKey(query: Sql): string {\n const { runs, values } = Sql.peekRuns(query, isCallerText);\n const renumbered = new Map<string, number>();\n const normalized = runs.map(({ text, opaque }) =>\n opaque\n ? [text]\n : text.replace(ALIAS_TOKEN, (_, n: string) => {\n let local = renumbered.get(n);\n if (local === undefined) {\n local = renumbered.size;\n renumbered.set(n, local);\n }\n return `q${local}`;\n })\n );\n // SQL text and bound strings may contain any delimiter. Preserve the\n // tuple boundaries, including array members, before sharing a predicate.\n return JSON.stringify([normalized, values.map(valueKey)]);\n}\n\n/**\n * Textual alias renumbering cannot distinguish a physical name from an\n * alias. Such schemas keep their relation bodies inline: an optimization\n * must never rename a column, table, junction or namespace in its identity.\n * An alias is `q<n>` between quotes or underscores ({@link ALIAS_TOKEN}), so\n * only a name that is one, or holds one at an end or between underscores,\n * resembles it; `seq1` or `freq2` do not.\n */\nconst aliasLikeSchemas = new WeakMap<EngineSchema, boolean>();\nconst ALIAS_LIKE_NAME = /(?:^|_)q\\d+(?:_|$)/;\nconst resemblesAlias = (name: string) => ALIAS_LIKE_NAME.test(name);\nfunction hasAliasLikeNames(schema: EngineSchema): boolean {\n // Physical names are immutable for the schema lifetime, shared by every\n // bound actor view. Scan them once, not for each operation's Queries.\n return memo(aliasLikeSchemas, schema, () => {\n for (const [model, slots] of schema.index) {\n if (resemblesAlias(model[\"~\"].names.sql!)) return true;\n for (const field of schema.storedFields(model))\n if (resemblesAlias(physicalField(schema, model, field).name))\n return true;\n for (const { edge } of slots.values()) {\n const junctions =\n edge.kind === \"junction\"\n ? [edge.topology]\n : edge.kind === \"variantJunctionCarrier\"\n ? edge.members.map((member) => member.topology)\n : [];\n for (const junction of junctions) {\n if (resemblesAlias(junction.table)) return true;\n for (const side of [junction.source, junction.target])\n if (\n side.members.some((member) =>\n resemblesAlias(member.junctionField)\n )\n )\n return true;\n }\n }\n }\n return false;\n });\n}\n/** No layer is lowering. */\nconst NO_LAYERS: readonly number[] = Object.freeze([]);\n/** A projection that carries no gate member (K5). */\nconst NO_GATES: readonly string[] = Object.freeze([]);\nconst isParameterOperand = (operand: PreparedOperand): boolean =>\n operand.kind === \"parameter\";\n\n/** One layer's projection key on a model (K5), with the layer's `read`. */\nexport interface DeclaredEvidence {\n readonly layer: number;\n readonly read: Input;\n readonly names: readonly (readonly [string, Input])[];\n readonly ordered: boolean;\n}\n/**\n * What a read-gated field's row must hold, per layer gating it: the layer's\n * `read` and the field's predicate there.\n */\nexport type FieldGate = readonly (readonly [number, Input, Input])[];\n/** A model's projection keys and read-gated fields under one domain (K5). */\nexport interface ProjectedFacts {\n readonly keys: ReadonlyMap<string, DeclaredEvidence>;\n readonly gates: ReadonlyMap<string, FieldGate>;\n}\n/**\n * The selections a caller wrote, and the read-gated fields each names (K5):\n * admission marks them by identity, as `omit` and `include` desugar every\n * node into a `select` naming every scalar. A field a selection does not mark\n * is projected where its gate holds and left out elsewhere.\n */\nexport const namedGatedFields = new WeakMap<object, ReadonlySet<string>>();\n\n/** Equal gates shared, so a projection carries one member per distinct gate. */\nfunction sharedGate(gate: FieldGate, known: FieldGate[]): FieldGate {\n const same = known.find(\n (other) =>\n other.length === gate.length &&\n other.every(\n ([layer, , input], index) =>\n layer === gate[index]![0] && input === gate[index]![2]\n )\n );\n if (same) return same;\n known.push(gate);\n return gate;\n}\n\n/**\n * One row domain as prepared meaning: per purpose and model, the conjunction\n * of the model's inputs, each a {@link PreparedPredicate} `layer` node,\n * prepared at most once for every `Queries` of one engine view (its reads and\n * its write contexts share it) and for every call: a value a call supplies is\n * a parameter. A layer's node holds its verb predicates beside its purpose's\n * (R2), each input prepared once whatever purposes and verbs reuse it.\n * Prepared meaning holds no alias, adapter or driver, so the view's own\n * `Queries` prepares it.\n */\nexport class PreparedDomain {\n readonly rows: RowDomain;\n /** The domain absent controls select: what a layer's traversals read (R5). */\n readonly defaults: PreparedDomain;\n readonly #queries: Queries;\n readonly #prepared = {\n root: new Map<string, PreparedSelector | null>(),\n related: new Map<string, PreparedSelector | null>(),\n };\n readonly #inputs = new Map<Input, PreparedSelector>();\n readonly #layered = new Map<string, Map<Input, PreparedSelector>>();\n readonly #projected = new Map<string, ProjectedFacts | null>();\n /** Whether a model's verbs declare a projection key or a gated field. */\n readonly projects: boolean;\n /**\n * The default projections of the models this domain projects facts for:\n * theirs differ from the view's shared ones, which carry no gate.\n */\n readonly defaultProjections = new WeakMap<AnyModel, PreparedProjection>();\n #view: Queries | undefined;\n constructor(rows: RowDomain, queries: Queries, defaults?: PreparedDomain) {\n this.rows = rows;\n this.#queries = queries;\n this.defaults = defaults ?? this;\n this.projects =\n rows.projects ??\n [...(rows.verbs?.values() ?? [])].some((layers) =>\n layers.some((verbs) => verbs?.evidence || verbs?.reads.size)\n );\n }\n /** `input`, one of `model`'s predicates in `layer`, as that layer's node. */\n layered(model: AnyModel, layer: number, input: Input): PreparedSelector {\n const name = model[\"~\"].names.ts!;\n const inputs = memo(this.#layered, `${name} ${layer}`, () => new Map());\n return memo(inputs, input, () => {\n const part = this.#queries.prepareSelector(model, input);\n return part.predicate === undefined\n ? part\n : freeze({ ...part, predicate: layerOf(layer, name, part.predicate) });\n });\n }\n /** `model`'s projection keys and read-gated fields; `undefined` for none. */\n projected(model: AnyModel): ProjectedFacts | undefined {\n return this.projects ? this.#projectedFacts(model) : undefined;\n }\n #projectedFacts(model: AnyModel): ProjectedFacts | undefined {\n const name = model[\"~\"].names.ts!;\n const facts = memo(this.#projected, name, () => {\n const keys = new Map<string, DeclaredEvidence>();\n const gates = new Map<string, FieldGate>();\n for (const [layer, verbs] of (\n this.rows.verbs?.get(name) ?? []\n ).entries()) {\n if (verbs === undefined) continue;\n const { evidence, read } = verbs;\n if (evidence)\n keys.set(\n evidence.as,\n freeze({\n layer,\n read,\n names: evidence.names,\n ordered: evidence.ordered,\n })\n );\n for (const [field, input] of verbs.reads)\n gates.set(field, [\n ...(gates.get(field) ?? []),\n freeze([layer, read, input] as const),\n ]);\n }\n const known: FieldGate[] = [];\n for (const [field, gate] of gates)\n gates.set(field, sharedGate(freeze(gate), known));\n return keys.size === 0 && gates.size === 0\n ? null\n : freeze({ keys, gates });\n });\n return facts ?? undefined;\n }\n /**\n * The read view under this domain for `call`: one for every call, whose\n * lifetime is the domain's, unless the call carries the values its\n * parameters read.\n */\n reads(call: CallScope): Queries {\n return call.rows.values === undefined\n ? (this.#view ??= this.#queries.under(this))\n : this.#queries.under(this, call);\n }\n /**\n * `model`'s predicate for `purpose` without the `excluded` layers, and,\n * under a `judgement`, each layer's predicates of its verb: `delete`'s, or\n * one per field an update writes (that field's own, else `update`'s), or\n * `update`'s when it writes none (R3). `undefined` where it states none.\n */\n selector(\n model: AnyModel,\n purpose: RowPurpose,\n excluded = NO_LAYERS,\n judgement?: RowJudgement\n ): PreparedSelector | undefined {\n const name = model[\"~\"].names.ts!;\n const verbs = this.rows.verbs?.get(name);\n const judged = verbs && judgement;\n // The plain key allocates nothing: a read takes it at every lookup.\n const key = judged\n ? `${name} ${excluded} ${judged.verb}${judged.marks ? \"+\" : \"\"} ${[...judged.writes].sort()}`\n : excluded.length === 0\n ? name\n : `${name} ${excluded}`;\n let prepared = this.#prepared[purpose].get(key);\n if (prepared === undefined)\n prepared = this.#prepareSelector(model, purpose, excluded, judged, key);\n return prepared ?? undefined;\n }\n /** {@link selector}'s answer, prepared once per key. */\n #prepareSelector(\n model: AnyModel,\n purpose: RowPurpose,\n excluded: readonly number[],\n judged: RowJudgement | undefined,\n key: string\n ): PreparedSelector | null {\n const name = model[\"~\"].names.ts!;\n const inputs = this.rows[purpose].get(name);\n const verbs = this.rows.verbs?.get(name);\n const queries = this.#queries;\n const prepared = memo(this.#prepared[purpose], key, () => {\n if (inputs === undefined && verbs === undefined) return null;\n const parts: PreparedSelector[] = [];\n const layers = Math.max(inputs?.length ?? 0, verbs?.length ?? 0);\n for (let layer = 0; layer < layers; layer++) {\n if (excluded.includes(layer)) continue;\n const own = verbs?.[layer];\n const wheres = [\n ...(own ? [own.read] : []),\n ...(inputs?.[layer] === undefined ? [] : [inputs[layer]!]),\n ...(own && judged ? verbInputs(own, judged) : []),\n ].map((where) =>\n memo(this.#inputs, where, () => queries.prepareSelector(model, where))\n );\n if (wheres.length === 0) continue;\n const part =\n wheres.length === 1\n ? wheres[0]!\n : queries.andSelectors(model, wheres);\n parts.push(\n part.predicate === undefined\n ? part\n : freeze({\n ...part,\n predicate: layerOf(layer, name, part.predicate),\n })\n );\n }\n if (parts.length === 0) return null;\n return parts.length === 1\n ? parts[0]!\n : queries.andSelectors(model, parts);\n });\n return prepared;\n }\n readonly #produced = new Map<string, PreparedSelector | null>();\n /**\n * What the row a write of `model` produces is judged at, as a value,\n * against the rows as they stand before the write (R4): a created row\n * (no `judgement`) at each layer's `place`; an updated one at the\n * predicates that judged its old row, `read` and its verb's (WITH CHECK),\n * and its written fields' `moves`. A write that states its candidates'\n * judgement in its own statement names the fields it `assigned`: where it\n * assigns none of what judged its old row, that judgement is the old\n * row's and is not stated twice. `undefined` where no layer judges it: no\n * verbs, no `place` for a create, a delete, an update nothing judges.\n */\n produced(\n model: AnyModel,\n judgement?: RowJudgement,\n assigned?: readonly string[]\n ): PreparedSelector | undefined {\n if (judgement?.verb === \"delete\") return undefined;\n const name = model[\"~\"].names.ts!;\n const verbs = this.rows.verbs?.get(name);\n if (verbs === undefined) return undefined;\n const queries = this.#queries;\n const changed = assigned && new Set(assigned);\n const keys = queries.schema.keys(model);\n const prepare = (where: Input) =>\n memo(this.#inputs, where, () => queries.prepareSelector(model, where));\n const prepared = memo(\n this.#produced,\n judgement\n ? `update ${name} ${[...judgement.writes].sort()} ${assigned ? [...assigned].sort() : \"*\"}`\n : `create ${name}`,\n () => {\n const parts: PreparedSelector[] = [];\n for (const [layer, own] of verbs.entries()) {\n if (own === undefined) continue;\n // What judged the old row judges the new one, unless the write\n // assigns nothing it reads: then the new row's answer is the old\n // row's, which the statement's own candidates already state.\n const checked = judgement\n ? [own.read, ...verbInputs(own, judgement)]\n : [];\n const unchanged =\n changed !== undefined &&\n checked.every(\n (where) =>\n prepare(where).predicate === undefined ||\n !readsAny(prepare(where).predicate!, changed, keys)\n );\n const wheres = judgement\n ? [\n ...(unchanged ? [] : checked),\n ...judgement.writes.flatMap((field) => {\n const move = own.moves.get(field);\n return move === undefined ? [] : [move];\n }),\n ]\n : own.place === undefined\n ? []\n : [own.place];\n if (wheres.length === 0) continue;\n const selectors = [...new Set(wheres)].map(prepare);\n const part =\n selectors.length === 1\n ? selectors[0]!\n : queries.andSelectors(model, selectors);\n if (part.predicate !== undefined)\n parts.push(\n freeze({\n ...part,\n predicate: layerOf(layer, name, part.predicate),\n })\n );\n }\n if (parts.length === 0) return null;\n return parts.length === 1\n ? parts[0]!\n : queries.andSelectors(model, parts);\n }\n );\n return prepared ?? undefined;\n }\n /**\n * The self relations whose links an update judged at `judgement` must\n * keep acyclic (R4): each layer's `acyclic` relations of `model` whose key\n * fields it writes.\n */\n cycles(model: AnyModel, judgement: RowJudgement): readonly string[] {\n if (judgement.verb === \"delete\") return NO_RELATIONS;\n const verbs = this.rows.verbs?.get(model[\"~\"].names.ts!);\n if (verbs === undefined) return NO_RELATIONS;\n const relations = new Set<string>();\n const written = (relation: string) => {\n const edge = this.#queries.schema.membership(model, relation);\n return (\n judgement.writes.includes(relation) ||\n (edge.kind === \"reference\" &&\n edge.pairs.some((pair) => judgement.writes.includes(pair.source)))\n );\n };\n for (const own of verbs) {\n const acyclic = own?.acyclic;\n if (acyclic === undefined) continue;\n const named = Array.isArray(acyclic)\n ? acyclic\n : (acyclic as LazyRelations).candidates.some(written)\n ? (acyclic as LazyRelations).resolve()\n : NO_RELATIONS;\n for (const relation of named)\n if (written(relation)) relations.add(relation);\n }\n return relations.size === 0 ? NO_RELATIONS : [...relations];\n }\n}\nconst NO_RELATIONS: readonly string[] = Object.freeze([]);\n\n/** The verb predicates one layer's `judgement` takes, each once. */\nfunction verbInputs(verbs: ModelVerbs, judgement: RowJudgement): Input[] {\n if (judgement.verb === \"delete\") return [verbs.delete];\n if (judgement.writes.length === 0) return [verbs.update];\n return [\n ...new Set([\n ...judgement.writes.map(\n (field) => verbs.writes.get(field) ?? verbs.update\n ),\n ...(judgement.marks ? [verbs.delete] : []),\n ]),\n ];\n}\n\n/**\n * `node`'s predicate with its conditions folded as `key` says (one digit per\n * condition), and the parameters it still reads: once per key and node.\n */\nfunction foldedLayer(\n node: Extract<PreparedPredicate, { kind: \"layer\" }>,\n key: string\n): Folded {\n const predicate =\n node.conditions.length === 0\n ? node.predicate\n : foldConditions(\n node.predicate,\n (condition) => key[node.conditions.indexOf(condition)] === \"1\"\n );\n const parameters = new Map<Parameter, boolean>();\n callReads(predicate, parameters, new Set());\n const folded = { predicate, parameters: [...parameters] };\n node.folded.set(key, folded);\n return folded;\n}\n/** `predicate` as `model`'s domain predicate of `layer`. */\nfunction layerOf(\n layer: number,\n model: string,\n predicate: PreparedPredicate\n): PreparedPredicate {\n const conditions = new Set<Condition>();\n callReads(predicate, new Map(), conditions);\n return freeze({\n kind: \"layer\",\n layer,\n model,\n predicate,\n conditions: freeze([...conditions]),\n folded: new Map(),\n });\n}\n\n/** Generated boolean sets must not inherit a provider's linear expression depth. */\nfunction balancedOr<T>(\n items: readonly T[],\n join: (items: readonly T[]) => T\n): T {\n const build = (start: number, end: number): T => {\n if (end - start < 2) return end === start ? join([]) : items[start]!;\n const middle = start + Math.floor((end - start) / 2);\n return join([build(start, middle), build(middle, end)]);\n };\n return build(0, items.length);\n}\n\nexport class Queries {\n readonly schema: EngineSchema;\n readonly adapter: DatabaseAdapter;\n #nextAlias = 0;\n readonly #views: QueryViews;\n /**\n * The DRIVER's own representation rules (D-17). Scalar meaning is owned by\n * the existing codecs, but \"what shape does THIS transport hand back?\" is\n * owned by the driver and the adapter — SQLite stores `json` as TEXT and\n * booleans as 0/1, MySQL hands back naive wall-clock datetimes — and that\n * chain is declared, implemented by every adapter and driver, and was\n * reached by nothing. The decoder asks it once per row value, at the row\n * boundary, and never for a value a JSON window already decoded.\n */\n readonly #result: DriverResultParser | undefined;\n /**\n * The row domain this `Queries` reads under: every to-many relation it\n * correlates, and every root read or lookup that names a purpose. Absent on\n * every path of a client without `rows`.\n */\n readonly domain: PreparedDomain | undefined;\n /** The call whose values the domain's parameters read. */\n readonly #call: CallScope | undefined;\n /**\n * The layers whose predicates are lowering here, outermost first: inside\n * one, a relation read takes every other layer at its default (R5). On this\n * `Queries`, so the statement keeps its one alias counter.\n */\n #excluded: number[] | undefined;\n /**\n * The produced row a judgement is lowering over ({@link holds}): the alias\n * it is read under, and per field whether the value the write sets is\n * null, where the write states it.\n */\n #known:\n | { readonly alias: string; readonly nulls: ReadonlyMap<string, boolean> }\n | undefined;\n /**\n * The statement part lowering here reads a masked window (K5): its read-\n * gated columns are already NULL where their rows do not carry them.\n */\n #masked = false;\n /**\n * The relation filter bodies of the statement lowering here, where the\n * adapter shares them ({@link sharingBodies}).\n */\n #shared: SharedBodies | undefined;\n readonly #sharesBodies: boolean;\n constructor(\n schema: EngineSchema,\n adapter: DatabaseAdapter,\n result?: DriverResultParser,\n domain?: PreparedDomain,\n call?: CallScope\n ) {\n this.schema = schema;\n this.adapter = adapter;\n this.#views = schema.queryViews(adapter);\n this.#result = result;\n this.domain = domain;\n this.#call = call;\n this.#sharesBodies =\n adapter.capabilities.sharesRelationBodies === true &&\n !resemblesAlias(adapter.namespace ?? \"\") &&\n !hasAliasLikeNames(schema);\n }\n /**\n * `build`'s statement, where the adapter shares relation bodies\n * (`capabilities.sharesRelationBodies`): each body the statement lowers\n * more than once is stated once, in a `WITH` before it, as the key set\n * every arm repeating it tests ({@link relationExists}); a body lowered once\n * keeps its place, so a statement that repeats none is unchanged. One scope\n * per statement: a statement lowered inside another's joins it.\n */\n #sharingBodies(build: () => Sql): Sql {\n if (this.#shared !== undefined) return build();\n const shared: SharedBodies = { byKey: new Map(), order: [] };\n this.#shared = shared;\n let statement: Sql;\n try {\n statement = build();\n } finally {\n this.#shared = undefined;\n }\n const definitions: { name: string; query: Sql }[] = [];\n for (const body of shared.order) {\n const repeated = body.slots.length > 1;\n for (const placed of body.slots)\n placed.slot.settle(repeated ? placed.use : placed.inline);\n if (repeated) definitions.push({ name: body.name, query: body.query });\n }\n return definitions.length === 0\n ? statement\n : sql`${this.adapter.cte.with(definitions)} ${statement}`;\n }\n /**\n * A write's statement, sharing its bodies where the adapter does: every\n * repeated body its WHERE (and its produced row's judgement) lowers is one\n * `WITH` member ahead of the `UPDATE` or `DELETE`, as a read's is.\n */\n sharing(build: () => Sql): Sql {\n return this.#sharing(build)!;\n }\n /** `build`'s statement, sharing its bodies where the adapter does. */\n #sharing(build: () => Sql | undefined): Sql | undefined {\n if (!this.#sharesBodies) return build();\n let built = true;\n const statement = this.#sharingBodies(() => {\n const made = build();\n built = made !== undefined;\n return made ?? sql.empty;\n });\n return built ? statement : undefined;\n }\n /** This view's `Queries` reading under `domain`, for `call`'s values. */\n under(domain: PreparedDomain, call?: CallScope): Queries {\n return new Queries(this.schema, this.adapter, this.#result, domain, call);\n }\n /**\n * The domain predicate a lowering-time read takes for `model`: the call's\n * own outside every layer, under `judgement` for a write; inside one, the\n * defaults' without the layers lowering, which a policy's traversal only\n * reads.\n */\n #scope(\n model: AnyModel,\n purpose: RowPurpose,\n judgement?: RowJudgement\n ): PreparedSelector | undefined {\n const excluded = this.#excluded;\n return excluded === undefined || excluded.length === 0\n ? this.domain?.selector(model, purpose, NO_LAYERS, judgement)\n : this.domain?.defaults.selector(model, purpose, excluded);\n }\n /**\n * The domain predicate a read lowering here takes for `model` and\n * `purpose`; `undefined` where it states none, or the call drops all it\n * states (R6), so the statement is the one without a domain.\n */\n domainOf(\n model: AnyModel,\n purpose: RowPurpose,\n judgement?: RowJudgement\n ): PreparedSelector | undefined {\n const scope = this.#scope(model, purpose, judgement);\n return scope && !this.#drops(scope.predicate) ? scope : undefined;\n }\n /** Whether a layer's predicates are lowering here. */\n get #lowersLayer(): boolean {\n return (this.#excluded?.length ?? 0) > 0;\n }\n get #values(): CallValues | undefined {\n return this.#call?.rows.values;\n }\n #instantOf: (() => Date) | undefined;\n /**\n * The call's one instant: a domain that reads it lowers for its call. Made\n * when first read, so a `Queries` whose domain reads no value makes none.\n */\n get #instant(): () => Date {\n return (this.#instantOf ??= () => this.#call!.instant());\n }\n /**\n * A layer's predicate for this call: its conditions folded, then R6 for\n * the values it still reads; `undefined` where it drops.\n */\n #resolve(\n node: Extract<PreparedPredicate, { kind: \"layer\" }>\n ): PreparedPredicate | undefined {\n const values = this.#values;\n const { conditions } = node;\n let key = \"\";\n // biome-ignore lint/style/useForOf: no iterator on a per-statement path (E5.1, measured).\n for (let index = 0; index < conditions.length; index++)\n key += conditions[index]!.holds(values, this.#instant) ? \"1\" : \"0\";\n const folded = node.folded.get(key) ?? foldedLayer(node, key);\n let dropped = false;\n const { parameters } = folded;\n // biome-ignore lint/style/useForOf: no iterator on a per-statement path (E5.1, measured).\n for (let index = 0; index < parameters.length; index++) {\n const [parameter, spread] = parameters[index]!;\n const value = parameter.read(values, this.#instant);\n if (value !== undefined && (!spread || Array.isArray(value))) continue;\n if (values?.required(parameter.control!, node.model))\n return VACUOUS_FALSE;\n dropped = true;\n }\n return dropped ? undefined : folded.predicate;\n }\n /**\n * The ONE provider continuation for a physical value of `type`, bound to\n * THIS execution's driver and adapter: the driver first (it owns the\n * transport's own spellings), then the adapter (it owns the dialect's), then\n * the engine's strict codec, which is the caller of the reader this returns.\n *\n * The driver's `next(value, type)` hands the adapter its value only: the\n * adapter is always asked about the leaf's own `type`. The adapter's `next()`\n * — or `next(undefined)` — answers the value the ADAPTER was handed, which is\n * the driver's transformed one, and either leg may answer without calling\n * `next` at all.\n *\n * A provider that raises the library's own error has already said what went\n * wrong, and that error reaches the caller intact; only a FOREIGN throw is\n * reported as a malformed scalar.\n *\n * The reader holds a driver's parser, so it belongs to the execution that\n * built this `Queries`, never to a shared leaf or projection: a borrowed\n * transaction may bind a different driver to the same prepared shape.\n */\n private fieldReader(type: string): FieldReader {\n const adapter = this.adapter.result;\n const adapterLeg = (input: unknown): unknown =>\n adapter.parseField(input, type, (transformed?: unknown) =>\n transformed === undefined ? input : transformed\n );\n const driverParse = this.#result?.parseField;\n return (value) => {\n try {\n return driverParse\n ? driverParse(value, type, adapterLeg)\n : adapterLeg(value);\n } catch (error) {\n if (\n error instanceof InvalidScalarResult ||\n error instanceof VibORMError\n )\n throw error;\n throw new InvalidScalarResult(type, \"provider scalar decoding failed\");\n }\n };\n }\n /**\n * ONE operation's raw result, through the same provider chain at the RESULT\n * boundary that {@link fieldReader} walks at the row-value boundary: the\n * driver first (it owns what its own TRANSPORT answers for a verb), then the\n * adapter (it owns what its DIALECT answers for one), then the engine's\n * decoder, which is the caller of this function and the one authority on what\n * a `count`/`exist` answer means: it asks for `_count` and reads `_count`\n * back. Neither provider leg says anything today: Arnaud's D-35 deleted the\n * SQLite drivers' count/exists arm and his D-40 the two adapter legs (MySQL's\n * count-column normalisation, PostgreSQL's bigint conversion), all three\n * measured answering `undefined` on every live operation of both routes.\n *\n * The other half of D-17 (Arnaud's D-28): `DriverResultParser.parseResult` is\n * a public driver contract — a driver may wrap the raw result of an operation\n * ONCE, before decoding — and it reached nothing after the result engine was\n * retired. Asked here, it is asked once per OPERATION, never per statement\n * and never per member, and the same way for live and prepared execution\n * (rule 7).\n */\n decodeResult(\n raw: Input[],\n operation: Operation,\n decode: (rows: Input[]) => Input[]\n ): Input[] {\n const adapterDecode = (input: unknown): unknown =>\n this.adapter.result.parseResult(\n input,\n operation,\n (transformed?: unknown) =>\n decode((transformed === undefined ? input : transformed) as Input[])\n );\n const driverParse = this.#result?.parseResult;\n return (\n driverParse\n ? driverParse(raw, operation, (input: unknown) => adapterDecode(input))\n : adapterDecode(raw)\n ) as Input[];\n }\n alias(): string {\n return `q${this.#nextAlias++}`;\n }\n /**\n * The FIRST alias of one statement, which opens that statement's alias scope.\n *\n * An alias is a fact of the statement it names, not of this owner's history,\n * so a statement whose first alias is minted by one of the owners named\n * below starts at `q0`, and the same logical query always emits the same\n * text. Without it the engine-lifetime read owner\n * (`commands/index.ts`) minted `q0, q1, … q10000` for the SAME\n * `findUnique`, so its statement text was unique per call — measured as an\n * obstacle by the cutover protocol (`g4/cutover/protocol.md` §7.2) and a\n * guaranteed miss for any transport that caches by statement text\n * (PostgreSQL named statements, `mysql2`'s prepare cache, D1/PlanetScale).\n *\n * The statement owners are {@link select}, {@link aggregated},\n * {@link grouped}, {@link selectSeries} and {@link junction} — every method\n * here that assembles a complete statement —\n * and each calls this before any other alias of that statement. Nothing else\n * may: a `lower…` fragment continues the statement it is part of, because a\n * mutation statement is assembled from several of them by the physical owner\n * (`OperationContext`'s `lowerMutationLimit` + `lowerProjection` pair) and\n * two fragments of ONE statement must not both start at `q0`. For the same\n * reason no statement owner may be entered while another statement is being\n * built: a nested complete statement is a subquery of its parent and shares\n * the parent's scope, which is why the nested relation projection, the\n * correlated count and the cursor window mint plain {@link alias}es.\n */\n #rootAlias(): string {\n this.#nextAlias = 0;\n return this.alias();\n }\n table(model: AnyModel, alias?: string): Sql {\n return this.adapter.identifiers.table(model[\"~\"].names.sql!, alias);\n }\n column(model: AnyModel, field: string, alias?: string): Sql {\n const name = this.columnName(model, field);\n return alias\n ? this.adapter.identifiers.column(alias, name)\n : this.adapter.identifiers.escape(name);\n }\n columnName(model: AnyModel, field: string): string {\n return physicalField(this.schema, model, field).name;\n }\n /**\n * A raw `Sql` operand is PARENTHESIZED. A caller's fragment is an\n * expression, not a token: `views: { gte: ctx => ctx.sql\\`SELECT MAX(...)\\` }`\n * composed as `\"views\" >= SELECT MAX(…)` is a syntax error on every dialect,\n * and a fragment with its own operator would re-associate. The shipped\n * engine wrapped at this same seam (`where-builder.ts:472`, applied `:492`).\n */\n value(value: unknown): Sql {\n return value instanceof Sql\n ? callerText(value)\n : this.adapter.literals.value(value);\n }\n /**\n * The one destination-aware operand owner: filters, cursors, order operands,\n * assignments and reference values all bind a value through this function,\n * so a column is never written in one vocabulary and read in another.\n */\n fieldValue(model: AnyModel, field: string, value: unknown): Sql {\n return this.#scalarValue(\n physicalField(this.schema, model, field).scalar,\n value,\n field,\n this.scalarShape(model, field).id\n );\n }\n /**\n * `id` is the destination column's identifier storage, which the scalar\n * alone cannot answer: a foreign key DERIVES its domain and a private\n * carrier column names the key it stands in for. Only a COLUMN operand\n * carries native storage; min/max operands additionally pass through the\n * same transport expression their aggregate reads.\n */\n #scalarValue(\n scalar: Scalar,\n value: unknown,\n field: string,\n id?: IdentifierColumn\n ): Sql {\n const a = this.adapter;\n const state = scalar[\"~\"].state;\n if (value instanceof Sql) {\n const fragment = callerText(value);\n return state.type === \"decimal\" && state.array !== true\n ? a.expressions.decimalCast(fragment, state.decimal)\n : fragment;\n }\n const sentinel = jsonNullKindOf(value);\n if (sentinel)\n return sentinel === \"DbNull\" ? a.literals.null() : a.json.value(null);\n if (value === null || value === undefined) return a.literals.null();\n if (state.array === true && Array.isArray(value))\n return this.#listValue(state, value, field);\n // A COMPACT identifier binds its physical form — the payload's bytes, or\n // a PostgreSQL `uuid`'s canonical text — through the adapter's one\n // identifier literal. A text-stored domain holds the public string itself\n // and takes the ordinary arm below, byte for byte what it took before.\n if (isCompact(id))\n return a.literals.id(encodeIdentifier(id, value), id.representation);\n switch (state.type) {\n case \"bigint\":\n return a.literals.value(state.array === true ? String(value) : value);\n case \"decimal\":\n case \"json\":\n case \"point\":\n case \"vector\":\n case \"datetime\":\n case \"date\":\n case \"time\":\n return this.#typedScalarValue(scalar, value, field);\n default:\n return a.literals.value(value);\n }\n }\n /** The scalars whose operand spelling depends on their type, out of line. */\n #typedScalarValue(scalar: Scalar, value: unknown, field: string): Sql {\n const a = this.adapter;\n const state = scalar[\"~\"].state;\n // A single value bound against a LIST field is one MEMBER of that field's\n // container (`has` is the operator that asks for one), and a container\n // carries what it was WRITTEN with — the same fact {@link nativeType}\n // already states for the decode leaf, which refuses to hand a list's\n // native type to a literal. The two scalars whose column spelling is\n // PHYSICAL have to consume it: a decimal's exact `DECIMAL(p,s)` operand\n // cast, and a datetime's dialect rendering of the instant (MySQL's naive\n // `DATETIME`, which a JSON container has no column to hold). Every other\n // scalar crosses a container exactly as it crosses its column.\n const member = state.array === true;\n switch (state.type) {\n case \"decimal\":\n return member\n ? a.literals.value(\n decimalMembers(state, [value], field, this.adapter.result)[0]!\n )\n : a.literals.decimal(\n canonicalDecimal(value, field),\n requireDecimal(state, field)\n );\n case \"json\":\n return a.literals.json(value);\n case \"point\":\n return this.#geoPoint(\"value\").value(\n this.value((value as GeoPoint).longitude),\n this.value((value as GeoPoint).latitude)\n );\n case \"vector\":\n // Providers without a native vector tier store the admitted JSON array.\n return a.capabilities.supportsVector\n ? a.vector.literal(value as number[])\n : a.literals.json(value);\n case \"datetime\": {\n const wire = admittedTemporal(value, validateIsoTimestamp);\n return typeof wire === \"string\"\n ? a.literals.dateTime(\n wire,\n member ? undefined : this.#nativeType(scalar),\n member\n )\n : a.literals.value(wire);\n }\n case \"time\": {\n const admitted = validateIsoTime(value);\n return a.literals.value(\"value\" in admitted ? admitted.value : value);\n }\n case \"date\": {\n const wire = admittedTemporal(value, validateIsoDate);\n return typeof wire === \"string\"\n ? a.literals.dateTime(wire, undefined, member)\n : a.literals.value(wire);\n }\n default:\n return a.literals.value(value);\n }\n }\n /** A whole list, bound as the container the destination column stores. */\n #listValue(\n state: ScalarState,\n values: readonly unknown[],\n field: string\n ): Sql {\n if (state.type === \"decimal\")\n return this.adapter.arrays.value(\n decimalMembers(state, values, field, this.adapter.result)\n );\n return state.type === \"enum\"\n ? this.adapter.arrays.enumValue([...values])\n : this.adapter.arrays.value(\n [...values],\n state.type === \"datetime\" || state.type === \"date\"\n ? state.type\n : undefined\n );\n }\n /** The declared native form of a column; a list's members live in its container. */\n #nativeType(scalar: Scalar): NativeTypeDeclaration | undefined {\n return scalar[\"~\"].state.array === true\n ? undefined\n : scalar[\"~\"].nativeType;\n }\n /** The provider's settled point protocol, or its named capability refusal. */\n #geoPoint(usage: string): GeoPointSql {\n const geoPoint = this.adapter.geoPoint;\n if (!geoPoint)\n throw new FeatureNotSupportedError(\n \"point\",\n usage,\n \"GeoPoint requires a provider with its physical point tier enabled.\"\n );\n return geoPoint;\n }\n projectedColumn(model: AnyModel, field: string, alias?: string): Sql {\n const column = this.column(model, field, alias);\n const leaf = this.scalarShape(model, field);\n const state = physicalField(this.schema, model, field).scalar[\"~\"].state;\n if (state.type === \"bigint\" && state.array !== true)\n return this.adapter.expressions.cast(column, \"text\");\n if (\n state.array === true &&\n (state.type === \"bigint\" || state.type === \"number\")\n )\n return this.adapter.arrays.exactNumericProjection(column);\n if (\n state.type === \"decimal\" ||\n (state.type === \"point\" && state.array !== true)\n )\n return this.#projectedTypedColumn(state, column);\n return transportedIdentifier(this.adapter, leaf.id, column, leaf.nullable);\n }\n /** A decimal or point column's projection spelling, out of line. */\n #projectedTypedColumn(state: ScalarStateOf, column: Sql): Sql {\n if (state.type === \"decimal\")\n return state.array === true\n ? this.adapter.arrays.exactNumericProjection(column)\n : this.adapter.expressions.cast(column, \"text\");\n // A scalar point: a JSON document of its two coordinates.\n const geoPoint = this.#geoPoint(\"projection\");\n const projected = this.adapter.json.objectFromColumns([\n [\n \"longitude\",\n this.adapter.json.document(\n this.adapter.json.number(geoPoint.longitude(column))\n ),\n ],\n [\n \"latitude\",\n this.adapter.json.document(\n this.adapter.json.number(geoPoint.latitude(column))\n ),\n ],\n ]);\n return state.nullable\n ? this.adapter.expressions.caseWhen(\n [\n {\n when: this.adapter.operators.isNull(column),\n then: this.adapter.literals.null(),\n },\n ],\n projected\n )\n : projected;\n }\n /**\n * A projected value carried INSIDE a JSON document. A value that is already\n * JSON stays a document; a value the container would round stays exact text.\n */\n #carriedValue(leaf: Shape | Leaf, expression: Sql): Sql {\n if (leaf.kind !== \"scalar\") return this.adapter.json.document(expression);\n // A decimal crossed the projection in the spelling {@link projectedColumn}\n // states — a text cast for a scalar, the adapter's decimal array\n // projection for a list — and its codec reads an exact value only from\n // that spelling: carried as a JSON number it is rounded by the container,\n // and carried as a JSON array its members are. This is the same physical\n // fact the projection stated, consumed rather than re-derived from the leaf.\n if (\n leaf.type === \"decimal\" ||\n ((leaf.type === \"bigint\" || leaf.type === \"number\") && leaf.list)\n )\n return leaf.list\n ? this.adapter.arrays.exactNumericProjection(expression)\n : this.adapter.expressions.cast(expression, \"text\");\n if (\n leaf.list ||\n leaf.type === \"json\" ||\n leaf.type === \"point\" ||\n leaf.type === \"vector\"\n )\n return this.adapter.json.document(expression);\n if (leaf.type === \"bigint\")\n return this.adapter.expressions.cast(expression, \"text\");\n if (leaf.type === \"number\") return this.adapter.json.number(expression);\n if (leaf.type === \"blob\")\n return this.adapter.expressions.caseWhen(\n [\n {\n when: this.adapter.operators.isNull(expression),\n then: this.adapter.literals.null(),\n },\n ],\n this.adapter.expressions.blobToHex(expression)\n );\n return expression;\n }\n /**\n * One field's decoded leaf, resolved once per (adapter, model, field).\n *\n * The answer is the field's declared scalar, its nullability and the\n * adapter's representation of it — schema and dialect only — so rebuilding a\n * fresh frozen object (and a fresh enum `Set`) on every projection of every\n * operation was pure repetition (rule 1). Nothing consumes a leaf by\n * identity: the decoder, the cache codec and the shape readers all read its\n * fields.\n */\n private scalarShape(model: AnyModel, field: string): Leaf {\n let leaves = this.#views.leaves.get(model);\n if (leaves === undefined) {\n leaves = new Map();\n this.#views.leaves.set(model, leaves);\n }\n let shape = leaves.get(field);\n if (shape === undefined) {\n const physical = physicalField(this.schema, model, field);\n shape = this.#leaf(\n physical.scalar,\n physical.nullable,\n identifierColumn(\n this.adapter,\n this.schema.index,\n model,\n field,\n physical\n )\n );\n leaves.set(field, shape);\n }\n return shape;\n }\n #leaf(\n scalar: Scalar,\n nullable: boolean,\n id: IdentifierColumn | undefined\n ): Leaf {\n const state = scalar[\"~\"].state;\n return freeze({\n kind: \"scalar\",\n type: state.type,\n nullable,\n scalar,\n list: state.array === true ? true : undefined,\n decimal: state.type === \"decimal\" ? state.decimal : undefined,\n dateTime:\n state.type === \"datetime\"\n ? (this.adapter.result.dateTimeRepresentation?.(\n this.#nativeType(scalar)\n ) ?? \"text\")\n : undefined,\n enumValues:\n state.type === \"enum\" && \"enumValues\" in scalar\n ? new Set(scalar.enumValues as readonly string[])\n : undefined,\n dimension: state.dimension,\n id,\n });\n }\n junctionWhere(\n edge: Extract<Membership, { kind: \"junction\" }>,\n values: Input,\n alias?: string\n ): Sql {\n return this.adapter.operators.and(\n ...[edge.sourceSide, edge.targetSide].flatMap((side) =>\n side.members\n .filter((pair) => Object.hasOwn(values, pair.junctionField))\n .map((pair) =>\n this.adapter.operators.eq(\n alias\n ? this.adapter.identifiers.column(alias, pair.junctionField)\n : this.adapter.identifiers.escape(pair.junctionField),\n this.fieldValue(\n side.model,\n pair.referencedField,\n values[pair.junctionField]\n )\n )\n )\n )\n );\n }\n junctionSideConditions(\n side: ResolvedJunctionSide,\n junctionAlias: string | undefined,\n endpoint: string | Input\n ): Sql[] {\n const a = this.adapter;\n return side.members.map((pair) =>\n a.operators.eq(\n junctionAlias\n ? a.identifiers.column(junctionAlias, pair.junctionField)\n : a.identifiers.escape(pair.junctionField),\n typeof endpoint === \"string\"\n ? this.column(side.model, pair.referencedField, endpoint)\n : this.fieldValue(\n side.model,\n pair.referencedField,\n endpoint[pair.referencedField]\n )\n )\n );\n }\n junction(\n edge: Extract<Membership, { kind: \"junction\" }>,\n values: Input,\n forUpdate = false\n ): Query {\n const a = this.adapter;\n const alias = this.#rootAlias();\n const owner =\n edge.uniqueSide === \"target\" ? edge.sourceSide : edge.targetSide;\n const fields: Record<string, Leaf> = {};\n const columns = owner.members.map((pair) => {\n const shape = this.scalarShape(owner.model, pair.referencedField);\n fields[pair.junctionField] = shape;\n const column = a.identifiers.column(alias, pair.junctionField);\n return a.identifiers.aliased(\n shape.type === \"decimal\" || shape.type === \"bigint\"\n ? a.expressions.cast(column, \"text\")\n : transportedIdentifier(a, shape.id, column, shape.nullable),\n pair.junctionField\n );\n });\n return {\n sql: assembleAdapterSelect(a, {\n columns: sql.join(columns, \", \"),\n from: a.identifiers.table(edge.table, alias),\n where: this.junctionWhere(edge, values, alias),\n forUpdate,\n }),\n shape: { kind: \"object\", fields },\n };\n }\n /** The payload {@link readUpdate} reads, refused where it cannot run. */\n #prepareUpdate(\n model: AnyModel,\n field: string,\n value: unknown\n ): PreparedUpdate {\n const update = readUpdate(value);\n // An exact decimal divided by zero fails HERE, before any statement is\n // issued: the operand's value is knowable and every dialect answers it\n // differently otherwise (SQLite NULL, MySQL NULL or an error,\n // PostgreSQL raises). The shipped refusal, verbatim.\n if (\n update.kind === \"arithmetic\" &&\n update.operator === \"divide\" &&\n exactDecimalDomain(\n physicalField(this.schema, model, field).scalar[\"~\"].state\n ) &&\n dividesByZero(update.by)\n )\n throw new QueryEngineError(\n `Cannot divide decimal field '${field}' by zero.`\n );\n return update;\n }\n /**\n * Whether {@link updateValue} names this payload over a known prior value:\n * the answer a counter `upsert` folds on (engine-08). Read before the\n * divide-by-zero refusal, which belongs to an assignment that runs.\n */\n namesUpdate(model: AnyModel, field: string, value: unknown): boolean {\n return this.#named(model, field, readUpdate(value));\n }\n /**\n * A list operator, and an exact decimal's `multiply` or `divide`, have no\n * expression form: the provider's assignment decides the stored result.\n */\n #named(\n model: AnyModel,\n field: string,\n update: PreparedUpdate\n ): update is Exclude<PreparedUpdate, { kind: \"list\" }> {\n if (update.kind !== \"arithmetic\") return update.kind === \"value\";\n return !(\n (update.operator === \"multiply\" || update.operator === \"divide\") &&\n exactDecimalDomain(\n physicalField(this.schema, model, field).scalar[\"~\"].state\n ) !== undefined\n );\n }\n /**\n * The target domain an arithmetic assignment lands back inside: an integer\n * column divides as an integer, an exact decimal is quantized to its scale.\n * The adapter owns both spellings; this only names the destination.\n */\n #arithmeticTarget(model: AnyModel, field: string): ArithmeticTarget {\n const state = physicalField(this.schema, model, field).scalar[\"~\"].state;\n return {\n integer: state.type === \"int\" || state.type === \"bigint\",\n decimal: exactDecimalDomain(state),\n };\n }\n /**\n * One admitted update payload as the provider's own `SET` assignment. Every\n * operator crosses through the adapter's `set` vocabulary, so the dialect owns\n * integer truncation, decimal quantization and list concatenation, and the\n * query owner spells no arithmetic of its own.\n */\n updateAssignment(model: AnyModel, field: string, value: unknown): Sql {\n const a = this.adapter;\n const column = this.column(model, field);\n const update = this.#prepareUpdate(model, field, value);\n if (update.kind === \"value\")\n return a.set.assign(column, this.fieldValue(model, field, update.value));\n if (update.kind === \"list\")\n return a.set[update.operator](\n column,\n this.fieldValue(model, field, update.members)\n );\n return a.set[update.operator](\n column,\n this.fieldValue(model, field, update.by),\n this.#arithmeticTarget(model, field)\n );\n }\n /**\n * The same admitted update payload named over an ALREADY-KNOWN value: the\n * key a row will carry after the mutation, which a non-returning readback and\n * a relation-key transition both have to state in SQL.\n *\n * Every operator is named through the SAME adapter vocabulary its assignment\n * uses, so the expression and the `SET` clause cannot disagree: `+`, `-` and\n * `*` are the dialect's own native arithmetic in every non-decimal domain,\n * and an integer `divide` asks `expressions.integerDivide` for the dialect's\n * truncation — the same provider fact `set.divide`'s `target.integer` flag\n * carries, in expression form.\n *\n * The one shape with no expression form is an EXACT DECIMAL under `multiply`\n * or `divide`: there the provider's assignment is a guarded coefficient\n * rewrite that rounds half-even back to the field's scale and refuses an\n * intermediate the dialect cannot represent, and restating it here would be a\n * second arithmetic owner. The refusal is registered and recorded as a\n * decision for Arnaud (note §R2.1).\n *\n * WHICH PAYLOAD REACHES IT, measured for the N4 census (the earlier reading\n * of this paragraph named the wrong shape). A decimal RELATION key does NOT\n * reach it: a relation key written beside a mutation of that relation must be\n * a literal (`Assignments.requireLiteral`, `commands/relation-body.ts:127`),\n * so no operator survives to be named, and a key transition is the only thing\n * that would ask. The reachable shape is a decimal PRIMARY key on an UPSERT's\n * FOUND arm whose update payload names NO relation: `EngineSchema.admit`\n * states `keyPortabilityRefusal` for `update` / `updateMany`, and the found\n * arm carries it only when the update payload names relations\n * (`commands/commands.ts:1743`, the shipped gate) — so\n * `upsert({ update: { decimalKey: { multiply: n } } })` arrives here through\n * `OperationContext.updatedIdentity`, which has to ADDRESS the row it just\n * wrote. It is a TRANSPORT boundary, not an invariant: the same payload\n * succeeds on a provider with RETURNING, where the post-update key is read\n * back instead of named. Executing it therefore belongs to that read-back's\n * owner (D-50's scratch at the column's declared type), not here; an ordered\n * observation cannot answer it, because what is missing is the row's address,\n * not a value a dependent consumes.\n */\n updateValue(\n model: AnyModel,\n field: string,\n value: unknown,\n before: Sql\n ): Sql {\n const a = this.adapter;\n const update = this.#prepareUpdate(model, field, value);\n if (!this.#named(model, field, update))\n throw new QueryEngineError(\n `Cannot determine the updated value of '${model[\"~\"].names.ts ?? \"unknown\"}.${field}' before '${update.operator}' executes: the database determines the stored result.`\n );\n if (update.kind === \"value\")\n return this.fieldValue(model, field, update.value);\n const state = physicalField(this.schema, model, field).scalar[\"~\"].state;\n const base =\n state.type === \"int\" ? a.expressions.cast(before, \"integer\") : before;\n const operand = this.fieldValue(model, field, update.by);\n if (update.operator === \"increment\")\n return a.expressions.add(base, operand);\n if (update.operator === \"decrement\")\n return a.expressions.subtract(base, operand);\n if (update.operator === \"multiply\")\n return a.expressions.multiply(base, operand);\n return state.type === \"int\" || state.type === \"bigint\"\n ? a.expressions.integerDivide(base, operand)\n : a.expressions.divide(base, operand);\n }\n /**\n * One prepared selector. `unique` states that the caller admitted this\n * `where` as a UNIQUE selector (a `whereUnique` input): its top-level\n * addressable-key entries are the row's discriminator and compare through the\n * constraint, while every other entry — an extended `where`'s filters, its\n * `AND`/`OR`/`NOT` arms and its relation predicates — stays a filter. The\n * same `{ id: … }` object is a discriminator under `findUnique` and a filter\n * under `findFirst`, so the fact belongs to the admitted operation and cannot\n * be recovered from the object's shape.\n * SQL-only consumers omit dependency summaries through `includeFacts`; the\n * unique constraint comparison remains independent of that collection.\n */\n prepareSelector(\n model: AnyModel,\n where?: Input,\n unique?: boolean\n ): PreparedSelector;\n prepareSelector(\n model: AnyModel,\n where: Input | undefined,\n unique: boolean,\n includeFacts: false\n ): Pick<PreparedSelector, \"model\" | \"predicate\">;\n prepareSelector(\n model: AnyModel,\n where?: Input,\n unique = false,\n includeFacts = true\n ): Pick<PreparedSelector, \"model\" | \"predicate\"> {\n if (!includeFacts)\n return freeze({\n model,\n predicate: where\n ? this.#rooted(model, undefined, () =>\n this.#prepareWhere(model, where, undefined, [], unique)\n )\n : undefined,\n });\n const facts = newSelectorFacts();\n const keys = Object.keys(where ?? {});\n const uniqueKey =\n keys.length === 1 ? findAddressableKey(model, keys[0]!) : undefined;\n const selected = uniqueKey\n ? uniqueKey.name\n ? record(where![uniqueKey.name])\n : where!\n : undefined;\n return freeze({\n model,\n facts,\n uniqueKey,\n uniqueValues: selected\n ? new Map(uniqueKey!.fields.map((field) => [field, selected[field]]))\n : undefined,\n predicate: where\n ? this.#rooted(model, facts, () =>\n this.#prepareWhere(model, where, facts, [], unique)\n )\n : undefined,\n });\n }\n /**\n * The rows a predicate being prepared reads, from its root to the relation\n * body it is in: what a `{ $row, up }` names. `sealed` says why a reference\n * may not cross that body.\n */\n #scopes: readonly {\n readonly model: AnyModel;\n readonly facts: SelectorFacts | undefined;\n readonly sealed?: string;\n }[] = [];\n #rooted<T>(\n model: AnyModel,\n facts: SelectorFacts | undefined,\n prepare: () => T\n ): T {\n const scopes = this.#scopes;\n this.#scopes = [{ model, facts }];\n try {\n return prepare();\n } finally {\n this.#scopes = scopes;\n }\n }\n selectorFacts(selector: PreparedSelector): SelectorFacts {\n return selector.facts;\n }\n identitySelector(model: AnyModel, identity: Input): PreparedSelector {\n const facts = newSelectorFacts();\n return freeze({\n model,\n facts,\n predicate: this.identityPredicate(model, identity, facts),\n });\n }\n /** One row's identity as prepared meaning: its key fields' equalities. */\n private identityPredicate(\n model: AnyModel,\n identity: Input,\n facts: SelectorFacts\n ): PreparedPredicate {\n return freeze({\n kind: \"and\",\n predicates: freeze(\n Object.entries(identity).map(([field, value]) =>\n this.#prepareScalarPredicate(model, field, value, facts)\n )\n ),\n });\n }\n /**\n * The complement of a CAPTURED identity set — \"this row is not one of the\n * rows the engine read\" — as prepared meaning.\n *\n * A captured set is identities the engine itself read, so its complement is\n * composed here from {@link identityPredicate}'s equalities under the one\n * combinator owner ({@link combine}), and never spelled as a public\n * `{ NOT: { OR: … } }` payload: N4 lets a model DECLARE a scalar or relation\n * named `NOT`, `OR` or `AND`, and such a payload is then read as that field\n * ({@link combinator}) — the public name wins, as validation admitted it. An\n * internal premise that borrowed public syntax could not survive that, which\n * is why the meaning is stated and only the SQL is spelled.\n *\n * An empty set excludes nothing: it states no condition, so a caller that\n * conjoins it through {@link andSelectors} keeps exactly its own selector —\n * the truth both consumers already carried, one by omitting the bag and the\n * other through the vacuous `NOT` of an empty `OR`.\n */\n excludeIdentities(\n model: AnyModel,\n identities: readonly Input[]\n ): PreparedSelector {\n const facts = newSelectorFacts();\n const captured = this.#capturedSet(model, identities, facts);\n return freeze({\n model,\n facts,\n predicate:\n identities.length === 0 ? undefined : this.combine(\"NOT\", [captured]),\n });\n }\n /**\n * The captured identity set ITSELF — \"this row is one of the rows the engine\n * read\" — and the positive counterpart of {@link excludeIdentities}.\n *\n * D-65 gives the consuming UPDATE/DELETE of a captured ROOT set both facts:\n * the rows the capture named, and the selector it captured them by. This\n * states the first, from the same identities' own equalities under the same\n * combinator owner, so the effect addresses the captured rows with no public\n * payload to collide with a declared `OR` (N4).\n *\n * An empty set names NO row — the vacuous FALSE {@link combine} already\n * states — which is why each caller answers an empty capture before any\n * statement is built.\n */\n includeIdentities(\n model: AnyModel,\n identities: readonly Input[]\n ): PreparedSelector {\n const facts = newSelectorFacts();\n return freeze({\n model,\n facts,\n predicate: this.#capturedSet(model, identities, facts),\n });\n }\n /**\n * The rows of `model` that a visible member still references through one of\n * `slots` — the rows a hard delete meets the database's restrict on. A\n * member is visible when it satisfies its model's inputs in `visible`; one\n * member may be excepted by identity: the parent a nested delete keeps its\n * link to, whose own membership a hard delete removes first.\n */\n referenced(\n model: AnyModel,\n slots: readonly string[],\n visible: PreparedDomain | undefined,\n except?: { readonly slot: string; readonly identity: Input }\n ): PreparedSelector {\n const predicates = slots.map((slot): PreparedPredicate => {\n const edge = bindMembership(this.schema, model, slot);\n const arms: PreparedPredicate[] = [];\n const domain = visible?.selector(edge.target, \"related\")?.predicate;\n if (domain) arms.push(domain);\n if (except?.slot === slot)\n arms.push(\n this.combine(\"NOT\", [\n // The member's own facts: a premise states them, nothing plans on them.\n this.identityPredicate(\n edge.target,\n except.identity,\n newSelectorFacts(false)\n ),\n ])\n );\n // Visibility is the given domain's, never the lowering call's own.\n return Object.freeze({\n kind: \"relation\",\n edge,\n quantifier: \"some\",\n predicate: arms.length === 0 ? undefined : this.combine(\"AND\", arms),\n unscoped: true,\n });\n });\n return Object.freeze({\n model,\n facts: newSelectorFacts(false),\n predicate: this.combine(\"OR\", predicates),\n });\n }\n /** One captured set's rows, as the disjunction of their own identities. */\n #capturedSet(\n model: AnyModel,\n identities: readonly Input[],\n facts: SelectorFacts\n ): PreparedPredicate {\n const keys = getModelKeyCatalog(model).rowKey?.fields;\n const field = keys?.length === 1 ? keys[0] : undefined;\n if (\n field &&\n identities.length > 0 &&\n identities.every(\n (identity) =>\n Object.keys(identity).length === 1 && Object.hasOwn(identity, field)\n )\n )\n return this.#prepareScalarPredicate(\n model,\n field,\n { in: identities.map((identity) => identity[field]) },\n facts\n );\n const captured = identities.map((identity) =>\n this.identityPredicate(model, identity, facts)\n );\n // A SET pins no equality: the facts describe a filter, not a discriminator,\n // exactly as the combinator walker records any `OR` arm.\n if (captured.length > 0) facts.exact = false;\n return balancedOr(captured, (arms) => this.combine(\"OR\", arms));\n }\n andSelectors(\n model: AnyModel,\n selectors: readonly PreparedSelector[]\n ): PreparedSelector {\n const facts = newSelectorFacts();\n const predicates: PreparedPredicate[] = [];\n for (const selector of selectors) {\n for (const field of selector.facts.fields) facts.fields.add(field);\n for (const [field, value] of selector.facts.equals)\n facts.equals.set(field, value);\n for (const [field, value] of selector.facts.keys)\n facts.keys.set(field, value);\n facts.exact &&= selector.facts.exact;\n facts.reads.push(...selector.facts.reads);\n if (selector.predicate) predicates.push(selector.predicate);\n }\n return freeze({\n model,\n facts,\n predicate:\n predicates.length === 0\n ? undefined\n : freeze({\n kind: \"and\",\n predicates: freeze(predicates),\n }),\n });\n }\n /**\n * The key-preserving conjunction: `selector` AND `domain`'s predicate for\n * `purpose`, keeping the selector's unique key, so the consumers that read\n * the key to recover (race convergence, a hidden conflict's rethrow) behave\n * as without a domain; `scoped` tells the ones that trust the key alone to\n * name the row (the RETURNING confirmation fast path, the targeted\n * `ON CONFLICT` fold) that it no longer does. A write's `judgement` adds\n * its verb's predicates. The selector itself where the domain states\n * nothing for its model.\n */\n candidates(\n selector: PreparedSelector,\n purpose: RowPurpose,\n domain: PreparedDomain | undefined = this.domain,\n judgement?: RowJudgement\n ): PreparedSelector {\n const scope = domain?.selector(\n selector.model,\n purpose,\n NO_LAYERS,\n judgement\n );\n if (scope === undefined) return selector;\n return Object.freeze({\n ...this.andSelectors(selector.model, [selector, scope]),\n uniqueKey: selector.uniqueKey,\n uniqueValues: selector.uniqueValues,\n scoped: true,\n ...(judgement && { judgement }),\n });\n }\n /**\n * The rows of `model` a write produces, as ONE FROM item read under\n * `alias`: every stored field, each row's value as `row` lowers it (NULL\n * where it says nothing). The model's own columns type them, through an\n * empty read of the table, so a bound value takes its column's type where\n * PostgreSQL would resolve a bare parameter as text; how the rows follow\n * it is the dialect's (`setOperations.typedRows`), so a chunk is bounded\n * by its binds alone.\n */\n #producedRows(\n model: AnyModel,\n rows: readonly ((field: string) => Sql | undefined)[],\n alias: string\n ): Sql {\n const a = this.adapter;\n const fields = this.schema.storedFields(model);\n const typed = this.alias();\n const from = this.table(model, typed);\n const head = assembleAdapterSelect(a, {\n columns: sql.join(\n fields.map((field) => this.column(model, field, typed)),\n \", \"\n ),\n from,\n where: a.literals.false(),\n });\n return a.setOperations.typedRows(\n {\n head,\n from,\n table: this.table(model),\n alias: typed,\n columns: fields.map((field) => this.columnName(model, field)),\n },\n rows.map((row) => fields.map((field) => row(field) ?? a.literals.null())),\n alias\n );\n }\n /**\n * `judged` over the produced row `from` reads (and, for each `acyclic`\n * relation, the row outside its own subtree), as the adapter's assertion:\n * 1, or the statement that carries it fails before it writes. `undefined`\n * where nothing is left to judge: the call drops every layer `judged` is\n * made of (R6).\n */\n #holds(\n model: AnyModel,\n judged: Pick<PreparedSelector, \"model\" | \"predicate\"> | undefined,\n alias: string,\n nulls: ReadonlyMap<string, boolean>,\n from?: Sql,\n acyclic: readonly string[] = NO_RELATIONS\n ): Sql | undefined {\n const a = this.adapter;\n const outer = this.#known;\n this.#known = { alias, nulls };\n let lowered: Sql | undefined;\n try {\n lowered = judged && this.lowerSelector(judged, alias);\n } finally {\n this.#known = outer;\n }\n const conditions = [\n ...(lowered === undefined ? [] : [lowered]),\n ...acyclic.map((relation) =>\n this.#outsideOwnSubtree(model, relation, alias)\n ),\n ];\n if (conditions.length === 0) return undefined;\n return a.subqueries.scalar(\n a.assertions.holds(a.operators.and(...conditions), from)\n );\n }\n /**\n * The row read as `alias` does not reach itself through `relation`, a\n * to-one relation of its model to itself: no row its new target leads to,\n * that target included, is the row. The walk is physical, read under no\n * domain: a cycle through a row the caller cannot see is still a cycle.\n */\n #outsideOwnSubtree(model: AnyModel, relation: string, alias: string): Sql {\n const a = this.adapter;\n const edge = this.schema.membership(model, relation);\n const { cte, cteName, walk, childColumns } = this.#walk(\n edge,\n alias,\n { depth: false, self: false },\n false\n );\n return a.filters.none(\n sql`${cte} ${assembleAdapterSelect(a, {\n columns: sql.raw(\"1\"),\n from: a.identifiers.aliased(a.identifiers.escape(cteName), walk),\n where: this.#sameRow(\n model,\n alias,\n childColumns.map((name) => a.identifiers.column(walk, name))\n ),\n })}`\n );\n }\n /**\n * The SELECT an INSERT of `rows` reads its values from when the rows it\n * creates are judged (R4): each row a value of the derived table, kept\n * where `judged` holds of it and failing the statement where it does not,\n * before any row is written or any constraint is checked. One statement:\n * nothing it writes is visible to its own judgement.\n */\n producedSource(\n model: AnyModel,\n columns: readonly string[],\n rows: readonly Input[],\n judged: PreparedSelector\n ): Sql | undefined {\n const a = this.adapter;\n const alias = this.alias();\n const written = new Set(columns);\n const from = this.#producedRows(\n model,\n rows.map(\n (row) => (field) =>\n written.has(field)\n ? this.fieldValue(model, field, row[field])\n : undefined\n ),\n alias\n );\n // A field's nullness folds where every row states the same one; a field\n // no row writes is null in each.\n const nulls = new Map<string, boolean>();\n for (const field of this.schema.storedFields(model)) {\n const states = new Set(\n rows.map((row) => {\n const value = written.has(field) ? row[field] : null;\n return value instanceof Sql\n ? undefined\n : value === null || value === undefined;\n })\n );\n const [state] = states;\n if (states.size === 1 && state !== undefined) nulls.set(field, state);\n }\n return this.#sharing(() => {\n const guard = this.#holds(model, judged, alias, nulls);\n if (guard === undefined) return undefined;\n return assembleAdapterSelect(a, {\n columns: sql.join(\n columns.map((field) => this.column(model, field, alias)),\n \", \"\n ),\n from,\n where: sql`${guard} = 1`,\n });\n });\n }\n /**\n * The WHERE of an UPDATE of `model` assigning `values` that judges the\n * rows it produces (R4): the keys of the rows `candidates` selects\n * (lowered at the alias it is handed; the first `limit` in key order),\n * read ONCE, before the statement writes any of them, each group of one\n * key kept where its produced row's assertion holds (the row as it stands\n * with the assignments applied, typed as {@link producedRows}): 1, or the\n * statement fails before it writes.\n *\n * An aggregate is computed over the rows its WHERE kept, so a row the\n * update does not write is never judged: a guard in a select list or a\n * WHERE is not, since PostgreSQL and MySQL flatten an `IN` subquery and\n * order its conditions by cost (measured: a viewed row's refused guard\n * raised before the predicate that excludes it). A set read once is\n * judged against the rows as they stand before the write, never against\n * a row the statement wrote earlier: SQLite and MySQL evaluate an\n * UPDATE's own SET row by row (measured: a team's lead demoted early made\n * its other members' new rows unwritable). On MySQL, which refuses to read\n * the written table from its own subquery, the set is a derived table,\n * materialized before the write (`#capped`'s form). `undefined` where\n * nothing is left to judge.\n */\n producedWhere(\n model: AnyModel,\n candidates: (alias: string) => Sql | undefined,\n values: Input,\n judged: PreparedSelector | undefined,\n acyclic: readonly string[] = NO_RELATIONS,\n limit?: number\n ): Sql | undefined {\n if (judged === undefined && acyclic.length === 0) return undefined;\n const a = this.adapter;\n const row = this.alias();\n const produced = this.alias();\n const current = (field: string) => this.column(model, field, row);\n const rowKeys = this.schema.keys(model);\n // A value only the database computes (a list append, an exact\n // decimal's multiply or divide) has no value to judge: it is refused\n // where the judgement reads it (`updateValue`), and stands as it was\n // where nothing does, since no answer depends on it.\n const unread = (field: string) =>\n !(\n this.namesUpdate(model, field, values[field]) ||\n (judged?.predicate &&\n readsAny(judged.predicate, new Set([field]), rowKeys)) ||\n acyclic.some((relation) => {\n const edge = this.schema.membership(model, relation);\n return (\n edge.kind === \"reference\" &&\n edge.pairs.some((pair) => pair.source === field)\n );\n })\n );\n const from = this.#producedRows(\n model,\n [\n (field) =>\n values[field] === undefined || unread(field)\n ? current(field)\n : this.updateValue(model, field, values[field], current(field)),\n ],\n produced\n );\n const nulls = new Map<string, boolean>();\n for (const [field, value] of Object.entries(values)) {\n if (value === undefined) continue;\n const whole = wholeValue(value);\n if (whole && !(whole.value instanceof Sql))\n nulls.set(field, whole.value === null);\n }\n const judgedSet = (): Sql | undefined => {\n const guard = this.#holds(model, judged, produced, nulls, from, acyclic);\n if (guard === undefined) return undefined;\n const keys = this.keyOrder(model).map(current);\n return assembleAdapterSelect(a, {\n columns: sql.join(keys, \", \"),\n from: this.table(model, row),\n where: candidates(row),\n groupBy: sql.join(keys, \", \"),\n having: sql`${a.aggregates.min(guard)} = 1`,\n ...(limit !== undefined && {\n orderBy: this.#ascendingKeys(model, row),\n limit: this.value(limit),\n }),\n });\n };\n const set = this.#sharing(judgedSet);\n if (set === undefined) return undefined;\n const table = model[\"~\"].names.sql!;\n return a.operators.in(\n rowValue(\n this.keyOrder(model).map((field) => this.column(model, field, table))\n ),\n a.subqueries.scalar(\n a.capabilities.supportsMutationTargetInSubquery\n ? set\n : sql`SELECT * FROM ${a.subqueries.correlate(set, this.alias())}`\n )\n );\n }\n /**\n * A read's own candidates: `selector` (absent: every row) under `purpose`.\n * Reads consume only the predicate, so the conjunction carries no facts:\n * the key-preserving form, {@link candidates}, is the write lookups'.\n */\n #within(\n model: AnyModel,\n selector: Pick<PreparedSelector, \"model\" | \"predicate\"> | undefined,\n purpose: RowPurpose\n ): Pick<PreparedSelector, \"model\" | \"predicate\"> | undefined {\n const scope = this.#scope(model, purpose);\n if (scope?.predicate === undefined) return selector;\n if (selector?.predicate === undefined) return scope;\n return freeze({\n model,\n predicate: freeze({\n kind: \"and\",\n predicates: freeze([selector.predicate, scope.predicate]),\n }),\n });\n }\n /** `undefined` where it states nothing, or the call drops all it states. */\n lowerSelector(\n selector: Pick<PreparedSelector, \"model\" | \"predicate\">,\n alias?: string\n ): Sql | undefined {\n if (!selector.predicate) return undefined;\n const frames = this.#frames;\n this.#frames = [{ alias, escaped: false }];\n try {\n return this.#lowerStated(selector.predicate, alias);\n } finally {\n this.#frames = frames;\n }\n }\n /**\n * The aliases of the rows a predicate being lowered reads, from its root\n * to the relation body it is in, each marked once a `{ $row, up }` inside\n * it names a row above it: such a body is correlated past its parent, so\n * it is never shared.\n */\n #frames: { readonly alias: string | undefined; escaped: boolean }[] = [];\n /** The alias of the row `up` bodies above the current one. */\n #outerAlias(up: number | undefined, alias: string | undefined): string {\n const frames = this.#frames;\n const at = frames.length - 1 - (up ?? 0);\n const owner = up === undefined || up === 0 ? alias : frames[at]?.alias;\n if (owner === undefined)\n throw new UnsupportedOperationError(\n \"An enclosing row's column ({ $row, up }) has no row to read here.\"\n );\n for (let index = at + 1; index < frames.length; index++)\n frames[index]!.escaped = true;\n return owner;\n }\n /**\n * `predicate` lowered; `undefined` where it is made of layers the call\n * drops (R6), so a statement without them is the one without the domain.\n */\n #lowerStated(predicate: PreparedPredicate, alias?: string): Sql | undefined {\n if (predicate.kind === \"layer\") {\n let resolved = this.#resolve(predicate);\n if (resolved === undefined) return undefined;\n const known = this.#known;\n if (known !== undefined && alias === known.alias)\n resolved = foldKnownNulls(resolved, known.nulls);\n // A stack, made at the first layer this `Queries` lowers: what reads\n // it reads it while it lowers (the selectors' memo keys its content).\n const excluded = (this.#excluded ??= []);\n excluded.push(predicate.layer);\n try {\n return this.#lowerPredicate(resolved, alias);\n } finally {\n excluded.pop();\n }\n }\n if (predicate.kind !== \"and\") return this.#lowerPredicate(predicate, alias);\n // No closure here: this runs at every filter node of every statement.\n const { predicates } = predicate;\n if (predicates.length === 1) {\n const only = this.#lowerStated(predicates[0]!, alias);\n return only && this.adapter.operators.and(only);\n }\n const members: Sql[] = [];\n // biome-ignore lint/style/useForOf: no iterator at every filter node (E5.1, measured).\n for (let index = 0; index < predicates.length; index++) {\n const lowered = this.#lowerStated(predicates[index]!, alias);\n if (lowered !== undefined) members.push(lowered);\n }\n return members.length === 0 && predicates.length > 0\n ? undefined\n : this.adapter.operators.and(...members);\n }\n /** Whether the call drops every layer `predicate` is made of (R6). */\n #drops(predicate: PreparedPredicate | undefined): boolean {\n if (predicate?.kind === \"layer\")\n return this.#resolve(predicate) === undefined;\n return (\n predicate?.kind === \"and\" &&\n predicate.predicates.length > 0 &&\n predicate.predicates.every((member) => this.#drops(member))\n );\n }\n /** An aggregate read's root filter: its `where` under the root domain. */\n lowerWhere(\n model: AnyModel,\n where: Input | undefined,\n alias?: string\n ): Sql | undefined {\n const selector = this.#within(\n model,\n where === undefined\n ? undefined\n : this.prepareSelector(model, where, false, false),\n \"root\"\n );\n return selector && this.lowerSelector(selector, alias);\n }\n /**\n * The value a LOCATED row holds for one field, read where it is SPENT:\n * `(SELECT <column> FROM <target> WHERE <this arm's selector> LIMIT 1)`,\n * inside the statement that writes it.\n *\n * A parent-held `connect` folds its target's referenced value into the\n * parent's own SET. Its planning probe answers EXISTENCE and the branch; the\n * bytes that land in the column are the target's own, read at the write — so\n * no second, re-derived provenance stands between the row the selector named\n * and the key written, and a collation that makes the selector's literal\n * differ from the stored value cannot change the answer (E1 U1, and the\n * create root's `toOneFkAssign` before it).\n *\n * `mutating` is the model the enclosing statement writes: where the provider\n * refuses to read the table its own statement mutates (MySQL ERROR 1093) the\n * read hides behind a derived table, the same one condition\n * {@link hideMutationTarget} already owns — the SELF relation's shape.\n */\n locatedValue(\n model: AnyModel,\n field: string,\n selector: PreparedSelector,\n mutating?: AnyModel\n ): Sql {\n const alias = this.alias();\n const located = assembleAdapterSelect(this.adapter, {\n columns: this.column(model, field, alias),\n from: this.table(model, alias),\n where: this.lowerSelector(selector, alias),\n limit: this.value(1),\n });\n return this.adapter.subqueries.scalar(\n this.hideMutationTarget(located, model, mutating?.[\"~\"].names.sql)\n );\n }\n lowerMutationLimit(\n model: AnyModel,\n selector: PreparedSelector,\n limit: number | undefined\n ): { readonly where?: Sql; readonly suffix?: Sql } {\n const adapter = this.adapter;\n // The UPDATE/DELETE target carries no alias, so it is addressable only by\n // its NAME. Without that qualifier a correlated `EXISTS` emits the parent\n // column bare and it rebinds to the CHILD table wherever both carry the\n // name — `some` matches nothing, `none`/`every` match everything, and a\n // `deleteMany` removes the complement of the intended set. The shipped\n // engine passed the table name for exactly this reason\n // (`operations/update.ts:79-90`, `delete.ts:85-92`).\n const mutated = model[\"~\"].names.sql!;\n // MySQL answers an UPDATE/DELETE's subquery row by row while the statement\n // and the referential actions it fires change the rows that subquery\n // reads, which is also why it refuses to read the mutated table there\n // (ERROR 1093). A selector that reads other rows is therefore its keys,\n // read into a derived table before any write: the statement snapshot\n // PostgreSQL and SQLite answer from.\n const where =\n !adapter.capabilities.supportsMutationTargetInSubquery &&\n selector.predicate !== undefined &&\n readsRelation(selector.predicate)\n ? this.#capped(selector)\n : this.lowerSelector(selector, mutated);\n if (limit === undefined) return { where };\n // A limited write takes the first `limit` rows in key order, the order a\n // read's `take` completes with: every path picks the same rows. MySQL,\n // which refuses a `LIMIT` inside `IN`, states it on the statement itself.\n if (!adapter.capabilities.supportsMutationRowLimit)\n return {\n where: adapter.operators.and(\n ...[where, this.#capped(selector, limit)].filter(\n (condition): condition is Sql => condition !== undefined\n )\n ),\n };\n return {\n where,\n suffix: sql`${adapter.clauses.orderBy(this.#ascendingKeys(model))} ${adapter.clauses.limit(this.value(limit))}`,\n };\n }\n /**\n * The first `limit` rows of `selector` in key order, as prepared meaning: a\n * limited window two statements of one atomic unit both name — a premise\n * about the window, then the effect over it — and agree on by construction,\n * because a total order leaves the same data one answer. Its rows are rows\n * of `selector`, so the selector's facts hold for them.\n */\n window(selector: PreparedSelector, limit: number): PreparedSelector {\n return Object.freeze({\n model: selector.model,\n facts: selector.facts,\n predicate: Object.freeze({ kind: \"window\", selector, limit }),\n });\n }\n /**\n * Every row of `selector` locked, answered as ONE row: the inner read takes\n * the row locks (`FOR UPDATE`), and the count over it, which must consume\n * every row, is all that crosses the wire. Locking a million candidates\n * then costs one row back, not a million keys.\n */\n lockAll(selector: PreparedSelector): Query {\n const a = this.adapter;\n const inner = this.#rootAlias();\n const locked = assembleAdapterSelect(a, {\n columns: a.literals.true(),\n from: this.table(selector.model, inner),\n where: this.lowerSelector(selector, inner),\n forUpdate: true,\n });\n return {\n sql: assembleAdapterSelect(a, {\n columns: a.identifiers.aliased(a.aggregates.count(), \"_count\"),\n from: a.subqueries.correlate(locked, this.alias()),\n }),\n shape: { kind: \"object\", fields: { _count: COUNT_LEAF } },\n };\n }\n /**\n * The rows whose key is at most `last`'s in key order: over a selector whose\n * key-ordered read ended at `last`, that read's rows, at one bound value per\n * key however many they are (keys are NOT NULL: a row-value `<=`).\n */\n through(model: AnyModel, last: Input): PreparedSelector {\n const facts = newSelectorFacts(false);\n for (const field of this.keyOrder(model)) facts.fields.add(field);\n return Object.freeze({\n model,\n facts,\n predicate: Object.freeze({ kind: \"through\", model, last }),\n });\n }\n /**\n * `<keys> IN (SELECT * FROM (SELECT <keys> FROM <model> WHERE <selector>\n * ORDER BY <keys> LIMIT <limit>) AS <alias>)`, the keys outside addressed\n * through `alias`: the first `limit` rows in key order, a mutation's limit\n * where the provider has no `UPDATE … LIMIT`, and a {@link window}; without\n * a `limit`, every row, a MySQL mutation's keyed snapshot\n * ({@link lowerMutationLimit}). Where the provider cannot read a mutation's\n * own table in a subquery (MySQL), the read sits in a derived table, as\n * {@link hideMutationTarget}'s does: MySQL also refuses a `LIMIT` directly\n * inside `IN (…)`, and the derived table answers both, in the premise's\n * SELECT and in the effect.\n */\n #capped(selector: PreparedSelector, limit?: number, alias?: string): Sql {\n const adapter = this.adapter;\n const model = selector.model;\n const inner = this.alias();\n const keys = this.keyOrder(model);\n const capped = assembleAdapterSelect(adapter, {\n columns: sql.join(\n keys.map((field) => this.column(model, field, inner)),\n \", \"\n ),\n from: this.table(model, inner),\n where: this.lowerSelector(selector, inner),\n ...(limit === undefined\n ? {}\n : {\n orderBy: this.#ascendingKeys(model, inner),\n limit: this.value(limit),\n }),\n });\n return adapter.operators.in(\n rowValue(keys.map((field) => this.column(model, field, alias))),\n adapter.subqueries.scalar(\n adapter.capabilities.supportsMutationTargetInSubquery\n ? capped\n : sql`SELECT * FROM ${adapter.subqueries.correlate(capped, this.alias())}`\n )\n );\n }\n /** `<key> ASC, …` in {@link keyOrder}, the keys addressed through `alias`. */\n #ascendingKeys(model: AnyModel, alias?: string): Sql {\n return sql.join(\n this.keyOrder(model).map((field) =>\n this.adapter.orderBy.asc(this.column(model, field, alias))\n ),\n \", \"\n );\n }\n lowerIdentity(model: AnyModel, identity: Input, alias?: string): Sql {\n return this.adapter.operators.and(\n ...Object.entries(identity).map(([field, value]) =>\n this.adapter.operators.eq(\n this.column(model, field, alias),\n this.fieldValue(model, field, value)\n )\n )\n );\n }\n /**\n * A combinator, unless the model declares a field by that name: validation\n * extends its three combinator entries with the model's own fields, so a\n * scalar or relation literally named `AND` wins the key there\n * (`validation/model/core/where.ts`, `validation/model/args/aggregate.ts`\n * for `having`), and\n * the engine reads the admitted payload the same way (N4).\n */\n private combinator(\n model: AnyModel,\n key: string\n ): key is \"AND\" | \"OR\" | \"NOT\" {\n return (\n (key === \"AND\" || key === \"OR\" || key === \"NOT\") &&\n !model[\"~\"].state.scalars[key] &&\n !model[\"~\"].state.relations[key]\n );\n }\n /**\n * The one logical-combinator owner, shared by `where` and `having`. An arm\n * that builds no condition is absent: it contributes nothing to `AND`,\n * nothing to `NOT` and nothing to `OR`, and only `OR` turns \"no surviving\n * arm\" into a condition — the vacuous FALSE.\n */\n private combine(\n key: \"AND\" | \"OR\" | \"NOT\",\n arms: readonly PreparedPredicate[]\n ): PreparedPredicate {\n const stated = arms.filter(states);\n if (key === \"OR\")\n return stated.length === 0\n ? VACUOUS_FALSE\n : (sameColumnIn(stated) ??\n freeze({ kind: \"or\", predicates: freeze(stated) }));\n const predicates: readonly PreparedPredicate[] =\n key === \"AND\"\n ? stated\n : stated.map((predicate) =>\n freeze({ kind: \"not\" as const, predicate })\n );\n return freeze({\n kind: \"and\",\n predicates: freeze(predicates),\n });\n }\n #prepareWhere(\n model: AnyModel,\n where: Input,\n facts: SelectorFacts | undefined,\n path: readonly Membership[],\n unique = false,\n positive = true\n ): PreparedPredicate {\n if (where instanceof Condition) {\n if (facts) facts.exact = false;\n return freeze({ kind: \"condition\", condition: where });\n }\n if (where instanceof Existence) return this.#prepareExists(where, facts);\n return freeze({\n kind: \"and\",\n predicates: freeze(\n Object.entries(where).map(([field, operand]) => {\n if (this.combinator(model, field)) {\n if (facts && field !== \"AND\") facts.exact = false;\n return this.combine(\n field,\n entries(operand).map((clause) =>\n this.#prepareWhere(\n model,\n clause,\n facts,\n path,\n false,\n field === \"NOT\" ? !positive : positive\n )\n )\n );\n }\n if (model[\"~\"].state.relations[field])\n return this.#prepareSlotPredicate(\n model,\n field,\n operand,\n facts,\n path,\n positive\n );\n // An ordinary scalar predicate is not a unique discriminator. Only\n // unique selectors and possible compound names need the key catalog.\n const key =\n unique || model[\"~\"].state.scalars[field] === undefined\n ? findAddressableKey(model, field)\n : undefined;\n if (key?.name)\n return freeze({\n kind: \"and\",\n predicates: freeze(\n key.fields.map((member) =>\n this.#prepareScalarPredicate(\n model,\n member,\n record(operand)[member],\n facts,\n unique,\n positive\n )\n )\n ),\n });\n return this.#prepareScalarPredicate(\n model,\n field,\n operand,\n facts,\n unique && key !== undefined,\n positive\n );\n })\n ),\n });\n }\n /**\n * `$exists`: the target's rows, read by the statement wherever it sits, so\n * a write to them orders before it (a read of the target with no path).\n */\n #prepareExists(\n existence: Existence,\n facts: SelectorFacts | undefined\n ): PreparedPredicate {\n const model = this.schema.schema[existence.model]!;\n const nestedFacts = facts && newSelectorFacts(false);\n // One body below the row that holds it, joined to nothing: a\n // `{ $row, up }` inside it may read that row (or one above), and then it\n // is correlated; else it is the same wherever the statement holds it.\n const scopes = this.#scopes;\n this.#scopes = [...scopes, { model, facts: nestedFacts }];\n let predicate: PreparedPredicate;\n try {\n predicate = this.#prepareWhere(model, existence.where, nestedFacts, []);\n } finally {\n this.#scopes = scopes;\n }\n if (facts && nestedFacts) {\n facts.exact = false;\n const domain = this.domain?.selector(model, \"related\");\n if (domain)\n for (const field of domain.facts.fields) nestedFacts.fields.add(field);\n facts.reads.push({\n model,\n path: [],\n fields: nestedFacts.fields,\n equals: nestedFacts.equals,\n exact: false,\n });\n facts.reads.push(...nestedFacts.reads);\n }\n return freeze({\n kind: \"exists\",\n model,\n ...(states(predicate) && { predicate }),\n });\n }\n /** One prepared scalar: the field and its memoised physical view. */\n #scalar(model: AnyModel, field: string): PreparedScalar {\n return freeze({\n model,\n field,\n physical: physicalField(this.schema, model, field),\n });\n }\n #prepareScalarPredicate(\n model: AnyModel,\n field: string,\n value: unknown,\n facts: SelectorFacts | undefined,\n key = false,\n positive = true\n ): PreparedPredicate {\n const scalar = this.#scalar(model, field);\n if (facts) {\n facts.fields.add(field);\n const filter =\n value !== null &&\n typeof value === \"object\" &&\n !(value instanceof Sql) &&\n !(value instanceof Parameter) &&\n !isFieldRef(value)\n ? record(value)\n : undefined;\n const hasEquality =\n filter === undefined ||\n (Object.keys(filter).length === 1 && \"equals\" in filter);\n const equality = filter && hasEquality ? filter.equals : value;\n if (\n hasEquality &&\n (equality === null ||\n (typeof equality !== \"object\" && !(equality instanceof Sql)))\n ) {\n facts.equals.set(field, equality);\n if (key) facts.keys.set(field, equality);\n } else if (!(hasEquality && equality instanceof Parameter))\n facts.exact = false;\n // A call's value (K2) is an equality whose value preparation does not\n // know: it pins nothing, and leaves the selector a conjunction of\n // equalities, so its literal ones still prove a write disjoint (N1).\n }\n return this.#prepareOperations(\n key\n ? freeze({ kind: \"column\", scalar, key: true })\n : freeze({ kind: \"column\", scalar }),\n value,\n false,\n positive\n );\n }\n /**\n * One operator vocabulary over one target. A column, a JSON value inside it\n * and an aggregate over it are the same grammar, so `where` and `having`\n * cannot admit different operators or bind an operand two ways.\n */\n #prepareOperations(\n target: PreparedTarget,\n value: unknown,\n insensitive = false,\n positive = true\n ): PreparedPredicate {\n const state = target.scalar?.physical.scalar[\"~\"].state;\n const shorthand =\n value === null ||\n value instanceof Sql ||\n isFieldRef(value) ||\n typeof value !== \"object\" ||\n jsonNullKindOf(value) !== undefined ||\n (state?.array === true && Array.isArray(value)) ||\n !addressesOperators(state, record(value));\n if (shorthand)\n return this.prepareOperation(\n target,\n \"equals\",\n value,\n insensitive,\n positive\n );\n return this.#prepareOperatorFilter(target, value, insensitive, positive);\n }\n /** An operator object (`{ gt: 1, not: … }`), out of line from the shorthand. */\n #prepareOperatorFilter(\n target: PreparedTarget,\n value: unknown,\n insensitive: boolean,\n positive: boolean\n ): PreparedPredicate {\n const state = target.scalar?.physical.scalar[\"~\"].state;\n const filter = record(value);\n // D-22. A JSON filter's own `mode` wins in BOTH directions — a declared\n // `default` really does restore exact matching on that arm — while a\n // scalar filter's `mode` may only UPGRADE to insensitive. That asymmetry\n // is the shipped pair of rules (`json-filter-builder.ts:31-45` against\n // `where-builder.ts`), and it is a fact about the TARGET KIND, resolved\n // here in the one operand owner rather than by a second walker.\n const declared = filter.mode;\n const folded =\n state?.type === \"json\" && declared !== undefined\n ? declared === \"insensitive\"\n : insensitive || declared === \"insensitive\";\n const scoped: PreparedTarget =\n state?.type === \"json\" && Array.isArray(filter.path)\n ? freeze({\n ...(target as Extract<PreparedTarget, { kind: \"column\" }>),\n path: freeze([...(filter.path as string[])]),\n })\n : target;\n const predicates: PreparedPredicate[] = [];\n for (const name of Object.keys(filter)) {\n if (name === \"mode\" || name === \"path\") continue;\n const operand = filter[name];\n if (name === \"equals\") {\n predicates.push(\n this.#prepareOperations(scoped, operand, folded, positive)\n );\n } else if (name === \"not\") {\n predicates.push(\n freeze({\n kind: \"not\",\n predicate: this.#prepareOperations(\n scoped,\n operand,\n folded,\n !positive\n ),\n })\n );\n } else {\n predicates.push(\n this.prepareOperation(scoped, name, operand, folded, positive)\n );\n }\n }\n return freeze({\n kind: \"and\",\n predicates: freeze(predicates),\n });\n }\n /** One admitted operator, with its operand resolved once. */\n private prepareOperation(\n target: PreparedTarget,\n operator: string,\n value: unknown,\n insensitive: boolean,\n positive = true\n ): PreparedPredicate {\n const owner = target.scalar;\n switch (operator) {\n case \"in\":\n case \"notIn\":\n return freeze({\n kind: \"operation\",\n operator,\n target,\n operands: freeze(\n value instanceof Parameter\n ? [\n {\n kind: \"parameter\" as const,\n parameter: value,\n spread: true as const,\n },\n ]\n : (value as unknown[]).map((member) =>\n owner\n ? this.#prepareOperand(owner, member)\n : { kind: \"value\" as const, value: member }\n )\n ),\n insensitive,\n });\n case \"equals\":\n case \"lt\":\n case \"lte\":\n case \"gt\":\n case \"gte\":\n case \"contains\":\n case \"startsWith\":\n case \"endsWith\":\n return freeze({\n kind: \"operation\",\n operator,\n target,\n operand: owner\n ? this.#prepareOperand(owner, value)\n : ({ kind: \"value\", value } satisfies PreparedOperand),\n value,\n insensitive,\n });\n default:\n return freeze({\n kind: \"operation\",\n operator,\n target,\n value,\n insensitive,\n ...(operator === \"distance\" &&\n positive &&\n owner?.physical.scalar[\"~\"].state.type === \"point\" &&\n distanceUpperBound(value) !== undefined\n ? { probe: true as const }\n : {}),\n });\n }\n }\n /**\n * One admitted filter member, resolved to the value it binds or the column it\n * names.\n *\n * The operand is NOT frozen and the structure that holds it is: the prepared\n * predicate ({@link prepareOperation}) and, for `in`/`notIn`, its operand\n * list. One owner builds an operand and one owner reads it\n * ({@link lowerOperation}), both in this file, so freezing each box restated\n * the same immutability the enclosing predicate already carries — and\n * restated it PER MEMBER: `Object.freeze` transitions a fresh object's map on\n * every call, measured at 1.98–2.20 µs for the 100 members of one\n * `id: { in: ids₁₀₀ }` against 0.25–0.28 µs for the same 100 boxes\n * (`g4/perf2/receipts/micro-in-list.json`).\n */\n #prepareOperand(owner: PreparedScalar, value: unknown): PreparedOperand {\n if (value instanceof Parameter)\n return { kind: \"parameter\", parameter: value };\n if (value instanceof OuterColumn)\n return this.#prepareOuterOperand(owner, value);\n if (isFieldRef(value)) {\n if (owner.physical.scalar[\"~\"].state.type === \"json\")\n throw new UnsupportedOperationError(\n `Field reference '${formatFieldRef(value)}' is not supported in a JSON filter operand.`\n );\n return this.#prepareFieldOperand(owner, value);\n }\n if (!(value instanceof Sql)) return { kind: \"value\", value };\n const operands = value.values.map((member) => {\n if (isFieldRef(member)) return this.#prepareFieldOperand(owner, member);\n // A token is executable only in a flat interpolation slot. An object\n // parameter stays data; never turn a hidden token into provider data.\n const pending = [member];\n const seen = new WeakSet<object>();\n for (const nested of pending) {\n if (isFieldRef(nested))\n throw new UnsupportedOperationError(\n \"An SQL filter field reference must be a direct interpolation, not nested inside a parameter object.\"\n );\n if (nested instanceof OuterColumn)\n throw new UnsupportedOperationError(\n \"An enclosing row's column ({ $row, up }) is compared directly, never inside an SQL filter.\"\n );\n if (nested === null || typeof nested !== \"object\" || seen.has(nested))\n continue;\n seen.add(nested);\n for (const descriptor of Object.values(\n Object.getOwnPropertyDescriptors(nested)\n ))\n if (\"value\" in descriptor) pending.push(descriptor.value);\n }\n return { kind: \"value\", value: member } as const;\n });\n return operands.some((member) => member.kind === \"field\")\n ? { kind: \"sql\", strings: [...value.strings], operands: freeze(operands) }\n : { kind: \"value\", value };\n }\n /** A field-reference operand, out of line: most operands are values. */\n #prepareFieldOperand(\n owner: PreparedScalar,\n value: Parameters<typeof fieldRefPayload>[0]\n ): Extract<PreparedOperand, { kind: \"field\" }> {\n const { model } = owner;\n const payload = fieldRefPayload(value);\n const scope = model[\"~\"].names.ts ?? \"unknown\";\n if (payload.model !== scope)\n throw new UnsupportedOperationError(\n `Field reference '${formatFieldRef(value)}' cannot be used while filtering '${scope}': a field reference may only compare columns of the same model.`\n );\n if (payload.list)\n throw new UnsupportedOperationError(\n `Field reference '${formatFieldRef(value)}' is a list field and cannot be used as a scalar SQL operand.`\n );\n const referenced = model[\"~\"].state.scalars[payload.field];\n if (!referenced)\n throw new UnsupportedOperationError(\n `Field reference '${formatFieldRef(value)}' does not name a scalar field of '${scope}'.`\n );\n const own = exactDecimalDomain(owner.physical.scalar[\"~\"].state);\n const other = exactDecimalDomain(referenced[\"~\"].state);\n if (own && other && !sameDecimalDomain(own, other))\n throw new UnsupportedOperationError(\n `Field reference '${payload.field}' cannot be compared with '${owner.field}' on '${scope}': '${owner.field}' is decimal(${own.precision},${own.scale}) and '${payload.field}' is decimal(${other.precision},${other.scale}). Two decimals compare exactly only when they declare the same precision and scale.`\n );\n const storage = incomparableIdentifiers(\n this.scalarShape(model, owner.field).id,\n this.scalarShape(model, payload.field).id,\n owner.field,\n payload.field\n );\n if (storage !== undefined)\n throw new UnsupportedOperationError(\n `Field reference '${payload.field}' cannot be compared with '${owner.field}' on '${scope}': ${storage}`\n );\n return {\n kind: \"field\",\n scalar: this.#scalar(model, payload.field),\n };\n }\n /**\n * `{ $row, up }`: the column of the row `up` relation bodies above, which\n * that row's scope reads, compared like a field reference. Refused when it\n * leaves the predicate (or an `$exists` body), crosses a recursive or\n * polymorphic relation, or names what a comparison cannot read.\n */\n #prepareOuterOperand(\n owner: PreparedScalar,\n value: OuterColumn\n ): Extract<PreparedOperand, { kind: \"field\" }> {\n const spelled = `{ $row: ${JSON.stringify(value.$row)}, up: ${value.up} }`;\n const scopes = this.#scopes;\n const at = scopes.length - 1 - value.up;\n if (at < 0)\n throw new UnsupportedOperationError(\n `${spelled} reaches past the predicate it is written in: it is ${Math.max(scopes.length - 1, 0)} relation bodies deep.`\n );\n for (let index = at + 1; index < scopes.length; index++)\n if (scopes[index]!.sealed !== undefined)\n throw new UnsupportedOperationError(\n `${spelled} crosses a ${scopes[index]!.sealed} relation: an enclosing row is read only through plain relations.`\n );\n const { model, facts } = scopes[at]!;\n const name = model[\"~\"].names.ts ?? \"unknown\";\n const referenced = model[\"~\"].state.scalars[value.$row];\n const own = owner.physical.scalar[\"~\"].state;\n if (!referenced)\n throw new UnsupportedOperationError(\n `${spelled} does not name a scalar field of '${name}'.`\n );\n const other = referenced[\"~\"].state;\n const kinds = new Set([own.type, other.type]);\n if (\n own.array === true ||\n other.array === true ||\n own.type === \"json\" ||\n !(\n own.type === other.type ||\n (kinds.size === 2 && kinds.has(\"string\") && kinds.has(\"enum\"))\n )\n )\n throw new UnsupportedOperationError(\n `${spelled} names '${name}.${value.$row}' (${other.array === true ? `${other.type}[]` : other.type}), which cannot be compared with '${owner.field}' (${own.array === true ? `${own.type}[]` : own.type}).`\n );\n const ownDomain = exactDecimalDomain(own);\n const otherDomain = exactDecimalDomain(other);\n if (ownDomain && otherDomain && !sameDecimalDomain(ownDomain, otherDomain))\n throw new UnsupportedOperationError(\n `${spelled} names a decimal(${otherDomain.precision},${otherDomain.scale}) and '${owner.field}' is decimal(${ownDomain.precision},${ownDomain.scale}): two decimals compare exactly only when they declare the same precision and scale.`\n );\n const storage = incomparableIdentifiers(\n this.scalarShape(owner.model, owner.field).id,\n this.scalarShape(model, value.$row).id,\n owner.field,\n value.$row\n );\n if (storage !== undefined)\n throw new UnsupportedOperationError(`${spelled}: ${storage}`);\n // The row that holds the column reads it: a write to it reorders.\n facts?.fields.add(value.$row);\n return {\n kind: \"field\",\n scalar: this.#scalar(model, value.$row),\n ...(value.up > 0 && { up: value.up }),\n };\n }\n /** One relation slot: ordinary quantifiers, to-one shorthand, or tagged arms. */\n #prepareSlotPredicate(\n model: AnyModel,\n name: string,\n operand: unknown,\n facts: SelectorFacts | undefined,\n path: readonly Membership[],\n positive = true\n ): PreparedPredicate {\n const resolved = this.schema.index.get(model)!.get(name)!;\n const entries = record(operand);\n if (\n resolved.member ||\n (resolved.edge.kind !== \"variantRowCarrier\" &&\n resolved.edge.kind !== \"variantJunctionCarrier\")\n ) {\n const edge = bindMembership(this.schema, model, name);\n // A spelled `recurse` IS the closure form (the validation dispatcher's\n // one rule), admitted densely: its unspelled arms are `undefined` holes.\n // The assertion names the admitted shape, as `Arguments.recurse` does.\n const closure: Closure | undefined =\n entries.recurse === undefined\n ? undefined\n : freeze({\n depth: (entries.recurse as NormalizedRecurrence).depth,\n self: entries.self === true,\n });\n const arms: [string, unknown][] = closure\n ? Object.entries(entries).filter(\n ([key, value]) => QUANTIFIERS.has(key) && value !== undefined\n )\n : Object.keys(entries).every((key) => QUANTIFIERS.has(key))\n ? Object.entries(entries)\n : [[\"is\", entries]];\n return freeze({\n kind: \"and\",\n predicates: freeze(\n arms.map(([quantifier, value]) =>\n this.#relationPredicate(\n edge,\n quantifier,\n value,\n facts,\n path,\n positive,\n closure\n )\n )\n ),\n });\n }\n const members = resolved.edge.members;\n const many = resolved.edge.kind === \"variantJunctionCarrier\";\n const variantEdge = (variant: unknown) =>\n bindMembership(this.schema, model, name, variant as string);\n if (\n resolved.edge.kind === \"variantRowCarrier\" &&\n entries.type === undefined\n ) {\n const absent = \"is\" in entries;\n // Presence names the stored pair, independently of target-row existence.\n const fields = [\n resolved.edge.storage.typeColumn.name,\n resolved.edge.storage.idColumn.name,\n ];\n return Object.freeze({\n kind: \"and\",\n predicates: Object.freeze(\n fields.map((field) =>\n this.#prepareScalarPredicate(\n model,\n field,\n absent ? null : { not: null },\n facts\n )\n )\n ),\n });\n }\n const arms: [string | undefined, Input][] = many\n ? Object.entries(entries).map(([quantifier, tagged]) => [\n quantifier,\n record(tagged),\n ])\n : [[undefined, entries]];\n return freeze({\n kind: \"and\",\n predicates: freeze(\n arms.map(([quantifier, tagged]) => {\n const edge = variantEdge(tagged.type);\n const negated = tagged.isNot !== undefined;\n const inexact =\n negated || quantifier === \"none\" || quantifier === \"every\";\n const inner = this.#relationScope(\n edge,\n negated ? record(tagged.isNot) : (tagged.is as Input | undefined),\n facts,\n path,\n inexact,\n positive,\n undefined,\n \"polymorphic\"\n );\n if (quantifier !== undefined) {\n const quantified = freeze({\n kind: \"relation\" as const,\n edge,\n quantifier,\n predicate:\n negated && inner\n ? freeze({ kind: \"not\" as const, predicate: inner })\n : inner,\n });\n // `some` and `none` address the tagged arm and nothing else.\n // `every` is a statement about the WHOLE collection — \"every member\n // is an arm-`T` member satisfying P\" — so a member of any OTHER arm\n // falsifies it. That is the one tagged quantifier that must also\n // state the arms it did not name; the shipped engine answers a\n // board holding two posts and one tag `false` for\n // `every: { type: \"post\", … }`, and this is why.\n if (quantifier !== \"every\") return quantified;\n return freeze({\n kind: \"and\",\n predicates: Object.freeze([\n ...(inner ? [quantified] : []),\n ...members\n .filter((member) => member.variant !== tagged.type)\n .map((member) =>\n this.#relationPredicate(\n variantEdge(member.variant),\n \"none\",\n undefined,\n facts,\n path,\n positive\n )\n ),\n ]),\n });\n }\n // A tagged to-one arm: `{ type }` asks only that the slot holds that\n // variant; `is`/`isNot` keep the ordinary to-one quantifier meaning.\n return freeze({\n kind: \"relation\",\n edge,\n quantifier: \"some\",\n predicate:\n negated && inner\n ? Object.freeze({ kind: \"not\", predicate: inner })\n : inner,\n });\n })\n ),\n });\n }\n #relationPredicate(\n edge: Membership,\n quantifier: string,\n value: unknown,\n facts: SelectorFacts | undefined,\n path: readonly Membership[],\n positive = true,\n closure?: Closure\n ): PreparedPredicate {\n return freeze({\n kind: \"relation\",\n edge,\n quantifier,\n predicate: this.#relationScope(\n edge,\n value === null || value === undefined ? undefined : record(value),\n facts,\n path,\n quantifier === \"none\" ||\n quantifier === \"every\" ||\n quantifier === \"isNot\",\n positive,\n closure\n ),\n ...(closure ? { closure } : {}),\n });\n }\n /** One relation read: SQL meaning and dependency facts from one traversal. */\n /**\n * `inexact` is also this arm's POLARITY: `none`, `isNot` and `every` consume\n * their nested predicate under a negation — `every` emits `NOT(nested)`\n * inside its `NOT EXISTS` — so a conjunct added there is a conjunct of what\n * is negated. One fact, read twice, instead of a second flag that could\n * disagree with it.\n */\n #relationScope(\n edge: Membership,\n where: Input | undefined,\n facts: SelectorFacts | undefined,\n path: readonly Membership[],\n inexact: boolean,\n positive = true,\n closure?: Closure,\n sealed: string | undefined = closure && \"recursive\"\n ): PreparedPredicate | undefined {\n if (!where) return this.#relationFacts(edge, facts, path, inexact, closure);\n const scopes = this.#scopes;\n const nestedFacts =\n facts && newSelectorFacts(!inexact && closure === undefined);\n this.#scopes = [\n ...scopes,\n { model: edge.target, facts: nestedFacts, ...(sealed && { sealed }) },\n ];\n try {\n const predicate = this.#prepareWhere(\n edge.target,\n where,\n nestedFacts,\n facts ? [...path, edge] : path,\n false,\n positive && !inexact\n );\n this.#relationFacts(edge, facts, path, inexact, closure, nestedFacts);\n return predicate;\n } finally {\n this.#scopes = scopes;\n }\n }\n /** The reads a relation's scope adds to its parent's facts (§2.2). */\n #relationFacts(\n edge: Membership,\n facts: SelectorFacts | undefined,\n path: readonly Membership[],\n inexact: boolean,\n closure: Closure | undefined,\n prepared?: SelectorFacts\n ): undefined {\n if (!facts) return;\n const scope = [...path, edge];\n // A closure's members are decided by every intermediate row's link, so no\n // `equals` it states proves a write to another row disjoint, and a write\n // to a link field changes who is a member.\n const nestedFacts =\n prepared ?? newSelectorFacts(!inexact && closure === undefined);\n if (closure && edge.kind === \"reference\")\n for (const pair of edge.pairs)\n nestedFacts.fields.add(pair.source).add(pair.target);\n // The related domain's fields are read by this scope too, so a lookup\n // that reads through it depends on a write to them (§2.2).\n const domain = this.domain?.selector(edge.target, \"related\");\n if (domain)\n for (const field of domain.facts.fields) nestedFacts.fields.add(field);\n facts.reads.push({\n model: edge.target,\n path: scope,\n fields: nestedFacts.fields,\n equals: nestedFacts.equals,\n exact: nestedFacts.exact,\n });\n facts.reads.push(...nestedFacts.reads);\n }\n #lowerPredicate(predicate: PreparedPredicate, alias?: string): Sql {\n const a = this.adapter;\n // biome-ignore lint/style/useDefaultSwitchClause: the prepared predicate union is exhaustive; a default would be dead code.\n switch (predicate.kind) {\n case \"and\":\n case \"layer\":\n return this.#lowerStated(predicate, alias) ?? a.literals.true();\n case \"or\":\n // A balanced tree, not a chain: SQLite parses `a OR b OR …` one\n // expression level deep per arm and refuses depth 1000 (platform-15).\n return balancedOr(\n predicate.predicates.map((member) =>\n this.#lowerPredicate(member, alias)\n ),\n (arms) => a.operators.or(...arms)\n );\n case \"not\":\n return a.operators.not(\n this.#lowerPredicate(predicate.predicate, alias)\n );\n case \"always\":\n return predicate.value ? a.literals.true() : a.literals.false();\n case \"condition\":\n return predicate.condition.holds(this.#values, this.#instant)\n ? a.literals.true()\n : a.literals.false();\n case \"operation\":\n return this.lowerOperation(this.#bound(predicate), alias);\n case \"relation\":\n return this.#lowerRelationPredicate(predicate, alias);\n case \"exists\":\n return this.#lowerExists(predicate);\n case \"window\":\n return this.#capped(predicate.selector, predicate.limit, alias);\n case \"through\": {\n const { model, last } = predicate;\n const keys = this.keyOrder(model);\n return a.operators.lte(\n rowValue(keys.map((field) => this.column(model, field, alias))),\n rowValue(\n keys.map((field) => this.fieldValue(model, field, last[field]))\n )\n );\n }\n }\n }\n /**\n * The operation with its parameters' values read for this call, so the\n * value-dependent lowering reads them as any value. R6 has made each\n * present (a spread one a list).\n */\n #bound(predicate: OperationPredicate): BoundOperation {\n if (\n predicate.operand?.kind !== \"parameter\" &&\n !(predicate.value instanceof Parameter) &&\n !predicate.operands?.some(isParameterOperand)\n )\n return predicate as BoundOperation;\n return this.#boundParameters(predicate);\n }\n /** {@link bound}'s operation, which reads at least one parameter. */\n #boundParameters(predicate: OperationPredicate): BoundOperation {\n const { operand, operands, value, ...rest } = predicate;\n const read = (parameter: Parameter) =>\n parameter.read(this.#values, this.#instant);\n const bound = (member: PreparedOperand): BoundOperand[] => {\n if (member.kind !== \"parameter\") return [member];\n const given = read(member.parameter);\n return member.spread\n ? (given as unknown[]).map((item) => ({ kind: \"value\", value: item }))\n : [{ kind: \"value\", value: given }];\n };\n return {\n ...rest,\n ...(operand && { operand: bound(operand)[0]! }),\n ...(operands && { operands: operands.flatMap(bound) }),\n value: value instanceof Parameter ? read(value) : value,\n };\n }\n #preparedColumn(scalar: PreparedScalar, alias?: string): Sql {\n return this.#guarded(\n scalar.model,\n scalar.field,\n alias\n ? this.adapter.identifiers.column(alias, scalar.physical.name)\n : this.adapter.identifiers.escape(scalar.physical.name),\n alias\n );\n }\n /**\n * `column`, `model`'s `field` at `alias`, as an operand the caller wrote\n * (K5): a read-gated field reads NULL on a row that does not carry it, in\n * every position a caller writes it. A layer's predicates read the column\n * itself: they lower inside the layer.\n */\n #guarded(model: AnyModel, field: string, column: Sql, alias?: string): Sql {\n if (this.#lowersLayer || this.#masked) return column;\n const gate = this.domain?.projected(model)?.gates.get(field);\n // Every row a caller's operand is read on is one the domain takes, so\n // `read` holds there: the gate's own predicate decides.\n const holds = gate && this.#gateHolds(model, gate, alias, true);\n return holds === undefined\n ? column\n : this.adapter.expressions.caseWhen(\n [{ when: holds, then: column }],\n this.adapter.literals.null()\n );\n }\n /** `model`'s `field` at `alias` as an operand the caller wrote ({@link guarded}). */\n #operand(model: AnyModel, field: string, alias?: string): Sql {\n return this.#guarded(model, field, this.column(model, field, alias), alias);\n }\n /** Whether a caller's operand over `model`'s `field` may read NULL (K5). */\n #gatedHere(model: AnyModel, field: string): boolean {\n return (\n !this.#lowersLayer &&\n this.domain?.projected(model)?.gates.has(field) === true\n );\n }\n /**\n * Whether `model`'s rows lower through a masked window: a read-gated field\n * the call reads under aggregation, where a gate repeated per expression\n * would bind its values again in every copy.\n */\n #masks(model: AnyModel): boolean {\n return (\n !(this.#lowersLayer || this.#masked) &&\n (this.domain?.projected(model)?.gates.size ?? 0) > 0\n );\n }\n /** `fn` lowered over a masked window ({@link masked}). */\n #overMasked<T>(fn: () => T): T {\n this.#masked = true;\n try {\n return fn();\n } finally {\n this.#masked = false;\n }\n }\n #lowerTarget(target: PreparedTarget, alias?: string): Sql {\n return target.kind === \"column\"\n ? this.#preparedColumn(target.scalar, alias)\n : this.#aggregateExpression(target.aggregate, target.scalar, alias);\n }\n private lowerOperation(predicate: BoundOperation, alias?: string): Sql {\n const a = this.adapter;\n const { operator, target, operand } = predicate;\n const scalar = target.scalar;\n // A `_count` compares with `COUNT(col)`, a row count on every storage, and\n // admission types its operand as a number (`numericFilterOps`). It has no\n // column domain: no JSON document class, no text collation, no identifier\n // or decimal binding — every domain dispatch below reads `state`, so the\n // fact is stated once, here.\n const counted =\n target.kind === \"aggregate\" && target.aggregate === \"_count\";\n const state = counted ? undefined : scalar?.physical.scalar[\"~\"].state;\n const column = this.#lowerTarget(target, alias);\n if (state?.type === \"json\" && state.array !== true)\n return this.#lowerJsonOperation(predicate, column);\n const insensitive = predicate.insensitive === true;\n // A discriminator member is compared by the constraint that answers it; the\n // engine's case-sensitivity contract governs every other comparison. An\n // `insensitive` mode is a filter spelling and never reaches a discriminator,\n // so it keeps the folded pair rather than silently folding one side.\n // A COLUMN target's identifier storage: its value operands bind the\n // physical form, and a compact column is compared as the bytes (or the\n // `uuid`) it holds — never collated or ASCII-folded as text.\n const id =\n target.kind === \"column\" && scalar\n ? this.scalarShape(scalar.model, scalar.field).id\n : undefined;\n const text =\n !(target.kind === \"column\" && target.key === true && !insensitive) &&\n state !== undefined &&\n state.array !== true &&\n (state.type === \"string\" || state.type === \"enum\") &&\n !isCompact(id);\n const pattern =\n operator === \"contains\" ||\n operator === \"startsWith\" ||\n operator === \"endsWith\";\n const exact = (expression: Sql, field = scalar) =>\n text\n ? a.expressions.caseSensitiveText(\n expression,\n field?.physical.scalar[\"~\"].nativeType,\n pattern || insensitive\n )\n : expression;\n const folded =\n text && insensitive\n ? a.expressions.caseSensitiveText(\n a.expressions.asciiCaseFold(exact(column))\n )\n : column;\n /**\n * An enum compared against ANOTHER COLUMN compares its SPELLING — on BOTH\n * sides, on every dialect. PostgreSQL gives each enum field its own type,\n * so `status = review_status` has no operator there (42883) while MySQL and\n * SQLite, which store the value as text, answer it; casting the operand\n * alone left the filtered column typed as its own enum and produced\n * `post_status = text`. A LITERAL operand still binds an enum-typed\n * parameter against the bare column, so ordinary enum equality keeps its\n * index. Ordered comparison has no portable answer and is refused at\n * admission (`validation/scalars/enum.ts`), so equality — and the `not`\n * that negates it — is the whole reach of this fact.\n */\n const spelledAsText = (member: BoundOperand): boolean =>\n member.kind === \"field\" &&\n (state?.type === \"enum\" ||\n member.scalar.physical.scalar[\"~\"].state.type === \"enum\");\n const comparableColumn = (member: BoundOperand): Sql =>\n exact(\n spelledAsText(member) ? a.expressions.cast(column, \"text\") : column\n );\n const bind = (member: BoundOperand, fold = false): Sql => {\n if (member.kind === \"field\") {\n const reference = this.#preparedColumn(\n member.scalar,\n member.up === undefined ? alias : this.#outerAlias(member.up, alias)\n );\n const comparable = spelledAsText(member)\n ? a.expressions.cast(reference, \"text\")\n : reference;\n return fold\n ? a.expressions.caseSensitiveText(\n a.expressions.asciiCaseFold(exact(comparable, member.scalar))\n )\n : exact(comparable, member.scalar);\n }\n if (member.kind === \"sql\") {\n const expression = this.value(\n new Sql(\n member.strings,\n member.operands.map((slot) =>\n slot.kind === \"field\"\n ? this.#preparedColumn(slot.scalar, alias)\n : slot.value\n )\n )\n );\n return fold ? a.expressions.asciiCaseFold(expression) : expression;\n }\n const literal =\n scalar && !counted\n ? this.#targetValue(target, scalar, member.value, id)\n : this.value(member.value);\n return fold ? a.expressions.asciiCaseFold(literal) : literal;\n };\n switch (operator) {\n case \"equals\": {\n const single = operand!;\n const literal = single.kind === \"value\" ? single.value : undefined;\n if (single.kind === \"value\" && literal === null)\n return a.operators.isNull(column);\n if (state?.type === \"point\" && state.array !== true)\n return this.#geoPoint(\"equals\").equals(column, literal as GeoPoint);\n if (state?.array === true && Array.isArray(literal))\n return a.operators.eq(column, bind(single));\n if (\n insensitive &&\n (single.kind !== \"value\" ||\n typeof literal === \"string\" ||\n literal instanceof Sql)\n )\n return a.operators.eq(folded, bind(single, true));\n if (text && single.kind === \"value\" && !(literal instanceof Sql))\n return a.operators.exactTextEq(\n column,\n bind(single),\n scalar?.physical.scalar[\"~\"].nativeType\n );\n return a.operators.eq(comparableColumn(single), bind(single));\n }\n case \"lt\":\n case \"lte\":\n case \"gt\":\n case \"gte\":\n return a.operators[operator](\n text && insensitive ? folded : exact(column),\n bind(operand!, text && insensitive)\n );\n default:\n return this.#lowerOtherOperation(predicate, {\n column:\n pattern &&\n !(\n operator === \"startsWith\" &&\n operand?.kind === \"value\" &&\n typeof operand.value === \"string\"\n )\n ? exact(column)\n : column,\n folded,\n insensitive,\n text,\n exact,\n bind,\n state,\n });\n }\n }\n /**\n * The less common filter operators, kept out of {@link lowerOperation} so a\n * first query that compares by equality never compiles them.\n */\n #lowerOtherOperation(\n predicate: BoundOperation,\n {\n column,\n folded,\n insensitive,\n text,\n exact,\n bind,\n state,\n }: {\n column: Sql;\n folded: Sql;\n insensitive: boolean;\n text: boolean;\n exact: (expression: Sql) => Sql;\n bind: (member: BoundOperand, fold?: boolean) => Sql;\n state: ScalarStateOf | undefined;\n }\n ): Sql {\n const a = this.adapter;\n const { operator, operand } = predicate;\n const scalar = predicate.target.scalar;\n const members = () => predicate.operands ?? [];\n switch (operator) {\n case \"in\":\n case \"notIn\": {\n const negated = operator === \"notIn\";\n const operands = members();\n if (operands.length === 0)\n return negated ? a.literals.true() : a.literals.false();\n if (insensitive) {\n const comparisons = operands.map((member) =>\n negated\n ? a.operators.neq(folded, bind(member, true))\n : a.operators.eq(folded, bind(member, true))\n );\n // One comparison per member: balanced, as an `OR` is (platform-15).\n return balancedOr(comparisons, (arms) =>\n negated ? a.operators.and(...arms) : a.operators.or(...arms)\n );\n }\n const list = a.literals.list(operands.map((member) => bind(member)));\n if (negated) return a.operators.notIn(exact(column), list);\n return text\n ? a.operators.exactTextIn(\n column,\n list,\n scalar?.physical.scalar[\"~\"].nativeType\n )\n : a.operators.in(column, list);\n }\n case \"contains\":\n return insensitive\n ? a.operators.containsText(folded, bind(operand!, true))\n : a.operators.containsText(column, bind(operand!));\n case \"startsWith\":\n if (insensitive)\n return a.operators.startsWithText(folded, bind(operand!, true));\n return operand!.kind === \"value\" && typeof operand!.value === \"string\"\n ? a.operators.startsWithPrefix(\n column,\n operand!.value,\n scalar?.physical.scalar[\"~\"].nativeType\n )\n : a.operators.startsWithText(column, bind(operand!));\n case \"endsWith\":\n return insensitive\n ? a.operators.endsWithText(folded, bind(operand!, true))\n : a.operators.endsWithText(column, bind(operand!));\n case \"has\":\n return predicate.value === null\n ? a.literals.false()\n : a.arrays.has(\n column,\n this.#scalarValue(\n scalar!.physical.scalar,\n predicate.value,\n scalar!.field\n )\n );\n case \"hasEvery\": {\n const values = predicate.value as unknown[];\n return values.length === 0\n ? a.operators.isNotNull(column)\n : a.arrays.hasEvery(\n column,\n this.#scalarValue(scalar!.physical.scalar, values, scalar!.field)\n );\n }\n case \"hasSome\": {\n const values = predicate.value as unknown[];\n return values.length === 0\n ? a.literals.false()\n : a.arrays.hasSome(\n column,\n this.#scalarValue(scalar!.physical.scalar, values, scalar!.field)\n );\n }\n case \"isEmpty\":\n return predicate.value\n ? a.arrays.isEmpty(column)\n : a.operators.not(a.arrays.isEmpty(column));\n case \"within\": {\n const area = predicate.value as GeoArea;\n const geoPoint = this.#geoPoint(\"within\");\n if (\"bounds\" in area) return geoPoint.withinBounds(column, area.bounds);\n if (geoPoint.withinPolygon)\n return geoPoint.withinPolygon(column, area.polygon);\n throw new FeatureNotSupportedError(\n \"point\",\n \"within polygon\",\n \"GeoPoint polygon filtering is not supported by this provider.\"\n );\n }\n default: {\n // `distance`, the one operator left. Admission enumerates this\n // operator set once, per scalar type (`validation/scalars/**`), and\n // `prepareOperation` carries the key it admitted; there is no second\n // operator list here to disagree with it (AGENTS.md: \"Do not add a\n // second operator switch\").\n const specification = record(predicate.value);\n const expression = this.#distanceExpression(\n column,\n state!,\n scalar!.field,\n specification,\n \"filter\"\n );\n // The index probe. `distance <= X` implies `withinBounds(box(X))`, so\n // the box is a redundant conjunct the provider can answer from the\n // spatial index before it evaluates one great-circle distance. It is\n // added only where preparation saw POSITIVE polarity\n // ({@link PreparedPredicate.probe}); the adapter spells both arms.\n const upper = predicate.probe\n ? distanceUpperBound(specification)\n : undefined;\n const probe =\n upper === undefined\n ? []\n : [\n this.#geoPoint(\"distance filter\").withinBounds(\n column,\n geoBoundsForDistance(specification.to as GeoPoint, upper)\n ),\n ];\n return a.operators.and(\n ...probe,\n ...([\"lt\", \"lte\", \"gt\", \"gte\"] as const)\n .filter((bound) => specification[bound] !== undefined)\n .map((bound) =>\n a.operators[bound](expression, this.value(specification[bound]))\n )\n );\n }\n }\n }\n /**\n * One operand, bound in the domain of the expression it is COMPARED WITH.\n * A `_count` never reaches here: `lowerOperation` binds its row-count\n * operand as a plain value.\n *\n * Everything compares inside the field's own domain except a `_sum` over an\n * exact decimal: the compared expression is the column's sum, whose value is\n * wider than one column can hold, so the operand's cast widens the PRECISION\n * while keeping the field's SCALE — every summed row carries that scale, and an\n * operand at another one would be a different number on SQLite. The adapter\n * states how wide its exact HAVING cast can be; the refusal below is the\n * shipped sentence, verbatim.\n */\n #targetValue(\n target: PreparedTarget,\n scalar: PreparedScalar,\n value: unknown,\n id: IdentifierColumn | undefined\n ): Sql {\n if (\n target.kind === \"aggregate\" &&\n (target.aggregate === \"_min\" || target.aggregate === \"_max\")\n ) {\n const aggregateId = this.scalarShape(scalar.model, scalar.field).id;\n if (isCompact(aggregateId))\n return aggregatedIdentifier(\n this.adapter,\n aggregateId,\n this.#scalarValue(\n scalar.physical.scalar,\n value,\n scalar.field,\n aggregateId\n )\n );\n }\n if (target.kind === \"aggregate\" && target.aggregate === \"_sum\")\n return this.#sumTargetValue(scalar, value, id);\n return this.#scalarValue(scalar.physical.scalar, value, scalar.field, id);\n }\n /** A `_sum` operand, out of line: only a decimal HAVING widens its cast. */\n #sumTargetValue(\n scalar: PreparedScalar,\n value: unknown,\n id: IdentifierColumn | undefined\n ): Sql {\n const state = scalar.physical.scalar[\"~\"].state;\n const domain = exactDecimalDomain(state);\n const operand = domain ? decimalSumOperand(value, domain) : undefined;\n // A value that is not an exact decimal is the ordinary binder's refusal.\n if (!domain || operand === undefined)\n return this.#scalarValue(scalar.physical.scalar, value, scalar.field, id);\n const { canonical, coefficient } = operand;\n const precision =\n this.adapter.aggregates.decimalSumOperandPrecision(coefficient);\n if (precision === undefined) {\n const digits = coefficient.startsWith(\"-\")\n ? coefficient.length - 1\n : coefficient.length;\n throw new QueryEngineError(\n `The 'having' _sum operand for decimal field '${scalar.field}' needs ${digits} coefficient digits, but its value is outside this provider's exact HAVING operand cast domain. ` +\n \"The provider may compute a wider sum, but VibORM cannot express this operand through its exact decimal cast without changing or refusing the value written.\"\n );\n }\n return this.adapter.literals.decimal(canonical, {\n precision: Math.max(domain.precision, precision),\n scale: domain.scale,\n });\n }\n /**\n * THE JSON NULL TRUTH TABLE and the document operator set. A JSON column's\n * operands are documents rather than scalars, which is a storage difference,\n * not a second semantic interpretation of the same operator.\n *\n * The target always names a scalar here: `lowerOperation` reaches this only\n * when that scalar's own state is a JSON document — never for a `_count`,\n * which has no column domain. A path with a null sentinel is refused at\n * admission (`pathSentinelRefusal`, validation/scalars/json.ts).\n */\n #lowerJsonOperation(predicate: BoundOperation, column: Sql): Sql {\n const a = this.adapter;\n const path = [\n ...(predicate.target.kind === \"column\"\n ? (predicate.target.path ?? [])\n : []),\n ];\n const value = predicate.value;\n const target = a.json.extract(column, path);\n const fold = (expression: Sql) =>\n predicate.insensitive\n ? a.expressions.asciiCaseFold(expression)\n : expression;\n const textTarget = () => fold(a.json.stringAtPath(column, path));\n const textValue = (member: unknown) => fold(a.literals.value(member));\n switch (predicate.operator) {\n case \"equals\": {\n const sentinel = jsonNullKindOf(value);\n if (sentinel) {\n const isDatabaseNull = a.operators.isNull(column);\n const isJsonNull = a.json.equals(target, a.json.value(null));\n if (sentinel === \"DbNull\") return isDatabaseNull;\n if (sentinel === \"JsonNull\") return isJsonNull;\n return a.operators.or(isDatabaseNull, isJsonNull);\n }\n if (value === null && path.length === 0)\n return a.operators.isNull(column);\n return a.json.equals(target, a.json.value(value));\n }\n case \"lt\":\n case \"lte\":\n case \"gt\":\n case \"gte\": {\n const compare = a.operators[predicate.operator];\n if (typeof value === \"number\")\n return compare(a.json.numberAtPath(column, path), this.value(value));\n if (typeof value === \"string\")\n return compare(a.json.stringAtPath(column, path), this.value(value));\n throw new QueryEngineError(\n `JSON filter '${predicate.operator}' requires a number or string operand.`\n );\n }\n case \"string_contains\":\n return a.operators.containsText(textTarget(), textValue(value));\n case \"string_starts_with\":\n return a.operators.startsWithText(textTarget(), textValue(value));\n case \"string_ends_with\":\n return a.operators.endsWithText(textTarget(), textValue(value));\n case \"array_contains\":\n return a.json.contains(\n target,\n a.json.value(Array.isArray(value) ? value : [value])\n );\n case \"array_starts_with\":\n return a.json.equals(\n a.json.extract(column, [...path, \"0\"]),\n a.json.value(value)\n );\n default:\n // `array_ends_with`, the one operator left: the same upstream owner as\n // the scalar operator switch above enumerates the JSON document\n // operators once, at admission.\n return a.json.equals(a.json.lastElement(target), a.json.value(value));\n }\n }\n /** One distance expression, for filters, ordering and projection alike. */\n #distanceExpression(\n column: Sql,\n state: ScalarState,\n field: string,\n specification: Input,\n usage: \"filter\" | \"orderBy\" | \"select\"\n ): Sql {\n if (state.type === \"vector\") {\n if (!this.adapter.capabilities.supportsVector)\n throw new FeatureNotSupportedError(\n \"vector\",\n usage,\n usage === \"orderBy\"\n ? \"vector ordering requires a pgvector-enabled PostgreSQL driver\"\n : \"vector distance select requires a pgvector-enabled PostgreSQL driver\"\n );\n const to = specification.to as number[];\n const { dimension } = state;\n if (dimension !== undefined && to.length !== dimension)\n throw new UnsupportedOperationError(\n `Vector distance ${usage} dimension mismatch for '${field}': expected ${dimension} values, received ${to.length}.`\n );\n const metric = specification.metric === \"cosine\" ? \"cosine\" : \"l2\";\n return this.adapter.vector[metric](\n column,\n this.adapter.vector.literal(to)\n );\n }\n const geoPoint = this.#geoPoint(`distance ${usage}`);\n if (!geoPoint.distance)\n throw new FeatureNotSupportedError(\n \"point\",\n `distance ${usage}`,\n \"GeoPoint distance is not supported by this provider.\"\n );\n const target = specification.to as GeoPoint;\n return geoPoint.distance(\n column,\n geoPoint.value(this.value(target.longitude), this.value(target.latitude))\n );\n }\n #lowerRelationPredicate(\n predicate: Extract<PreparedPredicate, { kind: \"relation\" }>,\n parentAlias?: string\n ): Sql {\n const a = this.adapter;\n if (\n predicate.quantifier === \"every\" &&\n !(predicate.predicate && states(predicate.predicate))\n )\n return a.literals.true();\n const { edge, closure } = predicate;\n const childAlias = this.alias();\n const frame = { alias: childAlias, escaped: false };\n this.#frames.push(frame);\n let nested: Sql | undefined;\n try {\n nested = predicate.predicate\n ? this.#lowerPredicate(predicate.predicate, childAlias)\n : undefined;\n } finally {\n this.#frames.pop();\n }\n const stated = nested\n ? [predicate.quantifier === \"every\" ? a.operators.not(nested) : nested]\n : [];\n let query: Sql;\n if (closure) {\n // The walk is this EXISTS's OWN `WITH`, never wrapped in a derived table\n // or a LATERAL: MySQL answers every outer row from one evaluation of a\n // wrapped correlated recursive CTE wherever the EXISTS is not flattened.\n // The walk owns membership and visibility; the reader joins by key.\n const { cte, cteName, walk, childColumns } = this.#walk(\n edge,\n parentAlias ?? \"\",\n closure\n );\n query = sql`${cte} ${a.subqueries.existsCheck(\n sql`${a.identifiers.aliased(a.identifiers.escape(cteName), walk)} ${a.joins.inner(\n this.table(edge.target, childAlias),\n this.#sameRow(\n edge.target,\n childAlias,\n childColumns.map((name) => a.identifiers.column(walk, name))\n )\n )}`,\n a.operators.and(...stated)\n )}`;\n } else\n query = this.#relationExists(\n edge,\n parentAlias ?? \"\",\n childAlias,\n predicate.unscoped === undefined,\n stated,\n predicate.predicate !== undefined && readsRelation(predicate.predicate),\n frame.escaped\n );\n switch (predicate.quantifier) {\n case \"some\":\n return a.filters.some(query);\n case \"none\":\n return a.filters.none(query);\n case \"every\":\n return a.filters.every(query);\n case \"is\":\n return predicate.predicate\n ? a.filters.is(query)\n : a.filters.isNot(query);\n default:\n // `isNot`, the one quantifier left: every relation filter that spells\n // quantifiers refuses a payload naming none of them in its own\n // registered sentence, at admission, so this switch only ever\n // receives an already-admitted quantifier.\n return predicate.predicate\n ? a.filters.isNot(query)\n : a.filters.is(query);\n }\n }\n /**\n * `EXISTS (SELECT 1 FROM target WHERE correlation AND stated)`: inside a\n * statement sharing its bodies ({@link sharingBodies}), a slot the\n * statement settles to that where the body is lowered once, and else to a\n * test of the body's key set, `EXISTS (SELECT 1 FROM <set> WHERE set.k =\n * parent.fk)`: a semijoin on the correlated columns, read under the same\n * layers and values, so it takes exactly the rows the EXISTS takes. A\n * reference edge only (a junction's and a variant's membership stay\n * where they are), and a body that states something.\n */\n #relationExists(\n edge: Membership,\n parent: string,\n child: string,\n scoped: boolean,\n stated: readonly Sql[],\n deeper = false,\n correlatedAbove = false\n ): Sql {\n const a = this.adapter;\n const member = this.#membershipWhere(edge, child, parent);\n // `correlation`'s two parts, lowered in its order.\n const domain = scoped ? this.domainOf(edge.target, \"related\") : undefined;\n const lowered = domain && this.lowerSelector(domain, child)!;\n // Where the filter goes on below (`deeper`), a dialect that sums nested\n // heights adds this level's `WHERE` height to every level under it: the\n // domain, isolated, pays its own height once, at the end of its branch\n // (`subqueries.isolated`; ENG-6, review 2).\n const related =\n lowered && deeper ? a.subqueries.isolated(lowered) : lowered;\n const inline = a.subqueries.existsCheck(\n this.table(edge.target, child),\n a.operators.and(\n related ? a.operators.and(member, related) : member,\n ...stated\n )\n );\n const shared = this.#shared;\n const conditions = related ? [related, ...stated] : stated;\n if (\n shared === undefined ||\n correlatedAbove ||\n edge.kind !== \"reference\" ||\n edge.discriminator !== undefined ||\n conditions.length === 0\n )\n return inline;\n const query = assembleAdapterSelect(a, {\n columns: sql.join(\n edge.pairs.map((pair, index) =>\n a.identifiers.aliased(\n this.column(edge.target, pair.target, child),\n `k${index}`\n )\n ),\n \", \"\n ),\n from: this.table(edge.target, child),\n where: a.operators.and(...conditions),\n });\n const key = sharedKey(query);\n let body = shared.byKey.get(key);\n if (body === undefined) {\n body = { name: `__shared_${shared.order.length}`, query, slots: [] };\n shared.byKey.set(key, body);\n shared.order.push(body);\n }\n const { name } = body;\n const use = a.subqueries.existsCheck(\n a.identifiers.escape(name),\n a.operators.and(\n ...edge.pairs.map((pair, index) =>\n a.operators.eq(\n this.column(edge.source, pair.source, parent),\n a.identifiers.column(name, `k${index}`)\n )\n )\n )\n );\n const slot = new SqlSlot(use);\n body.slots.push({ slot, inline, use });\n return slot;\n }\n /**\n * `EXISTS (SELECT 1 FROM target WHERE related AND stated)`, correlated to\n * nothing: inside a statement sharing its bodies, every occurrence with the\n * same text and values settles to one `WITH` member holding at most one row,\n * and each reads it as `EXISTS (SELECT 1 FROM <member>)`.\n */\n #lowerExists(predicate: Extract<PreparedPredicate, { kind: \"exists\" }>): Sql {\n const a = this.adapter;\n const { model } = predicate;\n const child = this.alias();\n const frame = { alias: child, escaped: false };\n this.#frames.push(frame);\n let stated: Sql[];\n try {\n stated = predicate.predicate\n ? [this.#lowerPredicate(predicate.predicate, child)]\n : [];\n } finally {\n this.#frames.pop();\n }\n const domain = this.domainOf(model, \"related\");\n const lowered = domain && this.lowerSelector(domain, child);\n const related =\n lowered && predicate.predicate && readsRelation(predicate.predicate)\n ? a.subqueries.isolated(lowered)\n : lowered;\n const conditions = related ? [related, ...stated] : stated;\n const where =\n conditions.length === 0\n ? a.literals.true()\n : a.operators.and(...conditions);\n const inline = a.subqueries.existsCheck(this.table(model, child), where);\n const shared = this.#shared;\n // Correlated to a row above it: written where it is.\n if (shared === undefined || frame.escaped) return a.filters.some(inline);\n const query = assembleAdapterSelect(a, {\n columns: sql`1`,\n from: this.table(model, child),\n where,\n limit: this.value(1),\n });\n const key = sharedKey(query);\n let body = shared.byKey.get(key);\n if (body === undefined) {\n body = { name: `__shared_${shared.order.length}`, query, slots: [] };\n shared.byKey.set(key, body);\n shared.order.push(body);\n }\n const use = a.subqueries.existsCheck(\n a.identifiers.escape(body.name),\n a.literals.true()\n );\n const slot = new SqlSlot(use);\n body.slots.push({ slot, inline, use });\n return a.filters.some(slot);\n }\n /**\n * MySQL ERROR 1093: a subquery may not read the table its own statement is\n * mutating. A derived table sidesteps it — it is materialized before the\n * write — while the correlation to the outer mutation survives as an outer\n * reference (MySQL 8.0.14+). The capability the adapter already declares\n * (`supportsMutationTargetInSubquery`) is the whole condition; the wrap goes\n * inside the caller's scalar subquery, which supplies its own parentheses.\n * A mutation's own selector needs no wrap: on MySQL it is the keyed snapshot\n * ({@link lowerMutationLimit}).\n */\n private hideMutationTarget(\n subquery: Sql,\n child: AnyModel,\n mutationTarget: string | undefined\n ): Sql {\n if (\n mutationTarget === undefined ||\n this.adapter.capabilities.supportsMutationTargetInSubquery ||\n child[\"~\"].names.sql !== mutationTarget\n )\n return subquery;\n return sql`SELECT * FROM ${this.adapter.subqueries.correlate(\n subquery,\n this.alias()\n )}`;\n }\n /**\n * Does the PARENT row claim a membership in this arm?\n *\n * A variant ROW carrier stores the claim on the parent itself — a\n * discriminator naming the arm and a reference to the row — so \"linked\" is\n * answerable without reading the target at all. That is what separates an\n * EMPTY slot (no claim) from an ORPHANED one (a claim whose row is gone),\n * which the target subquery alone reports identically as `null`.\n *\n * `undefined` where the claim is not the parent's to make: the membership is\n * then the child's or a junction's, and this owner says nothing about it.\n */\n #parentClaimsArm(edge: Membership, parentAlias: string): Sql | undefined {\n if (\n edge.kind !== \"reference\" ||\n edge.owner !== \"source\" ||\n edge.discriminator?.side !== \"source\"\n )\n return undefined;\n const a = this.adapter;\n return a.operators.and(\n a.operators.eq(\n this.column(edge.source, edge.discriminator.field, parentAlias),\n this.value(edge.discriminator.value)\n ),\n ...edge.pairs.map((pair) =>\n a.operators.isNotNull(\n this.column(edge.source, pair.source, parentAlias)\n )\n )\n );\n }\n /** The one join of a relation to its parent, under the {@link related} domain. */\n correlation(\n edge: Membership,\n parent: string,\n target: string,\n scoped = true\n ): Sql {\n const member = this.#membershipWhere(edge, target, parent);\n return scoped ? this.#related(edge, target, member) : member;\n }\n /**\n * The one place the related domain enters a relation read, conjoined to the\n * `member` condition that reached `target`: outside any quantifier's\n * negation, so `every`, `none` and a negated count read \"every VISIBLE\n * member\", and on every edge, so a to-one projection, `is`/`isNot`, a to-one\n * order term and an upward recursion read a hidden target as an absent one.\n */\n #related(edge: Membership, target: string, member: Sql): Sql {\n const domain = this.domainOf(edge.target, \"related\");\n if (domain === undefined) return member;\n return this.adapter.operators.and(\n member,\n this.lowerSelector(domain, target)!\n );\n }\n memberWhere(edge: Membership, parent: Input, alias: string): Sql {\n return this.#membershipWhere(edge, alias, parent);\n }\n /**\n * The rows OUTSIDE a membership, in three-valued logic: a member-side\n * column left NULL, or a parent that holds no key, is outside — where a\n * plain negation of {@link memberWhere} would answer NULL and select nothing\n * (an ordered observation's found requirement, N1).\n */\n outsideWhere(edge: Membership, parent: Input, alias: string): Sql {\n const a = this.adapter;\n const inside = this.#membershipWhere(edge, alias, parent);\n if (edge.kind !== \"reference\") return a.operators.not(inside);\n const unbound = edge.pairs.some(\n (pair) =>\n parent[pair.source] === null || parent[pair.source] === undefined\n );\n if (unbound) return sql`1 = 1`;\n const columns = [\n ...(edge.discriminator?.side === \"target\"\n ? [edge.discriminator.field]\n : []),\n ...edge.pairs.map((pair) => pair.target),\n ];\n return a.operators.or(\n a.operators.not(inside),\n ...columns.map((field) =>\n a.operators.isNull(this.column(edge.target, field, alias))\n )\n );\n }\n #membershipWhere(\n edge: Membership,\n target: string,\n source: string | Input\n ): Sql {\n const a = this.adapter;\n if (edge.kind === \"reference\") {\n return a.operators.and(\n ...(edge.discriminator\n ? [\n a.operators.eq(\n edge.discriminator.side === \"source\"\n ? typeof source === \"string\"\n ? this.column(edge.source, edge.discriminator.field, source)\n : this.value(source[edge.discriminator.field])\n : this.column(edge.target, edge.discriminator.field, target),\n this.value(edge.discriminator.value)\n ),\n ]\n : []),\n ...edge.pairs.map((pair) =>\n a.operators.eq(\n typeof source === \"string\"\n ? this.column(edge.source, pair.source, source)\n : this.column(edge.target, pair.target, target),\n typeof source === \"string\"\n ? this.column(edge.target, pair.target, target)\n : this.fieldValue(edge.target, pair.target, source[pair.source])\n )\n )\n );\n }\n const junction = this.alias();\n // Membership first: the index on the source side finds the small target\n // worklist before the provider visits those target identities.\n return a.operators.in(\n rowValue(\n edge.targetSide.members.map((field) =>\n this.column(edge.target, field.referencedField, target)\n )\n ),\n a.subqueries.scalar(\n assembleAdapterSelect(a, {\n columns: sql.join(\n edge.targetSide.members.map((field) =>\n a.identifiers.column(junction, field.junctionField)\n ),\n \", \"\n ),\n from: a.identifiers.table(edge.table, junction),\n where: a.operators.and(\n ...this.junctionSideConditions(edge.sourceSide, junction, source)\n ),\n })\n )\n );\n }\n order(\n model: AnyModel,\n input: Arguments[\"orderBy\"],\n alias: string\n ): Sql | undefined {\n if (!input) return undefined;\n return this.#lowerOrder(this.#orderTerms(model, input, alias));\n }\n #lowerOrder(terms: readonly OrderTerm[]): Sql | undefined {\n if (terms.length === 0) return undefined;\n const a = this.adapter;\n return sql.join(\n terms.map((term) => {\n const direction = term.descending ? \"desc\" : \"asc\";\n if (!term.nullable || term.nulls === undefined)\n return a.orderBy[direction](term.expression);\n return term.nulls === \"first\"\n ? a.orderBy.nullsFirst(term.expression, direction)\n : a.orderBy.nullsLast(term.expression, direction);\n }),\n \", \"\n );\n }\n /**\n * One order owner. A scalar key, a to-one relation path, a collection\n * `_count`, a distance and a grouped aggregate are all sort keys; only a\n * direct scalar key can also serve as a cursor's total order.\n */\n #orderTerms(\n model: AnyModel,\n input: Arguments[\"orderBy\"],\n alias: string,\n cursored = false\n ): OrderTerm[] {\n if (!input) return [];\n const terms: OrderTerm[] = [];\n for (const order of entries(input)) {\n for (const field of Object.keys(order)) {\n const direction = order[field];\n if (direction !== undefined)\n terms.push(this.#orderTerm(model, field, direction, alias, cursored));\n }\n }\n return terms;\n }\n #orderTerm(\n model: AnyModel,\n field: string,\n direction: unknown,\n alias: string,\n cursored = false\n ): OrderTerm {\n if (model[\"~\"].state.relations[field])\n return this.#relationOrderTerm(model, field, record(direction), alias);\n const physical = physicalField(this.schema, model, field);\n const state = physical.scalar[\"~\"].state;\n const column = this.#operand(model, field, alias);\n const nullable = physical.nullable || this.#gatedHere(model, field);\n if (direction !== \"asc\" && direction !== \"desc\") {\n const specification = record(direction);\n if (specification._distance !== undefined) {\n // A cursor's eligibility is a fact about the REQUEST; a provider's\n // vector support is a fact about the PROVIDER. Classifying the order\n // first is what keeps `page`'s sentence the answer on a driver that\n // happens not to support vectors — `distanceExpression` consults the\n // capability while it BUILDS, so it would otherwise pre-empt it.\n if (cursored) throw new UnsupportedOperationError(CURSOR_ORDER_REFUSAL);\n const distance = record(specification._distance);\n const point = state.type === \"point\";\n return this.#sortKey(\n this.#distanceExpression(column, state, field, distance, \"orderBy\"),\n distance.sort === \"desc\",\n point ? \"last\" : undefined,\n point,\n undefined,\n point ? true : undefined\n );\n }\n return this.#sortKey(\n column,\n specification.sort === \"desc\",\n specification.nulls as \"first\" | \"last\" | undefined,\n nullable,\n field\n );\n }\n return this.#sortKey(\n column,\n direction === \"desc\",\n undefined,\n nullable,\n field\n );\n }\n /** A to-one path is one correlated value; a collection orders by `_count`. */\n #relationOrderTerm(\n model: AnyModel,\n field: string,\n specification: Input,\n alias: string\n ): OrderTerm {\n const a = this.adapter;\n // A collection orders by `_count`, and that count is the projection's own\n // count owner — including a variant carrier, which has no single membership.\n const { edges: counted } = this.countedMemberships(model, field);\n if (\n counted.length > 1 ||\n counted[0]!.many ||\n specification._count !== undefined\n )\n return this.#sortKey(\n this.#correlatedCount(counted, undefined, alias),\n specification._count === \"desc\",\n undefined,\n false\n );\n const edge = counted[0]!;\n const childAlias = this.alias();\n const correlation = this.correlation(edge, alias, childAlias);\n const [nested] = Object.entries(specification);\n const inner = this.#orderTerm(\n edge.target,\n nested![0],\n nested![1],\n childAlias\n );\n const value = assembleAdapterSelect(a, {\n columns: inner.expression,\n from: this.table(edge.target, childAlias),\n where: correlation,\n limit: this.value(1),\n });\n return this.#sortKey(\n a.subqueries.scalar(value),\n inner.descending,\n inner.nulls,\n true\n );\n }\n #sortKey(\n expression: Sql,\n descending: boolean,\n nulls: \"first\" | \"last\" | undefined,\n nullable: boolean,\n field?: string,\n expressionNulls?: true\n ): OrderTerm {\n return freeze({\n expression,\n descending,\n nulls: nulls ?? (descending ? \"first\" : \"last\"),\n expressionNulls,\n nullable,\n field,\n });\n }\n #reverseOrder(terms: readonly OrderTerm[]): OrderTerm[] {\n return terms.map((term) =>\n freeze({\n ...term,\n descending: !term.descending,\n nulls:\n term.nulls === undefined || term.expressionNulls\n ? term.nulls\n : term.nulls === \"first\"\n ? (\"last\" as const)\n : (\"first\" as const),\n })\n );\n }\n /**\n * One page owner: the root read and every nested node use it, so a nested\n * window is the ordinary page operator inside its parent's correlation.\n */\n #page(\n model: AnyModel,\n args: Pick<\n Partial<Arguments>,\n \"orderBy\" | \"take\" | \"skip\" | \"cursor\" | \"distinct\"\n >,\n alias: string,\n purpose?: RowPurpose\n ): {\n readonly orderBy?: Sql;\n readonly limit?: Sql;\n readonly offset?: Sql;\n readonly cursor?: Sql;\n readonly distinct?: Sql;\n readonly distinctOrderBy?: Sql;\n } {\n const backward = args.take !== undefined && args.take < 0;\n const cursored = args.cursor !== undefined;\n const requested = this.#orderTerms(model, args.orderBy, alias, cursored);\n const total = this.#totalOrder(model, requested, args.cursor, alias);\n // The single raise point for every other non-scalar key: a relation term\n // builds with `field: undefined` and is classified here.\n if (cursored && requested.some((term) => term.field === undefined))\n throw new UnsupportedOperationError(CURSOR_ORDER_REFUSAL);\n const terms = total ?? requested;\n return {\n orderBy: this.#lowerOrder(backward ? this.#reverseOrder(terms) : terms),\n distinctOrderBy:\n backward && args.distinct?.length ? this.#lowerOrder(terms) : undefined,\n limit:\n args.take === undefined ? undefined : this.value(Math.abs(args.take)),\n offset: args.skip === undefined ? undefined : this.value(args.skip),\n cursor:\n args.cursor === undefined\n ? undefined\n : this.#cursorCondition(\n model,\n backward ? this.#reverseOrder(total!) : total!,\n args.cursor,\n purpose\n ),\n distinct: args.distinct?.length\n ? sql.join(\n args.distinct.map((field) => this.#operand(model, field, alias)),\n \", \"\n )\n : undefined,\n };\n }\n /** A windowed read needs a deterministic total order, not just the caller's. */\n #totalOrder(\n model: AnyModel,\n requested: readonly OrderTerm[],\n cursor: Input | undefined,\n alias: string\n ): OrderTerm[] {\n if (getModelKeyCatalog(model).rowKey === undefined && cursor === undefined)\n return [...requested];\n const terms = this.#completeOrder(\n model,\n requested,\n alias,\n cursor ? Object.keys(this.#identityEntries(model, cursor)) : []\n );\n // Fill the owned completed array directly. Nullable keys need an explicit\n // placement, and cursor comparisons consume the complete term descriptors;\n // ordinary non-nullable ordering does not use a null placement.\n for (let index = 0; index < terms.length; index++) {\n const term = terms[index]!;\n if (term.nulls === undefined && (term.nullable || cursor !== undefined)) {\n terms[index] = freeze({\n ...term,\n nulls: term.descending ? \"first\" : \"last\",\n });\n }\n }\n return terms;\n }\n /**\n * The caller's terms completed by the model's identity: the ONE complete-key\n * tie-break. A windowed page and a recursive sibling order both need a\n * deterministic order and both read it here, so equal sort keys break the\n * same way wherever one parent's rows are ordered — a second spelling (the\n * row key in constraint order) ordered the same tied siblings differently\n * under recursion than under the ordinary window.\n */\n #completeOrder(\n model: AnyModel,\n requested: readonly OrderTerm[],\n alias: string,\n cursorFields: readonly string[] = []\n ): OrderTerm[] {\n const terms = [...requested];\n const ordered = new Set<string>();\n for (const term of terms) {\n if (term.field !== undefined) ordered.add(term.field);\n }\n const identity = this.keyOrder(model);\n const completion =\n cursorFields.length === 0 ? identity : [...identity, ...cursorFields];\n for (const field of completion) {\n if (ordered.has(field)) continue;\n ordered.add(field);\n const physical = physicalField(this.schema, model, field);\n terms.push(\n this.#sortKey(\n this.#operand(model, field, alias),\n false,\n \"last\",\n physical.nullable || this.#gatedHere(model, field),\n field\n )\n );\n }\n return terms;\n }\n /**\n * The model's key order: a bare scalar id, else the row key's fields in\n * declaration order. A windowed read's tie-break, and the order a limited\n * write takes its rows in ({@link capped}, {@link through}).\n */\n keyOrder(model: AnyModel): readonly string[] {\n const catalog = getModelKeyCatalog(model);\n const bare = catalog.addressableKeys.find(\n (key) => key.kind === \"primary\" && key.name === undefined\n );\n if (bare) return bare.fields;\n const rowKey = catalog.rowKey;\n if (!rowKey)\n throw new QueryEngineError(\n \"Paginated scalar ordering requires a primary model identifier.\"\n );\n const fields = new Set<string>(rowKey.fields);\n return Object.keys(model[\"~\"].state.scalars).filter((field) =>\n fields.has(field)\n );\n }\n /** A strict unique selector's exact field values, compound keys expanded. */\n #identityEntries(model: AnyModel, input: Input): Input {\n const identity: Input = {};\n for (const [name, value] of Object.entries(input)) {\n const key = findAddressableKey(model, name);\n if (key?.name)\n for (const field of key.fields) identity[field] = record(value)[field];\n else identity[name] = value;\n }\n return identity;\n }\n /**\n * One null-aware lexicographic window against the cursor row. Where every\n * key is NOT NULL and shares a direction the same meaning is spelled as a\n * row-value comparison, which a planner can turn into a range seek.\n */\n #cursorCondition(\n model: AnyModel,\n order: readonly OrderTerm[],\n cursor: Input,\n purpose: RowPurpose | undefined\n ): Sql {\n const a = this.adapter;\n const identity = this.#identityEntries(model, cursor);\n const sourceAlias = this.alias();\n // The anchor is a candidate like any other: a hidden one is a missing one.\n const scope = purpose && this.domainOf(model, purpose);\n const where = a.operators.and(\n ...(scope ? [this.lowerSelector(scope, sourceAlias)!] : []),\n ...Object.entries(identity).map(([field, value]) => {\n if (value === null)\n throw new QueryEngineError(\n `Cursor field '${field}' cannot be null. Cursor must point to a specific record.`\n );\n return a.operators.eq(\n this.#operand(model, field, sourceAlias),\n this.fieldValue(model, field, value)\n );\n })\n );\n const descending = order[0]!.descending;\n const sargable = order.every(\n (term) => !term.nullable && term.descending === descending\n );\n const cursorRow = (columns: Sql[]) =>\n assembleAdapterSelect(a, {\n columns: sql.join(columns, \", \"),\n from: this.table(model, sourceAlias),\n where,\n limit: this.value(1),\n });\n const keyColumns = order.map((term) =>\n this.#operand(model, term.field!, sourceAlias)\n );\n if (sargable)\n return (descending ? a.operators.lte : a.operators.gte)(\n rowValue(order.map((term) => term.expression)),\n a.subqueries.scalar(cursorRow(keyColumns))\n );\n const cursorAlias = this.alias();\n const carrier = (index: number) => `${CURSOR_CARRIER_PREFIX}${index}`;\n const derived = cursorRow(\n keyColumns.map((column, index) =>\n a.identifiers.aliased(column, carrier(index))\n )\n );\n const comparisons = order.map((term, index) => ({\n row: term.expression,\n cursor: a.identifiers.column(cursorAlias, carrier(index)),\n term,\n }));\n const equalities: Sql[] = [];\n const afterTerms: Sql[] = [];\n for (const { row, cursor: key, term } of comparisons) {\n const compare = term.descending ? a.operators.lt : a.operators.gt;\n const strict = a.operators.and(\n a.operators.isNotNull(row),\n compare(row, key)\n );\n afterTerms.push(\n a.operators.and(\n ...equalities,\n term.nulls === \"first\"\n ? a.operators.or(\n a.operators.and(\n a.operators.isNull(key),\n a.operators.isNotNull(row)\n ),\n a.operators.and(a.operators.isNotNull(key), strict)\n )\n : a.operators.and(\n a.operators.isNotNull(key),\n a.operators.or(a.operators.isNull(row), strict)\n )\n )\n );\n equalities.push(\n a.operators.or(\n a.operators.and(a.operators.isNull(row), a.operators.isNull(key)),\n a.operators.and(\n a.operators.isNotNull(row),\n a.operators.isNotNull(key),\n a.operators.eq(row, key)\n )\n )\n );\n }\n afterTerms.push(a.operators.and(...equalities));\n return a.operators.exists(\n assembleAdapterSelect(a, {\n columns: a.literals.true(),\n from: a.subqueries.correlate(derived, cursorAlias),\n where: a.operators.or(...afterTerms),\n })\n );\n }\n select(\n model: AnyModel,\n args: Partial<Arguments>,\n membership?: { edge: Membership; parent: Input; outside?: boolean },\n controls: {\n condition?: Sql;\n forUpdate?: boolean;\n identity?: Input;\n projection?: PreparedProjection;\n selector?: Pick<PreparedSelector, \"model\" | \"predicate\">;\n /** Rows this selector does not take, NULL read as not taken. */\n unless?: Pick<PreparedSelector, \"model\" | \"predicate\">;\n /** The rows the read takes: its selector and cursor anchor under it. */\n purpose?: RowPurpose;\n } = {}\n ): Query {\n const alias = this.#rootAlias();\n // The shipped owner sequence, and the reason it is stated here: when one\n // call violates two contracts at once, the refusal the caller sees is the\n // one whose owner runs first. `buildFind` (`operations/find-common.ts`)\n // pages before it selects and selects before it builds the `where`, so the\n // cursor refusal outranks a projection refusal and both outrank a `where`\n // refusal. Nothing below reads the projection or the selector, so this is\n // an ORDER, not a dependency (`g4/unit01-review-followup-3.md` finding K).\n const page = this.#page(model, args, alias, controls.purpose);\n const prepared = controls.projection ?? this.prepareProjection(model, args);\n const projection = this.lowerProjection(\n prepared,\n alias,\n controls.purpose !== undefined\n );\n const given =\n controls.selector ??\n (args.where === undefined\n ? undefined\n : this.prepareSelector(model, args.where, false, false));\n const selector =\n controls.purpose === undefined\n ? given\n : this.#within(model, given, controls.purpose);\n const filter = selector ? this.lowerSelector(selector, alias) : undefined;\n const a = this.adapter;\n const unless =\n controls.unless &&\n a.operators.not(\n a.expressions.coalesce(\n this.lowerSelector(controls.unless, alias) ?? a.literals.true(),\n a.literals.false()\n )\n );\n return {\n sql: assembleAdapterSelect(this.adapter, {\n columns: sql.join(projection, \", \"),\n from: this.table(model, alias),\n where: this.#selectWhere(\n model,\n alias,\n membership,\n filter,\n unless,\n page.cursor,\n controls\n ),\n orderBy: page.orderBy,\n limit: page.limit,\n offset: page.offset,\n forUpdate: controls.forUpdate,\n ...(page.distinct\n ? {\n distinct: page.distinct,\n distinctOrderBy: page.distinctOrderBy,\n distinctColumnAliases: prepared.fields.map((field) => field.name),\n }\n : {}),\n }),\n shape: prepared.shape,\n };\n }\n /** {@link select}'s conjunction, in its order; `undefined` for none. */\n #selectWhere(\n model: AnyModel,\n alias: string,\n membership:\n | { edge: Membership; parent: Input; outside?: boolean }\n | undefined,\n filter: Sql | undefined,\n unless: Sql | undefined,\n cursor: Sql | undefined,\n controls: { condition?: Sql; identity?: Input }\n ): Sql | undefined {\n const where: Sql[] = [];\n if (membership)\n where.push(\n membership.outside\n ? this.outsideWhere(membership.edge, membership.parent, alias)\n : this.memberWhere(membership.edge, membership.parent, alias)\n );\n if (filter) where.push(filter);\n if (unless) where.push(unless);\n if (cursor) where.push(cursor);\n if (controls.identity)\n where.push(this.lowerIdentity(model, controls.identity, alias));\n if (controls.condition) where.push(controls.condition);\n return where.length === 0\n ? undefined\n : this.adapter.operators.and(...where);\n }\n /**\n * Every read verb is one cardinality and shape decision over the same\n * select, projection and decoder owners, its statement sharing its\n * relation bodies where the adapter does ({@link sharingBodies}).\n */\n read(model: AnyModel, operation: ReadOperation, args: Arguments): Read {\n if (!this.#sharesBodies) return this.#read(model, operation, args);\n let read: Read | undefined;\n const statement = this.#sharingBodies(() => {\n read = this.#read(model, operation, args);\n return read.query.sql;\n });\n return { ...read!, query: { ...read!.query, sql: statement } };\n }\n #read(model: AnyModel, operation: ReadOperation, args: Arguments): Read {\n switch (operation) {\n case \"findUnique\": {\n // The one read verb whose `where` is a unique selector: its addressable\n // entries name the row through the constraint, exactly as the shipped\n // `buildWhereUnique` compiles them, while `findFirst`/`findMany` read\n // the same object as a filter.\n const query = this.select(model, args, undefined, {\n selector:\n args.where === undefined\n ? undefined\n : this.prepareSelector(model, args.where, true, false),\n purpose: \"root\",\n });\n return {\n query,\n single: true,\n value: query.shape,\n result: firstRow,\n };\n }\n case \"findFirst\": {\n // A negative take selects from the end of the window: the signed unit\n // limit flips the total order and still returns one row.\n const take = args.take === undefined ? 1 : Math.sign(args.take);\n const query = this.select(\n model,\n { ...args, take },\n undefined,\n ROOT_CANDIDATES\n );\n return {\n query,\n single: true,\n value: query.shape,\n result: firstRow,\n };\n }\n case \"findMany\": {\n const backward = args.take !== undefined && args.take < 0;\n const query = this.select(model, args, undefined, ROOT_CANDIDATES);\n return {\n query,\n single: false,\n value: rowSet(query),\n result: backward ? reversedRows : rowIdentity,\n };\n }\n default:\n return this.#readAggregate(model, operation, args);\n }\n }\n /** Counting and aggregate reads, out of line from the row reads above. */\n #readAggregate(\n model: AnyModel,\n operation: Exclude<ReadOperation, \"findUnique\" | \"findFirst\" | \"findMany\">,\n args: Arguments\n ): Read {\n switch (operation) {\n case \"exist\": {\n // Existence is order-blind and `exist` admits only `where`: the\n // filtered table itself, with no total order to sort or scan by.\n const a = this.adapter;\n const alias = this.#rootAlias();\n const rows = assembleAdapterSelect(a, {\n columns: a.literals.true(),\n from: this.table(model, alias),\n where: this.lowerWhere(model, args.where, alias),\n });\n const query: Query = {\n sql: a.clauses.select(\n a.identifiers.aliased(a.operators.exists(rows), \"_count\")\n ),\n shape: { kind: \"object\", fields: { _count: BOOLEAN_LEAF } },\n expectedRows: {\n count: 1,\n missing: new QueryEngineError(\n \"Provider omitted the required existence result row.\"\n ),\n },\n };\n return {\n query,\n single: false,\n value: BOOLEAN_LEAF,\n result: (rows) => rows[0]?._count ?? false,\n };\n }\n case \"count\": {\n const selected = args.select ? record(args.select) : undefined;\n const outputs: { name: string; field?: string }[] = selected\n ? [\n ...(selected._all ? [{ name: \"_all\" }] : []),\n ...Object.keys(selected)\n .filter((field) => field !== \"_all\" && selected[field])\n .map((field) => ({ name: field, field })),\n ]\n : [{ name: \"_count\" }];\n const fields = outputs.flatMap(({ field }) =>\n field === undefined ? [] : [field]\n );\n const query = this.aggregated(\n model,\n args,\n fields,\n (alias) =>\n outputs.map(({ name, field }): [string, Sql] => [\n name,\n this.adapter.aggregates.count(\n field === undefined\n ? undefined\n : this.#operand(model, field, alias)\n ),\n ]),\n () => ({\n kind: \"object\",\n fields: Object.fromEntries(\n outputs.map(({ name }) => [name, COUNT_LEAF])\n ),\n })\n );\n query.expectedRows = {\n count: 1,\n missing: new QueryEngineError(\n \"Provider omitted the required aggregate result row.\"\n ),\n };\n return {\n query,\n // `count` publishes a number and `exist` a boolean: one VALUE, not one\n // row, so neither is `single` — the row they decode is scaffolding.\n single: selected !== undefined,\n value: selected ? query.shape : COUNT_LEAF,\n result: (rows) =>\n selected ? (rows[0] ?? {}) : ((rows[0]?._count as number) ?? 0),\n };\n }\n case \"aggregate\": {\n const prepared = this.#prepareAggregates(model, args);\n const query = this.aggregated(\n model,\n args,\n prepared.fields,\n (alias) => prepared.columns(alias),\n () => ({ kind: \"object\", fields: prepared.fields_ })\n );\n return {\n query,\n single: true,\n value: query.shape,\n result: aggregateRow,\n };\n }\n case \"groupBy\": {\n const query = this.grouped(model, args);\n return {\n query,\n single: false,\n value: rowSet(query),\n result: rowIdentity,\n };\n }\n default:\n return unreachable(operation, \"read operation\");\n }\n }\n /**\n * One aggregate statement. Aggregates are order-blind, so only a page\n * (`take`, `skip`, `cursor`) needs a window: the same filter, total order,\n * cursor and page, aggregated outside it. An unpaged aggregate reads the\n * filtered table itself, which leaves the provider its count fast path and\n * covering indexes instead of a key-ordered scan or a sort.\n */\n private aggregated(\n model: AnyModel,\n args: Arguments,\n fields: readonly string[],\n columns: (alias: string) => [string, Sql][],\n shape: (alias: string) => Extract<Shape, { kind: \"object\" }>\n ): Query {\n const a = this.adapter;\n const inner = this.#rootAlias();\n const page = this.#page(model, args, inner, \"root\");\n const filter = this.lowerWhere(model, args.where, inner);\n const aggregate = (alias: string, from: Sql, where?: Sql): Query => ({\n sql: assembleAdapterSelect(a, {\n columns: sql.join(\n columns(alias).map(([name, expression]) =>\n a.identifiers.aliased(expression, name)\n ),\n \", \"\n ),\n from,\n where,\n }),\n shape: shape(alias),\n });\n // A read-gated model aggregates a masked window (K5): its gate lowered\n // once per row, not once per aggregate over the field.\n if (!((page.limit ?? page.offset ?? page.cursor) || this.#masks(model)))\n return aggregate(inner, this.table(model, inner), filter);\n const window = assembleAdapterSelect(a, {\n columns: fields.length\n ? sql.join(\n [...new Set(fields)].map((field) =>\n a.identifiers.aliased(\n this.#operand(model, field, inner),\n this.columnName(model, field)\n )\n ),\n \", \"\n )\n : a.identifiers.aliased(this.value(1), \"0viborm_row\"),\n from: this.table(model, inner),\n where: a.operators.and(\n ...(filter ? [filter] : []),\n ...(page.cursor ? [page.cursor] : [])\n ),\n orderBy: page.orderBy,\n limit: page.limit,\n offset: page.offset,\n });\n const outer = this.alias();\n // The window masks its read-gated columns: the aggregate reads them as\n // they are.\n return this.#overMasked(() =>\n aggregate(outer, a.subqueries.correlate(window, outer))\n );\n }\n /** The admitted aggregate selections, as columns and as decoder leaves. */\n #prepareAggregates(\n model: AnyModel,\n args: Arguments\n ): {\n readonly fields: string[];\n readonly fields_: Record<string, Shape | Leaf>;\n columns(alias: string): [string, Sql][];\n } {\n const a = this.adapter;\n const fields: string[] = [];\n const shape: Record<string, Shape | Leaf> = {};\n const builders: ((alias: string) => [string, Sql])[] = [];\n for (const name of AGGREGATES) {\n const selection = args[name];\n if (!selection) continue;\n if (name === \"_count\" && selection === true) {\n shape._count = COUNT_LEAF;\n builders.push(() => [\"_count\", a.aggregates.count()]);\n continue;\n }\n const selected = Object.entries(record(selection)).filter(\n ([, include]) => include\n );\n if (selected.length === 0) continue;\n const leaves: Record<string, Leaf> = {};\n for (const [field] of selected) {\n if (field !== \"_all\") fields.push(field);\n leaves[field] = this.#aggregateLeaf(model, name, field);\n }\n shape[name] = { kind: \"object\", fields: leaves };\n builders.push((alias) => [\n name,\n a.json.objectFromColumns(\n selected.map(([field]) => {\n const leaf = leaves[field]!;\n const scalar =\n field === \"_all\" ? undefined : this.#scalar(model, field);\n const split = this.#splitSum(leaf);\n if (split)\n return [\n field,\n a.json.array(\n split\n .sql(this.#preparedColumn(scalar!, alias))\n .parts.map((part) => this.#carriedValue(leaf, part))\n ),\n ];\n return [\n field,\n this.#carriedValue(\n leaf,\n this.#aggregateExpression(name, scalar, alias)\n ),\n ];\n })\n ),\n ]);\n }\n return {\n fields,\n fields_: shape,\n columns: (alias) => builders.map((build) => build(alias)),\n };\n }\n /** One aggregate leaf classification: projection, `having` and `orderBy`. */\n #aggregateLeaf(model: AnyModel, aggregate: Aggregate, field: string): Leaf {\n if (aggregate === \"_count\") return COUNT_LEAF;\n const leaf = this.scalarShape(model, field);\n if (aggregate === \"_avg\" && leaf.type !== \"decimal\")\n return freeze({ kind: \"scalar\", type: \"number\", nullable: true });\n // Admission admits `_sum` only on the summable types, every one widened.\n return freeze({\n ...leaf,\n nullable: true,\n widened: aggregate === \"_sum\" ? true : undefined,\n });\n }\n /**\n * A widened `_sum` the provider's own `SUM` would overflow travels as two\n * parts no realistic row count overflows, joined before the field's decoder\n * reads it (engine-10): a number on every dialect, an int64 — an int, a\n * bigint or SQLite's decimal coefficient — where the adapter states\n * `integerSum`.\n */\n #splitSum(leaf: Leaf): SplitSum | undefined {\n if (!leaf.widened) return undefined;\n const { numberSum, integerSum } = this.adapter.aggregates;\n if (leaf.type === \"number\") return { sql: numberSum, join: joinNumberSum };\n return (\n integerSum && {\n sql: integerSum,\n join: (parts) => joinIntegerSum(parts, leaf.type),\n }\n );\n }\n /**\n * A split `_sum` as `having` compares it and a grouped `orderBy` sorts it:\n * the sum the projection publishes, not the provider's own `SUM`, which\n * can raise or answer another number (engine-10).\n */\n #splitSumSql(scalar: PreparedScalar, column: Sql): SplitSumSql | undefined {\n return this.#splitSum(\n this.#aggregateLeaf(scalar.model, \"_sum\", scalar.field)\n )?.sql(column);\n }\n #aggregateExpression(\n aggregate: Aggregate,\n scalar: PreparedScalar | undefined,\n alias?: string\n ): Sql {\n const a = this.adapter;\n const column = scalar ? this.#preparedColumn(scalar, alias) : undefined;\n const state = scalar?.physical.scalar[\"~\"].state;\n // biome-ignore lint/style/useDefaultSwitchClause: the Aggregate union is exhaustive; a default would be dead code.\n switch (aggregate) {\n case \"_count\":\n return a.aggregates.count(column);\n case \"_sum\":\n return (\n this.#splitSumSql(scalar!, column!)?.value ??\n a.aggregates.sum(column!)\n );\n case \"_min\":\n case \"_max\": {\n // Admission admits `_all` under `_count` alone, so these name a\n // column. A compact identifier is aggregated in the spelling it\n // TRAVELS in (`identifier.ts`); every other column is aggregated as\n // stored.\n const operand = aggregatedIdentifier(\n a,\n this.scalarShape(scalar!.model, scalar!.field).id,\n column!\n );\n return aggregate === \"_min\"\n ? a.aggregates.min(operand, state?.type === \"boolean\")\n : a.aggregates.max(operand, state?.type === \"boolean\");\n }\n case \"_avg\":\n return state?.type === \"decimal\" && state.decimal\n ? a.aggregates.decimalAvg(column!, state.decimal)\n : a.aggregates.avg(column!);\n }\n }\n selectSeries(\n prepared: PreparedProjection,\n identities: Input[],\n operation: \"createMany\" | \"updateMany\" = \"createMany\"\n ): Query {\n const model = prepared.model;\n const alias = this.#rootAlias();\n const projection = this.lowerProjection(prepared, alias);\n const predicates = identities.map((identity) =>\n this.lowerIdentity(model, identity, alias)\n );\n return {\n sql: assembleAdapterSelect(this.adapter, {\n columns: sql.join(projection, \", \"),\n from: this.table(model, alias),\n where: balancedOr(predicates, (arms) =>\n this.adapter.operators.or(...arms)\n ),\n orderBy: this.adapter.expressions.caseWhen(\n predicates.map((when, index) => ({\n when,\n then: this.value(index),\n })),\n this.value(identities.length)\n ),\n }),\n shape: prepared.shape,\n expectedRows: {\n count: identities.length,\n missing:\n operation === \"createMany\"\n ? new QueryEngineError(\n \"createMany with 'select' could not read back one of the created rows at the primary key it reported. A later row in the same call moved that row's primary key; use the '{ count }' form, or write those rows in separate calls.\"\n )\n : new TransactionError(\n \"updateMany with 'select' could not read back one of the updated rows at its final primary key.\",\n {\n meta: {\n model: model[\"~\"].names.ts ?? \"unknown\",\n operation: \"updateMany\",\n },\n }\n ),\n },\n };\n }\n /** The `_count` member of a projection, out of line: most reads have none. */\n #projectCounts(\n model: AnyModel,\n name: string,\n selection: unknown,\n fields: Record<string, Shape | Leaf>,\n prepared: PreparedProjectionField[]\n ): void {\n const counts = this.#prepareCounts(model, selection);\n // An empty count SELECTION contributes no field at all: the shipped\n // engine pushed the `_count` pair only `if (relationCountPairs.length\n // > 0)` (`select-builder.ts:418`), so `_count: true` on a model with\n // no to-many relation publishes no `_count` key rather than `{}`.\n if (counts.length === 0) return;\n fields[name] = freeze({\n kind: \"object\",\n // A count carrier is a document the statement always builds: a\n // provider that answers `null` here has not answered the question,\n // and an object shape that carried no nullability let that `null`\n // reach a caller whose type says `{ children: number }`.\n nullable: false,\n fields: freeze(\n Object.fromEntries(counts.map((count) => [count.relation, COUNT_LEAF]))\n ),\n });\n prepared.push(freeze({ kind: \"counts\", name, counts }));\n }\n /** A selected `_distance`, out of line: most reads select none. */\n #projectDistance(\n model: AnyModel,\n name: string,\n distance: unknown,\n distanceSelected: boolean,\n fields: Record<string, Shape | Leaf>,\n prepared: PreparedProjectionField[]\n ): void {\n if (distanceSelected) throw new QueryEngineError(DISTANCE_SELECTED_TWICE);\n // The output key `_distance` is the distance's alone: schema\n // validation refuses a member of that name (F010).\n prepared.push(\n freeze({\n kind: \"distance\",\n name: DISTANCE_FIELD,\n field: name,\n specification: record(distance),\n })\n );\n fields[DISTANCE_FIELD] = this.#distanceLeaf(model, name, record(distance));\n }\n /** A polymorphic slot's projection, out of line: most reads have none. */\n #projectVariants(\n model: AnyModel,\n name: string,\n resolved: ResolvedSlot,\n selection: unknown,\n fields: Record<string, Shape | Leaf>,\n prepared: PreparedProjectionField[],\n path: string\n ): void {\n // The caller dispatched on a variant carrier; the closure below loses that.\n const edge = resolved.edge as ResolvedVariantEdge;\n const many = edge.kind === \"variantJunctionCarrier\";\n // A junction-carried slot's arm is a collection of its rows; a row\n // carrier's arm is the target's document.\n const collections: Record<string, CollectionShape> = {};\n const documents: Record<string, Shape> = {};\n const preparedArms: ({\n readonly variant: string;\n } & PreparedRelationProjection)[] = [];\n // The integrity probe's subjects: every configured member of a\n // junction-carried slot, each of which binds a junction membership (an\n // invariant of this one construction site, not a refusal: N4). A ROW\n // carrier states its own claim on the parent row, which the arm document\n // already answers (D-19).\n const memberships = many\n ? edge.members.map((member) => ({\n variant: member.variant,\n edge: bindMembership(\n this.schema,\n model,\n name,\n member.variant\n ) as Extract<Membership, { kind: \"junction\" }>,\n }))\n : [];\n // Which arms are read, and with which node, is `selectedArm`'s one\n // rule, shared with the schema-only result shape.\n for (const member of edge.members) {\n const arm = selectedArm(selection, many, member.variant);\n if (arm === undefined) continue;\n const nested = this.#prepareRelationProjection(\n bindMembership(this.schema, model, name, member.variant),\n arm,\n `${path}${many ? \"variants.\" : \"\"}${member.variant}.`\n );\n if (many) collections[member.variant] = this.#collectionShape(nested);\n else documents[member.variant] = this.#relationShape(nested);\n preparedArms.push(freeze({ variant: member.variant, ...nested }));\n }\n fields[name] = freeze(\n many\n ? {\n kind: \"variants\",\n relation: name,\n many,\n arms: freeze(collections),\n }\n : {\n kind: \"variants\",\n relation: name,\n many,\n arms: freeze(documents),\n }\n );\n prepared.push(\n freeze({\n kind: \"variants\",\n name,\n many,\n arms: freeze(preparedArms),\n memberships: freeze(memberships),\n })\n );\n }\n /**\n * One immutable alias-free projection description and decoder shape.\n *\n * An operation that names NEITHER `select` NOR `include` asks for the model's\n * DEFAULT projection, which is a fact of the model and the dialect and of\n * nothing else, so it is resolved once per (adapter, model) and shared\n * ({@link QueryViews}). Every other operation prepares per operation exactly\n * as before, reusing only the per-field leaves.\n */\n /**\n * `internal` names a projection the engine reads for itself (a stored row,\n * an identity): it carries no declared key and no gate, whatever the domain\n * declares (K5); every projection a caller's result reads is not internal.\n */\n prepareProjection(\n model: AnyModel,\n args: Partial<Arguments>,\n internal = false,\n path = \"\"\n ): PreparedProjection {\n const projected = internal ? undefined : this.domain?.projected(model);\n const shared = args.select === undefined && args.include === undefined;\n const defaults =\n projected === undefined\n ? this.#views.defaultProjections\n : this.domain!.defaultProjections;\n if (shared) {\n const resolved = defaults.get(model);\n if (resolved !== undefined) return resolved;\n }\n const named =\n projected && args.select !== undefined\n ? namedGatedFields.get(args.select)\n : undefined;\n // Made only where the domain gates a field of `model` (K5).\n const gated: Record<string, GatedMember> | undefined = projected && {};\n const gates = projected && new Map<FieldGate, string>();\n // `omit` is desugared into `select` at admission; an explicit selection and\n // an include can therefore both be present and both belong to the result.\n let selected = args.select ?? defaultSelection(model);\n if (args.include !== undefined) selected = { ...selected, ...args.include };\n const prepared: PreparedProjectionField[] = [];\n const fields: Record<string, Shape | Leaf> = {};\n let distanceSelected = false;\n for (const name of Object.keys(selected)) {\n const selection = selected[name];\n if (!selection) continue;\n // `_count` is the relation-count key and nothing else: schema\n // validation refuses a member of that name (F010).\n if (name === \"_count\") {\n this.#projectCounts(model, name, selection, fields, prepared);\n continue;\n }\n if (!model[\"~\"].state.relations[name]) {\n const distance =\n selection === true ? undefined : record(selection)._distance;\n if (distance !== undefined) {\n this.#projectDistance(\n model,\n name,\n distance,\n distanceSelected,\n fields,\n prepared\n );\n distanceSelected = true;\n continue;\n }\n }\n const evidence = projected?.keys.get(name);\n if (evidence !== undefined) {\n this.#projectEvidence(evidence, name, selection, fields, prepared);\n continue;\n }\n if (!model[\"~\"].state.relations[name]) {\n prepared.push(freeze({ kind: \"scalar\", name }));\n fields[name] = this.scalarShape(model, name);\n const gate = projected?.gates.get(name);\n if (gate === undefined) continue;\n let member = gates!.get(gate);\n if (member === undefined) {\n member = gateResultKey(gates!.size);\n gates!.set(gate, member);\n prepared.push(freeze({ kind: \"gate\", name: member, gate }));\n }\n gated![name] = named?.has(name)\n ? freeze({ gate: member, refused: `${path}select.${name}` })\n : freeze({ gate: member });\n continue;\n }\n const resolved = this.schema.index.get(model)!.get(name)!;\n if (\n !resolved.member &&\n (resolved.edge.kind === \"variantRowCarrier\" ||\n resolved.edge.kind === \"variantJunctionCarrier\")\n ) {\n this.#projectVariants(\n model,\n name,\n resolved,\n selection,\n fields,\n prepared,\n `${path}${args.include?.[name] === undefined ? \"select\" : \"include\"}.${name}.`\n );\n continue;\n }\n const nested = this.#prepareRelationProjection(\n bindMembership(this.schema, model, name),\n selection,\n `${path}${args.include?.[name] === undefined ? \"select\" : \"include\"}.${name}.`\n );\n fields[name] = this.#relationShape(nested);\n prepared.push(freeze({ kind: \"relation\", name, ...nested }));\n }\n // An empty projection is the model's own default — every scalar omitted —\n // and the row still exists, so it carries the sentinel column. A written\n // `select` that projects nothing never arrives: admission refuses it at\n // its path (`requireSelectedField`, validation/model/core/select.ts).\n if (prepared.length === 0)\n prepared.push(freeze({ kind: \"sentinel\", name: EMPTY_ROW_RESULT_KEY }));\n const projection: PreparedProjection = freeze({\n model,\n fields: freeze(prepared),\n shape: freeze(\n gates?.size\n ? {\n kind: \"object\",\n fields: freeze(fields),\n gated: freeze(gated!),\n gates: freeze([...gates.values()]),\n }\n : { kind: \"object\", fields: freeze(fields) }\n ),\n });\n if (shared) defaults.set(model, projection);\n return projection;\n }\n /**\n * A declared projection key (K5): `true` reports every declared name, a\n * list the names it gives, in declared order. Admission refused any other\n * value. With `ordered`, the last name that holds, `null` where `read` does\n * not; else one boolean per name.\n */\n #projectEvidence(\n evidence: DeclaredEvidence,\n name: string,\n selection: unknown,\n fields: Record<string, Shape | Leaf>,\n prepared: PreparedProjectionField[]\n ): void {\n const names =\n selection === true\n ? evidence.names\n : evidence.names.filter(([held]) =>\n (selection as readonly string[]).includes(held)\n );\n fields[name] = evidence.ordered\n ? freeze({\n kind: \"scalar\",\n type: \"enum\",\n nullable: true,\n enumValues: new Set(names.map(([held]) => held)),\n })\n : freeze({\n kind: \"object\",\n nullable: false,\n fields: freeze(\n Object.fromEntries(names.map(([held]) => [held, BOOLEAN_LEAF]))\n ),\n });\n prepared.push(freeze({ kind: \"evidence\", name, evidence, names }));\n }\n /**\n * A to-many node's decoded shape. A negative `take` runs the reversed window\n * exactly as at the root, so the carried array is restored to the caller's\n * logical order by the one decoder that reads this shape.\n */\n #relationShape(nested: PreparedRelationProjection): Shape {\n if (nested.recurrence) {\n const resolved = this.schema.index\n .get(nested.edge.source)!\n .get(nested.edge.name)!;\n return freeze({\n kind: \"recursive\",\n relation: nested.edge.name,\n many: nested.edge.many,\n optional: slotMayBeEmpty(resolved),\n recurrence: nested.recurrence,\n row: nested.projection.shape,\n identity: freeze(\n this.schema\n .keys(nested.edge.target)\n .map((field) => this.scalarShape(nested.edge.target, field))\n ),\n });\n }\n if (!nested.edge.many) return nested.projection.shape;\n return this.#collectionShape(nested);\n }\n /** A to-many relation's rows, in the window its `take` requested. */\n #collectionShape(nested: PreparedRelationProjection): CollectionShape {\n const take = nested.arguments.take;\n return freeze({\n kind: \"collection\",\n reversed: take !== undefined && take < 0 ? true : undefined,\n row: nested.projection.shape,\n });\n }\n /** A missing point/vector or a zero-norm cosine distance has no number. */\n #distanceLeaf(model: AnyModel, field: string, distance: Input): Leaf {\n const physical = physicalField(this.schema, model, field);\n return freeze({\n kind: \"scalar\",\n type: \"number\",\n nullable:\n physical.nullable ||\n (physical.scalar[\"~\"].state.type === \"vector\" &&\n distance.metric === \"cosine\"),\n });\n }\n #prepareRelationProjection(\n edge: Membership,\n selection: unknown,\n path = \"\"\n ): PreparedRelationProjection {\n const nested =\n selection === true ? {} : (record(selection) as Partial<Arguments>);\n return freeze({\n edge,\n arguments: freeze({\n selector: nested.where\n ? this.prepareSelector(edge.target, nested.where, false, false)\n : undefined,\n orderBy: nested.orderBy,\n take: nested.take,\n skip: nested.skip,\n cursor: nested.cursor,\n distinct: nested.distinct,\n }),\n projection: this.prepareProjection(edge.target, nested, false, path),\n recurrence: nested.recurse,\n });\n }\n /**\n * Admission desugars `_count: true` into `{ select: { relation: … } }`, so\n * the projection owner reads one shape; an entry may filter its target.\n */\n #prepareCounts(\n model: AnyModel,\n selection: unknown\n ): readonly PreparedCount[] {\n const requested = record(record(selection).select);\n const counts: PreparedCount[] = [];\n for (const [relation, configuration] of Object.entries(requested)) {\n if (!configuration) continue;\n const { edges, variants } = this.countedMemberships(model, relation);\n const where =\n configuration === true ? undefined : record(configuration).where;\n if (where === undefined) {\n counts.push(freeze({ relation, edges }));\n continue;\n }\n const filter = record(where);\n if (!variants) {\n counts.push(\n freeze({\n relation,\n edges,\n selector: this.prepareSelector(\n edges[0]!.target,\n filter,\n false,\n false\n ),\n })\n );\n continue;\n }\n // A TAGGED count filter selects an arm; it is not a scalar predicate\n // over one of them. `type` names the arm — admission makes it mandatory\n // for a polymorphic collection — and `is`/`isNot` are prepared against\n // THAT arm's target, whose columns are the only ones they can address.\n const tag = filter.type;\n const arm = edges.find((edge) => edge.scope.member?.variant === tag);\n if (!arm)\n throw new QueryEngineError(\n `Unknown polymorphic target '${String(tag)}' for relation '${relation}'.`\n );\n const negated = filter.isNot !== undefined;\n const inner = negated ? filter.isNot : filter.is;\n counts.push(\n freeze({\n relation,\n edges: freeze([arm]),\n selector:\n inner === undefined\n ? undefined\n : this.prepareSelector(arm.target, record(inner), false, false),\n ...(negated ? { negated: true as const } : {}),\n })\n );\n }\n return freeze(counts);\n }\n /**\n * Every membership one relation SLOT counts.\n *\n * An ordinary relation is one edge. A variant carrier is not: it has no single\n * membership — each arm has its own target and its own correlation — so the\n * slot's population is the union of its arms, and its size is their sum. This\n * is the one place that fact is stated; the `_count` projection and `_count`\n * ordering both read it here.\n */\n private countedMemberships(\n model: AnyModel,\n relation: string\n ): {\n readonly edges: readonly Membership[];\n /**\n * Whether those memberships are a carrier's ARMS. The same owner answers\n * it, because it is the same classification: a tagged `_count` filter\n * selects one arm and an ordinary `where` filters one target, and reading\n * \"is this a carrier?\" a second time is how the two got confused.\n */\n readonly variants: boolean;\n } {\n const resolved = this.schema.index.get(model)!.get(relation)!;\n const carrier =\n resolved.member === undefined &&\n (resolved.edge.kind === \"variantRowCarrier\" ||\n resolved.edge.kind === \"variantJunctionCarrier\")\n ? resolved.edge\n : undefined;\n return freeze({\n edges: freeze(\n carrier\n ? carrier.members.map((member) =>\n bindMembership(this.schema, model, relation, member.variant)\n )\n : [bindMembership(this.schema, model, relation)]\n ),\n variants: carrier !== undefined,\n });\n }\n /**\n * `visible`: every row this projection reads is one the domain takes, so\n * each layer's `read` holds there and its evidence tests the rest alone; a\n * row captured by identity (a write's) is not (K5).\n */\n lowerProjection(\n projection: PreparedProjection,\n alias?: string,\n visible = false\n ): Sql[] {\n const columns: Sql[] = [];\n for (const field of projection.fields) {\n columns.push(\n this.adapter.identifiers.aliased(\n this.#lowerProjectionField(projection, field, alias, visible),\n field.name\n )\n );\n }\n return columns;\n }\n /** Count, distance and polymorphic members, out of line from plain columns. */\n #lowerSpecialProjectionField(\n projection: PreparedProjection,\n field: Exclude<\n PreparedProjectionField,\n { kind: \"scalar\" | \"sentinel\" | \"relation\" | \"evidence\" | \"gate\" }\n >,\n alias?: string\n ): Sql {\n const a = this.adapter;\n let expression: Sql;\n if (field.kind === \"counts\") {\n expression = a.json.objectFromColumns(\n field.counts.map((count) => [\n count.relation,\n this.#correlatedCount(\n count.edges,\n count.selector,\n alias ?? \"\",\n count.negated\n ),\n ])\n );\n } else if (field.kind === \"distance\") {\n expression = this.#distanceExpression(\n this.column(projection.model, field.field, alias),\n physicalField(this.schema, projection.model, field.field).scalar[\"~\"]\n .state,\n field.field,\n field.specification,\n \"select\"\n );\n } else {\n // The slot's own document: one entry per SELECTED arm, and — for a\n // junction-carried slot — one integrity entry naming every CONFIGURED\n // member (D-26). The integrity entry is a sibling of the arms, so it is\n // answered whatever `only` selected, including nothing at all.\n const integrity: [string, Sql][] =\n field.memberships.length === 0\n ? []\n : [\n [\n POLYMORPHIC_COLLECTION_ORPHANS_KEY,\n a.json.document(\n a.json.objectFromColumns(\n field.memberships.map((member) => [\n member.variant,\n this.#orphanedMemberships(member.edge, alias ?? \"\"),\n ])\n )\n ),\n ],\n ];\n const resolved = this.schema.index\n .get(projection.model)!\n .get(field.name)!;\n if (resolved.edge.kind === \"variantRowCarrier\") {\n const edge = resolved.edge;\n const type = this.column(\n projection.model,\n edge.storage.typeColumn.name,\n alias\n );\n const id = this.column(\n projection.model,\n edge.storage.idColumn.name,\n alias\n );\n const empty = slotMayBeEmpty(resolved)\n ? a.operators.and(a.operators.isNull(type), a.operators.isNull(id))\n : a.literals.false();\n const valid = a.operators.and(\n a.operators.isNotNull(id),\n a.operators.or(\n ...edge.members.map((member) =>\n a.operators.eq(type, this.value(member.entry.storedValue))\n )\n )\n );\n const invalid = a.expressions.caseWhen(\n [{ when: a.operators.or(empty, valid), then: this.value(0) }],\n this.value(1)\n );\n integrity.push([\n POLYMORPHIC_COLLECTION_ORPHANS_KEY,\n a.json.document(a.json.objectFromColumns([[\"$storage\", invalid]])),\n ]);\n }\n expression = a.json.object([\n ...field.arms.map((arm) => {\n const row = this.#lowerRelationProjection(arm, alias ?? \"\");\n const claim = field.many\n ? undefined\n : this.#parentClaimsArm(arm.edge, alias ?? \"\");\n // A claimed arm always carries a DOCUMENT: the empty one says\n // \"linked, and the row is gone\", which the decoder refuses from\n // the arm's own selected keys (Arnaud's D-19 — no private carrier\n // column). An unclaimed arm stays null, which is an empty slot.\n return [\n arm.variant,\n a.json.document(\n claim\n ? a.expressions.caseWhen(\n [\n {\n when: claim,\n then: a.expressions.coalesce(\n row,\n this.#missingArm(arm.edge, alias ?? \"\")\n ),\n },\n ],\n a.literals.null()\n )\n : row\n ),\n ] as [string, Sql];\n }),\n ...integrity,\n ]);\n }\n return expression;\n }\n #lowerProjectionField(\n projection: PreparedProjection,\n field: PreparedProjectionField,\n alias?: string,\n visible = false\n ): Sql {\n const a = this.adapter;\n let expression: Sql;\n if (field.kind === \"scalar\") {\n expression = this.projectedColumn(projection.model, field.name, alias);\n } else if (field.kind === \"sentinel\") {\n expression = a.expressions.cast(a.literals.value(1), \"integer\");\n } else if (field.kind === \"evidence\") {\n expression = this.#lowerEvidence(projection.model, field, alias, visible);\n } else if (field.kind === \"gate\") {\n expression = this.#truth(\n this.#gateHolds(projection.model, field.gate, alias, visible)\n );\n } else if (field.kind === \"relation\") {\n expression = this.#duplicateMembershipGuard(\n field.edge,\n alias ?? \"\",\n field.recurrence\n ? this.#lowerRecursiveRelationProjection(\n field,\n field.recurrence,\n alias ?? \"\"\n )\n : this.#lowerRelationProjection(field, alias ?? \"\")\n );\n } else {\n expression = this.#lowerSpecialProjectionField(projection, field, alias);\n }\n return expression;\n }\n /**\n * Where `input`, one of `model`'s predicates in `layer`, holds on the row\n * at `alias`, as that layer's node: R5 and R6 judge it as they judge the\n * layer's filter. `undefined` where the call drops it (it holds).\n */\n #layerHolds(\n model: AnyModel,\n layer: number,\n input: Input,\n alias?: string\n ): Sql | undefined {\n return this.lowerSelector(this.domain!.layered(model, layer, input), alias);\n }\n /** Where a read-gated field's row carries it: every gating layer's `read` and predicate. */\n #gateHolds(\n model: AnyModel,\n gate: FieldGate,\n alias: string | undefined,\n visible: boolean\n ): Sql | undefined {\n const held: Sql[] = [];\n for (const [layer, read, input] of gate) {\n const tested = input === read ? [read] : [read, input];\n for (const where of visible ? tested.slice(1) : tested) {\n const lowered = this.#layerHolds(model, layer, where, alias);\n if (lowered !== undefined) held.push(lowered);\n }\n }\n return held.length === 0 ? undefined : this.adapter.operators.and(...held);\n }\n /** A condition as a value: true or false, never NULL; `undefined` holds. */\n #truth(condition: Sql | undefined): Sql {\n const a = this.adapter;\n return condition === undefined\n ? a.literals.true()\n : a.expressions.caseWhen(\n [{ when: condition, then: a.literals.true() }],\n a.literals.false()\n );\n }\n /**\n * A declared projection key's value on the row at `alias` (K5): the\n * layer's `read` once, around one test per name. Ordered, the last name\n * that holds; else a document of one boolean per name.\n */\n #lowerEvidence(\n model: AnyModel,\n field: Extract<PreparedProjectionField, { kind: \"evidence\" }>,\n alias: string | undefined,\n taken: boolean\n ): Sql {\n const a = this.adapter;\n const { layer, read, ordered } = field.evidence;\n const visible = taken\n ? undefined\n : this.#layerHolds(model, layer, read, alias);\n const test = (input: Input) =>\n input === read ? undefined : this.#layerHolds(model, layer, input, alias);\n if (ordered) {\n const highest = a.expressions.caseWhen(\n [...field.names].reverse().map(([name, input]) => ({\n when: test(input) ?? a.literals.true(),\n then: a.expressions.cast(this.value(name), \"text\"),\n })),\n a.literals.null()\n );\n return visible === undefined\n ? highest\n : a.expressions.caseWhen(\n [{ when: visible, then: highest }],\n a.literals.null()\n );\n }\n const held = a.json.objectFromColumns(\n field.names.map(([name, input]) => [name, this.#truth(test(input))])\n );\n return visible === undefined\n ? held\n : a.expressions.caseWhen(\n [{ when: visible, then: held }],\n a.json.objectFromColumns(\n field.names.map(([name]) => [name, a.literals.false()])\n )\n );\n }\n /**\n * What a claimed arm whose row did not come back carries: the empty\n * document, \"the row is gone\", which the decoder refuses. Under a related\n * domain the row may exist and be hidden, which reads as an empty slot, so\n * the empty document then also needs the row to be physically absent: a\n * membership test with no domain, evaluated only for a claim that read no\n * row. Without a domain, the bytes are the ones a plain client emits.\n */\n #missingArm(edge: Membership, parentAlias: string): Sql {\n const a = this.adapter;\n if (this.domainOf(edge.target, \"related\") === undefined)\n return a.json.object([]);\n const target = this.alias();\n return a.expressions.caseWhen(\n [\n {\n when: a.operators.exists(\n a.subqueries.existsCheck(\n this.table(edge.target, target),\n this.correlation(edge, parentAlias, target, false)\n )\n ),\n then: a.literals.null(),\n },\n ],\n a.json.object([])\n );\n }\n /**\n * How many of this member's memberships name a row that is gone.\n *\n * A polymorphic member table carries no real foreign key to its target on\n * every provider, so a disabled constraint or a raw write can leave the\n * membership behind; reading the slot must then FAIL, not report the row as\n * absent — existence and membership are execution semantics (rule 4), and a\n * silent absence is a wrong answer.\n *\n * The probe is a SIBLING scalar subquery of the arm's row window: it carries\n * no user filter, no cursor and no window, so it is evaluated outside — and\n * therefore ahead of — the arm's own `WHERE` and `LIMIT`, exactly as the\n * shipped `guardJunctionIntegrity` did\n * (`builders/include-many-to-many.ts` at `ff5e77ca`). It is emitted for every\n * configured member, so `only` cannot hide one (Arnaud's D-26).\n */\n /**\n * A SINGULAR polymorphic inverse holding more than one membership is\n * malformed provider state, even where a missing unique constraint allowed\n * it — and the row window cannot say so: a target filter that leaves one\n * visible row, or the `LIMIT 1` itself, hides the second member.\n *\n * So the count is a SIBLING scalar subquery over the member table, ahead of\n * the row subquery's `WHERE` and its `LIMIT`, and the refusal is carried in\n * the VALUE, not raised in SQL — no provider has a portable `RAISE`. The\n * branch emits a JSON ARRAY where the leaf owes one row object, which is the\n * shape the decoder already refuses by name and which no projection of a\n * model row can produce (the shipped `guardJunctionIntegrity`,\n * `builders/include-many-to-many.ts` at `ff5e77ca`).\n *\n * Only a polymorphic member table: an ordinary pair table's inverse is\n * enforced by its own unique constraint and its bytes are unchanged.\n */\n #duplicateMembershipGuard(\n edge: Membership,\n parentAlias: string,\n projected: Sql\n ): Sql {\n if (\n edge.kind !== \"junction\" ||\n edge.many ||\n edge.scope.edge.kind !== \"variantJunctionCarrier\"\n )\n return projected;\n const a = this.adapter;\n const junction = this.alias();\n const members = a.subqueries.scalar(\n assembleAdapterSelect(a, {\n columns: a.aggregates.count(),\n from: a.identifiers.table(edge.table, junction),\n where: a.operators.and(\n ...this.junctionSideConditions(edge.sourceSide, junction, parentAlias)\n ),\n })\n );\n return a.expressions.caseWhen(\n [\n {\n when: a.operators.gt(members, this.value(1)),\n then: a.json.emptyArray(),\n },\n ],\n projected\n );\n }\n #orphanedMemberships(\n edge: Extract<Membership, { kind: \"junction\" }>,\n parentAlias: string\n ): Sql {\n const a = this.adapter;\n const junction = this.alias();\n const target = this.alias();\n return a.subqueries.scalar(\n assembleAdapterSelect(a, {\n columns: a.aggregates.count(),\n from: a.identifiers.table(edge.table, junction),\n where: a.operators.and(\n ...this.junctionSideConditions(\n edge.sourceSide,\n junction,\n parentAlias\n ),\n a.filters.none(\n a.subqueries.existsCheck(\n this.table(edge.target, target),\n a.operators.and(\n ...this.junctionSideConditions(\n edge.targetSide,\n junction,\n target\n )\n )\n )\n )\n ),\n })\n );\n }\n /**\n * One slot's correlated count, shared by the `_count` projection and `_count`\n * ordering. A variant carrier's arms are summed, because the slot's population\n * is their union ({@link countedMemberships}).\n */\n #correlatedCount(\n edges: readonly Membership[],\n selector: Pick<PreparedSelector, \"model\" | \"predicate\"> | undefined,\n parentAlias: string,\n negated = false\n ): Sql {\n const a = this.adapter;\n const counted = edges.map((edge) => {\n const childAlias = this.alias();\n const filter = selector\n ? this.lowerSelector(selector, childAlias)!\n : undefined;\n return a.expressions.coalesce(\n a.subqueries.scalar(\n assembleAdapterSelect(a, {\n columns: a.aggregates.count(),\n from: this.table(edge.target, childAlias),\n where: a.operators.and(\n this.correlation(edge, parentAlias, childAlias),\n ...(filter ? [negated ? a.operators.not(filter) : filter] : [])\n ),\n })\n ),\n this.value(0)\n );\n });\n return counted.reduce((total, arm) => a.expressions.add(total, arm));\n }\n /**\n * One value this unit PRODUCED, published as the field it belongs to.\n *\n * `SELECT <expression> AS <field>` — no FROM, so one row by construction —\n * composed from the owners that already hold the parts: the field's own\n * physical value ({@link fieldValue}, the one destination-aware operand\n * owner) and its own decode leaf ({@link scalarShape}), read back by\n * {@link decodeQuery} like every other row. That is the composition\n * {@link grouped} and {@link junction} already state for every scalar they\n * publish.\n *\n * A user projection was never the question: D-58's segment boundary asks for\n * exactly ONE field, so preparing one to borrow its shape and its lowering\n * was a detour through arms — relation, variant, `_count`, `_distance`,\n * sentinel — that a produced scalar cannot reach, and it ended in a cast back\n * to the scalar arm the caller already knew it had.\n */\n scalarQuery(model: AnyModel, field: string, value: unknown): Query {\n return {\n shape: {\n kind: \"object\",\n fields: { [field]: this.scalarShape(model, field) },\n },\n sql: this.adapter.clauses.select(\n this.adapter.identifiers.aliased(\n this.fieldValue(model, field, value),\n field\n )\n ),\n };\n }\n #lowerRelationProjection(\n relation: PreparedRelationProjection,\n alias: string\n ): Sql {\n const a = this.adapter;\n const { edge, arguments: nested, projection } = relation;\n const childAlias = this.alias();\n const child = this.lowerProjection(projection, childAlias, true);\n const childFields = Object.keys(projection.shape.fields);\n // A nested node is the ordinary page operator inside the parent's\n // correlation scope; `take: -n` reverses the window exactly as at the root.\n const window = this.#page(edge.target, nested, childAlias, \"related\");\n const source = this.#memberSource(edge, alias, childAlias);\n const page = assembleAdapterSelect(a, {\n columns: sql.join(child, \", \"),\n from: source.from,\n joins: source.joins,\n where: a.operators.and(\n source.where,\n ...(nested.selector\n ? [this.lowerSelector(nested.selector, childAlias)!]\n : []),\n ...(window.cursor ? [window.cursor] : [])\n ),\n orderBy: window.orderBy,\n // The aggregate below reads this page IN ORDER, so an ordered page\n // states its bound. MySQL merges an UNLIMITED derived table into the\n // query that reads it and the merge takes the ORDER BY with it, and the\n // rows then arrive in storage order — measured, both answers from the\n // same aggregate over the same page. What the bound buys is the MERGE\n // RULE, which is the documented fact: MySQL does not merge a derived\n // table that states a LIMIT. That the same page then answered in the\n // requested order is the measurement beside it, not a documented\n // property of materialising. The caller's window is that bound wherever\n // it asked for one — including the offset-only window, whose bare\n // OFFSET already needs the same spelling — and where it asked for none,\n // the dialect's own \"no limit\" value is. A dialect that needs no bound\n // to keep a derived order declares none (PostgreSQL) and emits nothing.\n limit: edge.many\n ? (window.limit ?? (window.orderBy ? a.noLimitValue : undefined))\n : this.value(1),\n offset: window.offset,\n ...(window.distinct\n ? {\n distinct: window.distinct,\n distinctOrderBy: window.distinctOrderBy,\n distinctColumnAliases: projection.fields.map((field) => field.name),\n }\n : {}),\n });\n const pageAlias = this.alias();\n const members = childFields.map((field): [string, Sql] => [\n field,\n this.#carriedValue(\n projection.shape.fields[field]!,\n a.identifiers.column(pageAlias, field)\n ),\n ]);\n for (const gate of projection.shape.gates ?? NO_GATES)\n members.push([gate, a.identifiers.column(pageAlias, gate)]);\n const object = a.json.object(members);\n const expression = a.subqueries.scalar(\n assembleAdapterSelect(a, {\n columns: edge.many\n ? a.expressions.coalesce(a.json.agg(object), a.json.emptyArray())\n : object,\n from: a.subqueries.correlate(page, pageAlias),\n })\n );\n return expression;\n }\n\n /**\n * One physical row identity, encoded through the existing JSON carrier rule:\n * the one encoder of the carrier's root, node keys and edge endpoints, whose\n * texts the decoder matches.\n */\n #recursiveIdentity(model: AnyModel, key: readonly Sql[]): Sql {\n return this.adapter.json.array(\n this.schema.keys(model).map((field, index) => {\n // The carried key is the RAW column, so a byte identifier takes its\n // transport spelling here, as every projected column already has.\n const leaf = this.scalarShape(model, field);\n return this.#carriedValue(\n leaf,\n transportedIdentifier(\n this.adapter,\n leaf.id,\n key[index]!,\n leaf.nullable\n )\n );\n })\n );\n }\n\n /** One row's complete key, addressed through `alias`. */\n #rowKey(model: AnyModel, alias: string): Sql[] {\n return this.schema\n .keys(model)\n .map((field) => this.column(model, field, alias));\n }\n /** The complete-key join of one model alias to carried key columns. */\n #sameRow(model: AnyModel, alias: string, carried: readonly Sql[]): Sql {\n const a = this.adapter;\n return a.operators.and(\n ...this.#rowKey(model, alias).map((column, index) =>\n a.operators.eq(column, carried[index]!)\n )\n );\n }\n\n /**\n * One hop of a walk, from `current` into `next`, under the {@link related}\n * domain. A reference hop is the ordinary {@link correlation}; a junction\n * hop joins the junction table, and its target as a relation page does\n * ({@link memberSource}): the membership's `IN (SELECT … WHERE link.source =\n * current.key)` correlates to `next`'s sibling, which PostgreSQL cannot turn\n * into a semi-join, so it would run once per target row at every hop.\n */\n #step(edge: Membership, current: string, next: string, scoped = true): Sql {\n const a = this.adapter;\n if (edge.kind !== \"junction\")\n return a.joins.inner(\n this.table(edge.target, next),\n this.correlation(edge, current, next, scoped)\n );\n const link = this.alias();\n return sql`${a.joins.inner(\n a.identifiers.table(edge.table, link),\n a.operators.and(\n ...this.junctionSideConditions(edge.sourceSide, link, current)\n )\n )} ${this.#junctionTarget(edge, link, next)}`;\n }\n /**\n * Where one parent's relation page reads its rows. A junction membership\n * reads FROM the junction, joined to its target by key, so the junction's\n * source-side index drives the page whatever the target's statistics say:\n * behind {@link correlation}'s `IN (SELECT …)` SQLite, once ANALYZE has\n * run, scans a target smaller than its fixed guess of the list's length,\n * once per parent (parity-04). PostgreSQL and MySQL already plan that\n * membership as this join. The junction's primary key spans both sides\n * and each side references a complete row key, so every member is read\n * once, as the membership reads it.\n */\n #memberSource(\n edge: Membership,\n parent: string,\n child: string\n ): { from: Sql; joins?: Sql[]; where: Sql } {\n if (edge.kind !== \"junction\")\n return {\n from: this.table(edge.target, child),\n where: this.correlation(edge, parent, child),\n };\n const link = this.alias();\n return {\n from: this.adapter.identifiers.table(edge.table, link),\n joins: [this.#junctionTarget(edge, link, child)],\n where: this.adapter.operators.and(\n ...this.junctionSideConditions(edge.sourceSide, link, parent)\n ),\n };\n }\n /** A junction's target joined from `link`, under the {@link related} domain. */\n #junctionTarget(\n edge: Extract<Membership, { kind: \"junction\" }>,\n link: string,\n next: string\n ): Sql {\n const a = this.adapter;\n return a.joins.inner(\n this.table(edge.target, next),\n this.#related(\n edge,\n next,\n a.operators.and(\n ...this.junctionSideConditions(edge.targetSide, link, next)\n )\n )\n );\n }\n\n /**\n * The ONE walk of a recursive membership: a recursive CTE of the rows\n * reached from `parentAlias` by 1..`depth` hops of `edge` (every hop when\n * `depth` is false). Each hop reads the related domain (the anchor's\n * {@link correlation}, then {@link step}), so a hidden row stops the walk\n * below it, and `UNION` on\n * the carried key (and depth, when bounded) ends every cycle and visits a\n * diamond's row once per depth. Two readers:\n * - the recursive projection asks for `edges`: each reached row carries the\n * row it was reached from, and the per-hop `selector` narrows every hop;\n * - a recursive filter reads the reached SET, plus the start row itself at\n * depth 0 when `self` holds. The start row joins the FIRST hop in the\n * anchor, so the recursive member stays the projection's and needs no\n * depth guard: a start-only anchor would spend one of MySQL's\n * `cte_max_recursion_depth` iterations and fail `{ depth: 1000 }`.\n * The two are ONE derived-table term, so the CTE keeps exactly two\n * top-level terms: PlanetScale's Neki cannot resolve the CTE from the\n * recursive member of a third (42P01).\n */\n #walk(\n edge: Membership,\n parentAlias: string,\n start:\n | Closure\n | {\n readonly depth: number | false;\n readonly edges: true;\n readonly selector?: Pick<PreparedSelector, \"model\" | \"predicate\">;\n },\n scoped = true\n ) {\n const a = this.adapter;\n const model = edge.target;\n const keys = this.schema.keys(model);\n const scope = this.alias();\n const cteName = `__${scope}_recursive`;\n const { depth } = start;\n const edges = \"edges\" in start;\n const parentColumns = edges\n ? keys.map((_, index) => `__${scope}_parent_${index}`)\n : [];\n const childColumns = keys.map((_, index) => `__${scope}_child_${index}`);\n const depthColumn = `__${scope}_depth`;\n const selector = edges ? start.selector : undefined;\n const hop = (value: Sql) =>\n depth === false ? [] : [a.identifiers.aliased(value, depthColumn)];\n const reached = (alias: string) =>\n selector ? [this.lowerSelector(selector, alias)!] : [];\n\n const anchorChild = this.alias();\n const firstHop = assembleAdapterSelect(a, {\n columns: sql.join(\n [\n ...this.#aliased(parentColumns, this.#rowKey(model, parentAlias)),\n ...this.#aliased(childColumns, this.#rowKey(model, anchorChild)),\n ...hop(a.expressions.cast(this.value(1), \"integer\")),\n ],\n \", \"\n ),\n from: this.table(model, anchorChild),\n where: a.operators.and(\n this.correlation(edge, parentAlias, anchorChild, scoped),\n ...reached(anchorChild)\n ),\n });\n const seed = !edges && start.self ? this.alias() : undefined;\n const anchor = seed\n ? assembleAdapterSelect(a, {\n columns: sql.join(\n [...childColumns, ...(depth === false ? [] : [depthColumn])].map(\n (column) => a.identifiers.column(seed, column)\n ),\n \", \"\n ),\n from: a.subqueries.correlate(\n a.setOperations.union(\n a.clauses.select(\n sql.join(\n [\n ...this.#aliased(\n childColumns,\n this.#rowKey(model, parentAlias)\n ),\n ...hop(a.expressions.cast(this.value(0), \"integer\")),\n ],\n \", \"\n )\n ),\n firstHop\n ),\n seed\n ),\n })\n : firstHop;\n\n const walk = this.alias();\n const current = this.alias();\n const next = this.alias();\n const carried = (column: string) => a.identifiers.column(walk, column);\n const recursive = assembleAdapterSelect(a, {\n columns: sql.join(\n [\n ...this.#aliased(parentColumns, childColumns.map(carried)),\n ...this.#aliased(childColumns, this.#rowKey(model, next)),\n ...hop(a.expressions.add(carried(depthColumn), this.value(1))),\n ],\n \", \"\n ),\n from: sql`${a.identifiers.aliased(a.identifiers.escape(cteName), walk)} ${a.joins.inner(\n this.table(model, current),\n this.#sameRow(model, current, childColumns.map(carried))\n )} ${this.#step(edge, current, next, scoped)}`,\n where: a.operators.and(\n ...(depth === false\n ? []\n : [a.operators.lt(carried(depthColumn), this.value(depth))]),\n ...reached(next)\n ),\n });\n return {\n cte: a.cte.recursive(cteName, anchor, recursive, \"distinct\"),\n cteName,\n scope,\n /** The walk's own alias, free again for a reader outside the CTE. */\n walk,\n parentColumns,\n childColumns,\n depthColumn,\n };\n }\n /** Each expression aliased as the column of the same index. */\n #aliased(names: readonly string[], expressions: readonly Sql[]): Sql[] {\n return names.map((name, index) =>\n this.adapter.identifiers.aliased(expressions[index]!, name)\n );\n }\n\n /**\n * A recursive relation remains one ordinary projected field. The recursive\n * CTE carries only edge facts; one node table supplies each projected row,\n * and the decoder owns path occurrences and cutoff omission. The recursive\n * member expands every reached row below the bound with the same\n * correlation and filter and prunes nothing (the cycle policy belongs to the\n * decoder), because `decodeRecursiveCarrier` refuses a carrier in which a\n * parent lacks its children at any level it is reached below the cutoff.\n */\n #lowerRecursiveRelationProjection(\n relation: PreparedRelationProjection,\n recurrence: NormalizedRecurrence,\n parentAlias: string\n ): Sql {\n const a = this.adapter;\n const model = relation.edge.target;\n const {\n cte,\n cteName,\n scope,\n walk,\n parentColumns,\n childColumns,\n depthColumn,\n } = this.#walk(relation.edge, parentAlias, {\n depth: recurrence.depth,\n edges: true,\n selector: relation.arguments.selector,\n });\n const walkColumn = (name: string) => a.identifiers.column(walk, name);\n\n const ids = this.alias();\n const idColumns = childColumns.map((_, index) => `__${scope}_id_${index}`);\n const distinctIds = assembleAdapterSelect(a, {\n distinct: sql.join(childColumns.map(walkColumn), \", \"),\n distinctColumnAliases: idColumns,\n columns: sql.join(\n this.#aliased(idColumns, childColumns.map(walkColumn)),\n \", \"\n ),\n from: a.identifiers.aliased(a.identifiers.escape(cteName), walk),\n });\n const node = this.alias();\n const nodeDocument = a.json.object(\n relation.projection.fields.map((field) => [\n field.name,\n this.#carriedValue(\n // A gate is the one member the decoded shape does not list.\n relation.projection.shape.fields[field.name] ?? BOOLEAN_LEAF,\n this.#lowerProjectionField(relation.projection, field, node, true)\n ),\n ])\n );\n const nodeCarrier = a.json.object([\n [\n RECURSIVE_CARRIER.key,\n this.#recursiveIdentity(model, this.#rowKey(model, node)),\n ],\n [RECURSIVE_CARRIER.row, nodeDocument],\n ]);\n const nodes = a.subqueries.scalar(\n assembleAdapterSelect(a, {\n columns: a.json.agg(nodeCarrier),\n from: sql`${a.subqueries.correlate(distinctIds, ids)} ${a.joins.inner(\n this.table(model, node),\n this.#sameRow(\n model,\n node,\n idColumns.map((name) => a.identifiers.column(ids, name))\n )\n )}`,\n })\n );\n\n const edgeWalk = this.alias();\n const edgeChild = this.alias();\n const edgeColumn = (name: string) => a.identifiers.column(edgeWalk, name);\n const edgeCarrierName = `__${scope}_edge`;\n const edgePairs: [string, Sql][] = [\n [\n RECURSIVE_CARRIER.parent,\n this.#recursiveIdentity(model, parentColumns.map(edgeColumn)),\n ],\n [\n RECURSIVE_CARRIER.child,\n this.#recursiveIdentity(model, childColumns.map(edgeColumn)),\n ],\n ];\n if (recurrence.depth !== false)\n edgePairs.push([RECURSIVE_CARRIER.depth, edgeColumn(depthColumn)]);\n const edgeCarrier = a.json.object(edgePairs);\n // Each parent's siblings in the caller's order, ties broken by the order\n // owner's one complete key — the ordinary window's tie-break, not another.\n const siblingOrder = this.#lowerOrder(\n this.#completeOrder(\n model,\n this.#orderTerms(model, relation.arguments.orderBy, edgeChild),\n edgeChild\n )\n );\n const edgePage = assembleAdapterSelect(a, {\n columns: a.identifiers.aliased(edgeCarrier, edgeCarrierName),\n from: sql`${a.identifiers.aliased(\n a.identifiers.escape(cteName),\n edgeWalk\n )} ${a.joins.inner(\n this.table(model, edgeChild),\n this.#sameRow(model, edgeChild, childColumns.map(edgeColumn))\n )}`,\n orderBy: sql.join(\n [\n ...parentColumns.map((name) => a.orderBy.asc(edgeColumn(name))),\n ...(siblingOrder ? [siblingOrder] : []),\n ],\n \", \"\n ),\n // MySQL otherwise merges the derived page into the aggregate reader and\n // drops its ORDER BY. The adapter's unbounded LIMIT prevents that merge.\n limit: a.noLimitValue,\n });\n const edgePageAlias = this.alias();\n const edges = a.subqueries.scalar(\n assembleAdapterSelect(a, {\n columns: a.json.agg(\n a.json.document(a.identifiers.column(edgePageAlias, edgeCarrierName))\n ),\n from: a.subqueries.correlate(edgePage, edgePageAlias),\n })\n );\n\n const carrier = (nodeFacts: Sql, edgeFacts: Sql) =>\n a.json.object([\n [\n RECURSIVE_CARRIER.root,\n this.#recursiveIdentity(model, this.#rowKey(model, parentAlias)),\n ],\n [RECURSIVE_CARRIER.nodes, a.json.document(nodeFacts)],\n [RECURSIVE_CARRIER.edges, a.json.document(edgeFacts)],\n ]);\n if (!a.capabilities.supportsLateralJoins)\n return a.subqueries.scalar(\n sql`${cte} ${a.clauses.select(carrier(nodes, edges))}`\n );\n // MySQL materializes a correlated recursive CTE that is read twice (the\n // nodes and the edges) once for the whole statement and hands every outer\n // row the first row's facts. A lateral derived table is re-evaluated per\n // outer row by definition, so the CTE and both readers live inside one\n // wherever the provider spells LATERAL (PostgreSQL, MySQL); SQLite, which\n // has no LATERAL, evaluates the correlated CTE per row as written above.\n const one = this.alias();\n const facts = this.alias();\n const nodeFacts = `__${scope}_nodes`;\n const edgeFacts = `__${scope}_edges`;\n return a.subqueries.scalar(\n assembleAdapterSelect(a, {\n columns: carrier(\n a.identifiers.column(facts, nodeFacts),\n a.identifiers.column(facts, edgeFacts)\n ),\n from: a.subqueries.correlate(a.clauses.select(sql`1`), one),\n joins: [\n a.joins.lateral(\n sql`${cte} ${a.clauses.select(\n sql.join(\n [\n a.identifiers.aliased(nodes, nodeFacts),\n a.identifiers.aliased(edges, edgeFacts),\n ],\n \", \"\n )\n )}`,\n facts\n ),\n ],\n })\n );\n }\n grouped(model: AnyModel, args: Arguments): Query {\n const a = this.adapter;\n const alias = this.#rootAlias();\n // The ONE `by` authority. Admission normalises `by` to an array and\n // refuses its duplicates; the grouped read computes the grouped column SET\n // once and hands it to the two owners that have to know it — `having` and\n // the grouped `orderBy` — instead of each re-reading `args`.\n const by = args.by!;\n const grouped: ReadonlySet<string> = new Set(by);\n // A read-gated model groups a masked window of its filtered rows (K5): a\n // gate lowered once per row, where a gate repeated in the grouping, the\n // projection and the order would be three expressions to the provider.\n if (this.#masks(model)) {\n const inner = this.alias();\n const window = assembleAdapterSelect(a, {\n columns: sql.join(\n this.schema\n .storedFields(model)\n .map((field) =>\n a.identifiers.aliased(\n this.#operand(model, field, inner),\n this.columnName(model, field)\n )\n ),\n \", \"\n ),\n from: this.table(model, inner),\n where: this.lowerWhere(model, args.where, inner),\n });\n return this.#overMasked(() =>\n this.#grouped(model, args, alias, by, grouped, {\n from: a.subqueries.correlate(window, alias),\n })\n );\n }\n return this.#grouped(model, args, alias, by, grouped, {\n from: this.table(model, alias),\n where: this.lowerWhere(model, args.where, alias),\n });\n }\n #grouped(\n model: AnyModel,\n args: Arguments,\n alias: string,\n by: readonly string[],\n grouped: ReadonlySet<string>,\n rows: { readonly from: Sql; readonly where?: Sql }\n ): Query {\n const a = this.adapter;\n const aggregates = this.#prepareAggregates(model, args);\n const fields: Record<string, Shape | Leaf> = {};\n const gates = this.#masked\n ? this.domain?.projected(model)?.gates\n : undefined;\n const columns: Sql[] = by.map((field) => {\n const leaf = this.scalarShape(model, field);\n // A masked group reads a gated key as absent: the NULL group.\n fields[field] = gates?.has(field)\n ? freeze({ ...leaf, nullable: true })\n : leaf;\n return a.identifiers.aliased(\n this.projectedColumn(model, field, alias),\n field\n );\n });\n for (const [name, expression] of aggregates.columns(alias)) {\n fields[name] = aggregates.fields_[name]!;\n columns.push(a.identifiers.aliased(expression, name));\n }\n return {\n sql: assembleAdapterSelect(a, {\n columns: sql.join(columns, \", \"),\n from: rows.from,\n where: rows.where,\n groupBy: sql.join(\n by.map((field) => this.column(model, field, alias)),\n \", \"\n ),\n having: args.having\n ? this.#lowerPredicate(\n this.#prepareHaving(model, record(args.having)),\n alias\n )\n : undefined,\n orderBy: this.#lowerOrder(\n this.#groupOrderTerms(model, args.orderBy, alias, grouped)\n ),\n limit: args.take === undefined ? undefined : this.value(args.take),\n offset: args.skip === undefined ? undefined : this.value(args.skip),\n }),\n shape: { kind: \"object\", fields },\n };\n }\n /** `having` is the same predicate vocabulary over aggregate targets. */\n #prepareHaving(model: AnyModel, having: Input): PreparedPredicate {\n return freeze({\n kind: \"and\",\n predicates: freeze(\n Object.entries(having).flatMap(([key, value]) => {\n if (value === undefined) return [];\n // Prisma negates each NOT arm and conjoins the negations.\n if (this.combinator(model, key))\n return [\n this.combine(\n key,\n entries(value).map((clause) =>\n this.#prepareHaving(model, record(clause))\n )\n ),\n ];\n const scalar = this.#scalar(model, key);\n const filter = record(value);\n const aggregated = AGGREGATES.filter(\n (name) => filter[name] !== undefined\n );\n // A field-keyed condition names a grouped column: admission refuses\n // one outside `by` at its path (`args/aggregate.ts`).\n if (aggregated.length === 0)\n return [\n this.#prepareOperations(\n freeze({ kind: \"column\", scalar }),\n value\n ),\n ];\n return aggregated.map((aggregate) =>\n this.#prepareOperations(\n freeze({ kind: \"aggregate\", aggregate, scalar }),\n filter[aggregate]\n )\n );\n })\n ),\n });\n }\n /**\n * A grouped read orders by a grouped field or by an aggregate; admission\n * refuses any other field at its `orderBy` path (`args/aggregate.ts`).\n */\n #groupOrderTerms(\n model: AnyModel,\n input: Arguments[\"orderBy\"],\n alias: string,\n grouped: ReadonlySet<string>\n ): OrderTerm[] {\n const terms = entries(input ?? {}).flatMap((order) =>\n Object.entries(order).flatMap(([name, direction]) => {\n if (direction === undefined) return [];\n if (!isAggregate(name))\n return [this.#orderTerm(model, name, direction, alias)];\n return Object.entries(record(direction)).flatMap(([field, sort]) => {\n const scalar =\n field === \"_all\" ? undefined : this.#scalar(model, field);\n const split =\n name === \"_sum\" &&\n this.#splitSumSql(scalar!, this.#preparedColumn(scalar!, alias));\n return (\n split\n ? split.order\n : [this.#aggregateExpression(name, scalar, alias)]\n ).map((key) => this.#sortKey(key, sort === \"desc\", undefined, false));\n });\n })\n );\n const ordered = new Set(terms.map((term) => term.field));\n for (const field of grouped)\n if (!ordered.has(field))\n terms.push(this.#orderTerm(model, field, \"asc\", alias));\n return terms;\n }\n /**\n * ONE statement's row-count contract, on the rows that statement answered.\n *\n * It is the one fact a terminal WINDOW owns rather than the operation:\n * {@link Queries.selectSeries} stamps every bind-budget window with its own\n * identity count and its own registered refusal, so a terminal split into\n * windows is decided here, per window, while the window is still known. A\n * total taken over the concatenation would compare a whole terminal with one\n * window's count and could not raise that window's refusal at all\n * (`OperationContext.publishedTerminal`, Arnaud's D-28).\n */\n assertExpectedRows(query: Query, rows: number): void {\n if (query.expectedRows && rows < query.expectedRows.count)\n throw query.expectedRows.missing;\n if (query.expectedRows && rows > query.expectedRows.count)\n throw new QueryEngineError(\n \"createMany returned a different number of rows than expected.\"\n );\n }\n decodeQuery(query: Query, rows: Input[], internal = false): Input[] {\n this.assertExpectedRows(query, rows.length);\n return this.decodeProjection(query.shape, rows, internal);\n }\n decodeProjection(\n shape: ProjectionShape,\n rows: Input[] | unknown[][],\n internal = false,\n columns?: readonly string[]\n ): Input[] {\n // An empty batch — a filter that matched nothing — reads nothing, so it\n // compiles nothing.\n if (rows.length === 0) return [];\n const read = this.compileReader(shape, internal, false, columns);\n return rows.map((row) => record(read(row)));\n }\n private decodeRecursiveCarrier(\n shape: Extract<Shape, { kind: \"recursive\" }>,\n value: unknown,\n readRow: Reader,\n readIdentity: readonly Reader[]\n ): unknown {\n const carrier = providerDocument(providerJson(value));\n if (!carrier)\n throw new InvalidScalarResult(\n \"recursive carrier\",\n \"the carrier is not an object\"\n );\n const root = own(carrier, RECURSIVE_CARRIER.root);\n const rawNodes = own(carrier, RECURSIVE_CARRIER.nodes);\n const rawEdges = own(carrier, RECURSIVE_CARRIER.edges);\n if (\n !(\n Array.isArray(root) &&\n Array.isArray(rawNodes) &&\n Array.isArray(rawEdges)\n )\n )\n throw new InvalidScalarResult(\n \"recursive carrier\",\n \"the carrier's root, nodes or edges member is not an array\"\n );\n\n const identity = (tuple: unknown): string => {\n if (!Array.isArray(tuple) || tuple.length !== shape.identity.length)\n throw new InvalidScalarResult(\n \"recursive identity\",\n \"an identity is not a tuple of the key's width\"\n );\n // A counted walk: `entries()` allocated an iterator and a pair per\n // member on every identity — root, node key and both edge endpoints.\n let index = 0;\n for (const read of readIdentity) {\n read(tuple[index]);\n index += 1;\n }\n return JSON.stringify(tuple);\n };\n const rootKey = identity(root);\n const nodes = new Map<string, unknown>();\n for (const rawNode of rawNodes) {\n const node = providerDocument(rawNode);\n if (!node)\n throw new InvalidScalarResult(\n \"recursive node\",\n \"a node entry is not an object\"\n );\n const key = identity(own(node, RECURSIVE_CARRIER.key));\n if (nodes.has(key))\n throw new InvalidScalarResult(\n \"duplicate recursive node\",\n \"two nodes carry the same identity\"\n );\n nodes.set(key, own(node, RECURSIVE_CARRIER.row));\n }\n\n type Edge = { readonly child: string; readonly depth?: number };\n const edges = new Map<string, Edge[]>();\n const facts = new Set<string>();\n for (const rawEdge of rawEdges) {\n const edge = providerDocument(rawEdge);\n if (!edge)\n throw new InvalidScalarResult(\n \"recursive edge\",\n \"an edge entry is not an object\"\n );\n const parent = identity(own(edge, RECURSIVE_CARRIER.parent));\n const child = identity(own(edge, RECURSIVE_CARRIER.child));\n if (!nodes.has(child))\n throw new InvalidScalarResult(\n \"recursive edge endpoint\",\n \"an edge's child is not a carried node\"\n );\n const rawDepth = own(edge, RECURSIVE_CARRIER.depth);\n let depth: number | undefined;\n if (shape.recurrence.depth === false) {\n if (rawDepth !== undefined)\n throw new InvalidScalarResult(\n \"exhaustive recursive depth\",\n \"an exhaustive carrier states an edge depth\"\n );\n } else {\n if (\n typeof rawDepth !== \"number\" ||\n !Number.isSafeInteger(rawDepth) ||\n rawDepth < 1 ||\n rawDepth > shape.recurrence.depth\n )\n throw new InvalidScalarResult(\n \"recursive depth\",\n \"an edge depth is not an integer from 1 to the cutoff\"\n );\n depth = rawDepth;\n }\n const fact = JSON.stringify([parent, child, depth ?? null]);\n if (facts.has(fact))\n throw new InvalidScalarResult(\n \"duplicate recursive edge\",\n \"an edge fact is carried twice\"\n );\n facts.add(fact);\n const siblings = edges.get(parent);\n const entry = freeze({\n child,\n ...(depth === undefined ? {} : { depth }),\n });\n if (siblings) siblings.push(entry);\n else edges.set(parent, [entry]);\n }\n\n /**\n * One parent, one answer, taken once over the COMPLETE edge index: the\n * distinct successors it offers, in transported sibling order. Their count\n * is also where singular cardinality is answerable at all, so the parent's\n * endpoint, its cardinality and its successors are decided here — over\n * every transported fact — instead of being rediscovered at each\n * occurrence that happens to unfold this parent.\n */\n const successors = new Map<string, readonly string[]>();\n for (const [parent, entries] of edges) {\n if (parent !== rootKey && !nodes.has(parent))\n throw new InvalidScalarResult(\n \"recursive edge endpoint\",\n \"an edge's parent is neither the root nor a carried node\"\n );\n const unique = [...new Set(entries.map((entry) => entry.child))];\n if (!shape.many && unique.length > 1)\n throw new InvalidScalarResult(\n \"recursive singular relation\",\n \"a singular parent has several successors\"\n );\n successors.set(parent, unique);\n }\n /**\n * ONE walk over the transported facts, before any of them is unfolded.\n *\n * The root is reached at level 0, and a bounded edge is reachable only one\n * level below its own recorded `__rq_depth` — the only meaning that number\n * has, and the reason the provider transports it. An identity reached by\n * several distinct paths keeps EVERY level it was reached at, so a diamond\n * and a re-entered junction node stay legal; an exhaustive carrier records\n * no level, collapses to the identity alone, and so still terminates on a\n * legal cyclic graph.\n *\n * Three facts fall out of that one walk. A BOUNDED edge no level can\n * consume is a depth attributed to a hop it was not discovered at. A\n * bounded hop below the cutoff whose children at the next level are not\n * the parent's one answer is a hop the provider did not discover: the\n * statement discovers a parent's children at EVERY level it reaches that\n * parent (a filter prunes each hop the same way, and prevention is this\n * decoder's, not the statement's), so unfolding the one answer there would\n * invent an occurrence the carrier never transported. An identity no\n * consumed edge reaches is a node outside this answer. Only a stated depth\n * can be misattributed or missing, so only a bounded carrier is asked the\n * first two questions: on an exhaustive one an unconsumed edge means its\n * parent was never reached, which is the third question's answer.\n */\n const consumed = new Set<Edge>();\n const reached = new Set<string>();\n const levels = new Set<string>();\n const pending: (readonly [string, number])[] = [[rootKey, 0]];\n // `for…of` re-reads the length each step, so the levels pushed below are\n // walked too, exactly as the indexed loop did.\n for (const [parent, level] of pending) {\n const children = new Set<string>();\n for (const entry of edges.get(parent) ?? []) {\n if (entry.depth !== undefined && entry.depth !== level + 1) continue;\n consumed.add(entry);\n reached.add(entry.child);\n children.add(entry.child);\n const at =\n entry.depth === undefined\n ? entry.child\n : `${entry.depth} ${entry.child}`;\n if (levels.has(at)) continue;\n levels.add(at);\n pending.push([entry.child, level + 1]);\n }\n if (\n shape.recurrence.depth !== false &&\n carriesRepeatedKey(shape.recurrence.depth, level) &&\n children.size !== (successors.get(parent)?.length ?? 0)\n )\n throw new InvalidScalarResult(\n \"recursive depth\",\n \"a hop below the cutoff omits some of its parent's children\"\n );\n }\n if (shape.recurrence.depth !== false && consumed.size !== facts.size)\n throw new InvalidScalarResult(\n \"recursive depth\",\n \"an edge is not reachable at its recorded depth\"\n );\n if (reached.size !== nodes.size)\n throw new InvalidScalarResult(\n \"unreachable recursive node\",\n \"a carried node is not reachable from the root\"\n );\n\n /** A numeric cutoff reached: this occurrence omits the repeated slot. */\n const cutoff = (depth: number) =>\n !carriesRepeatedKey(shape.recurrence.depth, depth);\n /** One slot's successors, collapsed by its cardinality and emptiness. */\n // A singular slot here may be empty: CM002 refuses a required self\n // foreign key.\n const collapse = (rows: Input[]): unknown => {\n if (rows.length > 0) return shape.many ? rows : rows[0]!;\n return shape.many ? [] : null;\n };\n type Frame = {\n readonly key: string;\n readonly depth: number;\n readonly row: Input;\n readonly childKeys: readonly string[];\n readonly childRows: Input[];\n next: number;\n };\n /**\n * ONE active path, seeded by the outer row and kept by enter and leave.\n *\n * Copying the ancestry prefix into every descended occurrence held those\n * identities once per hop and made a chain quadratic in its own depth;\n * the stack already holds them.\n */\n const active = new Set<string>([rootKey]);\n const stack: Frame[] = [];\n /**\n * The one admission EVERY followed edge passes, the first hop included —\n * which is what seeding the path with the root makes possible: a graph\n * edge straight back to the outer row is a revisit like any other, and an\n * FK one is the same refusal at the first hop as at the hundredth.\n */\n let occurrences = 0;\n const budget = shape.recurrence.maxOccurrences ?? DEFAULT_MAX_OCCURRENCES;\n const follow = (from: number, key: string): void => {\n if (active.has(key)) {\n if (shape.recurrence.cycles === \"reject\")\n throw new UnsupportedOperationError(\n `Recursive relation '${shape.relation}' contains a cycle.`,\n {\n meta: {\n relation: shape.relation,\n feature: \"cyclic recursive traversal\",\n },\n }\n );\n if (shape.recurrence.cycles === \"prevent\") return;\n }\n if (++occurrences > budget)\n throw new RecursiveOutputOverBudget(shape.relation, budget);\n active.add(key);\n const decoded = readRow(nodes.get(key));\n if (decoded === null)\n throw new InvalidScalarResult(\"recursive row\", \"a node's row is null\");\n const depth = from + 1;\n stack.push({\n key,\n depth,\n row: record(decoded),\n childKeys: cutoff(depth) ? [] : (successors.get(key) ?? []),\n childRows: [],\n next: 0,\n });\n };\n const rootRows: Input[] = [];\n for (const child of successors.get(rootKey) ?? []) {\n follow(0, child);\n for (\n let current = stack.at(-1);\n current !== undefined;\n current = stack.at(-1)\n ) {\n if (current.next < current.childKeys.length) {\n follow(current.depth, current.childKeys[current.next++]!);\n continue;\n }\n active.delete(current.key);\n stack.pop();\n if (!cutoff(current.depth))\n current.row[shape.relation] = collapse(current.childRows);\n const parent = stack.at(-1);\n if (parent) parent.childRows.push(current.row);\n else rootRows.push(current.row);\n }\n }\n return collapse(rootRows);\n }\n /**\n * The ONE decoder of the projection language, compiled for one decoded\n * batch — a result window, a RETURNING answer, an internal read — and\n * dropped with it. Every invariant decision of a placement is taken here,\n * once: an object's member list and each member's placement, a variant\n * slot's arms, a collection's and a recursive carrier's row reader, a list\n * leaf's container reader ({@link compileList}), and — for a PHYSICAL\n * scalar slot only — this execution's provider continuation\n * ({@link fieldReader}). The returned reader then does only what depends on\n * the provider's value, through the preselected scalar codec\n * ({@link compileScalar}) and the one carrier validator\n * ({@link decodeRecursiveCarrier}).\n *\n * `carried` is a fact of the PLACEMENT, never of the shape: a to-one\n * relation's shape is its target's shared default projection, read as the\n * root row of one statement and inside a JSON document of another. Only a\n * scalar member of a physical row crosses the provider chain; a JSON window\n * already decoded everything under it.\n *\n * The reader holds a driver's parser, so it lives no longer than the batch\n * it was compiled for and is never stored on the prepared shape, which\n * `EngineSchema` shares across executions and driver bindings.\n */\n private compileReader(\n shape: Shape | Leaf,\n internal: boolean,\n carried: boolean,\n columns?: readonly string[]\n ): Reader {\n if (shape.kind === \"scalar\") {\n const provider = carried ? undefined : this.fieldReader(shape.type);\n const list = shape.list ? this.compileList(shape, internal) : undefined;\n return this.compileScalar(shape, internal, provider, list);\n }\n if (shape.kind === \"recursive\") {\n const readRow = this.compileReader(shape.row, internal, true);\n // An identity is validated as the stored key it is (an INTERNAL read),\n // never published.\n const readIdentity = shape.identity.map((leaf) =>\n this.compileReader(leaf, true, true)\n );\n return (value) =>\n this.decodeRecursiveCarrier(shape, value, readRow, readIdentity);\n }\n if (shape.kind === \"variants\") {\n const slot = (value: unknown): Input => {\n // The slot is a provider document the statement always builds, read\n // by the one document rule: a NULL or non-object slot is a malformed\n // result, refused at the slot before any arm is asked (Arnaud,\n // 2026-09-25).\n const variants = providerDocument(providerJson(value));\n if (!variants)\n throw new InvalidScalarResult(\n \"polymorphic slot\",\n \"the slot is not an object\"\n );\n // The integrity probe first, and before any arm: a membership whose\n // row is gone is a fact about the SLOT, so `only` — which selects what\n // is read — cannot make it unobservable (Arnaud's D-26). One refusal,\n // from the decoder arm that already owns the sentence. Its entry is a\n // document of the slot, read by the same rule: a slot with no\n // junction membership carries none, and a PRESENT entry that is no\n // document is the slot's malformed result — never \"no memberships\".\n const evidence = own(variants, POLYMORPHIC_COLLECTION_ORPHANS_KEY);\n if (evidence === undefined) return variants;\n const orphans = providerDocument(evidence);\n if (!orphans)\n throw new InvalidScalarResult(\n \"polymorphic slot\",\n \"the integrity entry is not an object\"\n );\n for (const [type, count] of Object.entries(orphans))\n if (Number(count) > 0) {\n if (type === \"$storage\")\n throw new QueryEngineError(\n `Polymorphic relation '${shape.relation}' has an unknown discriminator or incomplete stored pair.`\n );\n throw new QueryEngineError(\n `Polymorphic relation '${shape.relation}' references a missing '${type}' record.`\n );\n }\n return variants;\n };\n // Its arms, compiled once, in `shape.arms` order. A junction-carried\n // slot's arm is a collection, so its reader answers the arm's rows.\n if (shape.many) {\n const arms = Object.keys(shape.arms).map((type) => ({\n type,\n read: this.#compileCollection(shape.arms[type]!, internal),\n }));\n return (value) => {\n const variants = slot(value);\n const values: unknown[] = [];\n for (const { type, read } of arms)\n for (const data of read(own(variants, type)))\n values.push({ type, data });\n return values;\n };\n }\n const arms = Object.keys(shape.arms).map((type) => {\n const arm = shape.arms[type]!;\n return { type, arm, read: this.compileReader(arm, internal, true) };\n });\n return (value) => {\n const variants = slot(value);\n for (const { type, arm, read } of arms) {\n const carrier = own(variants, type);\n if (orphanedArm(carrier, arm))\n throw new QueryEngineError(\n `Polymorphic relation '${shape.relation}' references a missing '${type}' record.`\n );\n const data = read(carrier);\n if (data !== null) return { type, data };\n }\n return null;\n };\n }\n if (shape.kind === \"collection\")\n return this.#compileCollection(shape, internal);\n // The document's MEMBER LIST is a fact of the PREPARED PROJECTION, stated\n // once by {@link prepareProjection} and frozen on the shape; a row carries\n // only the values for it. It is read here, once per batch — the shape's\n // OWN keys, exactly as {@link own} reads the provider's — and never again\n // per row: materialising it per row as pairs (`Object.entries` read back\n // by `Object.fromEntries`) made this decoder allocate 2.5x the shipped\n // engine's bytes per row (`g4/release/p1/note.md`).\n const fields = Object.keys(shape.fields);\n const readers = fields.map((field) => {\n const nested = shape.fields[field]!;\n return this.compileReader(\n nested,\n internal,\n carried || nested.kind !== \"scalar\"\n );\n });\n // An internal read is the engine's own: it reads every member it asked\n // for, its gates unread (K5).\n if (shape.gates !== undefined && !internal)\n return this.#compileGatedDocument(\n shape,\n fields,\n readers,\n carried,\n columns\n );\n if (columns) {\n // Native aliases locate cells once; a statement transform may reorder\n // columns. Last occurrence matches the keyed transport's duplicate names.\n const positions = fields.map((field) => columns.lastIndexOf(field));\n return (value) => {\n if (!Array.isArray(value))\n throw new InvalidScalarResult(\n \"row\",\n \"a positional row is not an array\"\n );\n const document: Input = {};\n for (let index = 0; index < fields.length; index++) {\n const position = positions[index]!;\n document[fields[index]!] = readers[index]!(\n position < 0 ? undefined : value[position]\n );\n }\n return document;\n };\n }\n return (value) => {\n const source = providerDocument(providerJson(value));\n if (source === null) {\n if (shape.nullable === false)\n throw new InvalidScalarResult(\n \"row\",\n \"a document the statement always builds is null\"\n );\n return null;\n }\n if (source === undefined)\n throw new InvalidScalarResult(\n \"row\",\n \"a requested document is not a provider row\"\n );\n // OWN-key semantics ({@link own}): a plain member read on a\n // `JSON.parse` result finds `Object.prototype`'s own members, so a\n // field named `toString` the provider OMITTED would inherit a function\n // instead of failing closed. Nested evidence documents also contain\n // user-named predicates, not just schema identifiers. Their `__proto__`\n // member must be an own data property, never the inherited setter.\n const document: Input = {};\n for (let index = 0; index < fields.length; index++) {\n const field = fields[index]!;\n const decoded = readers[index]!(own(source, field));\n if (field === \"__proto__\")\n Object.defineProperty(document, field, {\n value: decoded,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n else document[field] = decoded;\n }\n return document;\n };\n }\n /**\n * A document with read-gated members (K5), out of line from the plain\n * reader: its gates are read first, once per row, and each gated member is\n * written only where its gate holds; where it does not, a member the caller\n * named fails the read, and any other is left out (the row's shape\n * changes, so the document is always a new object).\n */\n #compileGatedDocument(\n shape: Extract<ProjectionShape, { kind: \"object\" }>,\n fields: readonly string[],\n readers: readonly Reader[],\n carried: boolean,\n columns?: readonly string[]\n ): Reader {\n const gates = shape.gates!;\n const readGate = this.compileReader(BOOLEAN_LEAF, false, carried);\n const gated = fields.map((field) => shape.gated![field]);\n const gateIndex = gated.map((member) =>\n member === undefined ? -1 : gates.indexOf(member.gate)\n );\n const positions = columns && [\n ...fields.map((field) => columns.lastIndexOf(field)),\n ...gates.map((gate) => columns.lastIndexOf(gate)),\n ];\n const cell = (source: unknown, index: number, key: string): unknown => {\n if (positions === undefined) return own(source as Input, key);\n const position = positions[index]!;\n return position < 0 ? undefined : (source as unknown[])[position];\n };\n return (value) => {\n let source: unknown = value;\n if (positions) {\n if (!Array.isArray(value))\n throw new InvalidScalarResult(\n \"row\",\n \"a positional row is not an array\"\n );\n } else {\n source = providerDocument(providerJson(value));\n if (source === null) {\n if (shape.nullable === false)\n throw new InvalidScalarResult(\n \"row\",\n \"a document the statement always builds is null\"\n );\n return null;\n }\n if (source === undefined)\n throw new InvalidScalarResult(\n \"row\",\n \"a requested document is not a provider row\"\n );\n }\n const held = gates.map((gate, index) =>\n readGate(cell(source, fields.length + index, gate))\n );\n const document: Input = {};\n for (let index = 0; index < fields.length; index++) {\n const field = fields[index]!;\n const gate = gateIndex[index]!;\n if (gate >= 0 && held[gate] !== true) {\n const refused = gated[index]!.refused;\n if (refused !== undefined) throw new GatedFieldRefusal(refused);\n continue;\n }\n document[field] = readers[index]!(cell(source, index, field));\n }\n return document;\n };\n }\n /**\n * A collection's reader, compiled by {@link compileReader} for a to-many\n * relation and for each arm of a junction-carried variant slot: its rows\n * are carried documents, restored to the requested order.\n */\n #compileCollection(\n shape: CollectionShape,\n internal: boolean\n ): (value: unknown) => unknown[] {\n const readRow = this.compileReader(shape.row, internal, true);\n return (value) => {\n const decoded = providerJson(value);\n if (!Array.isArray(decoded))\n throw new InvalidScalarResult(\n \"collection\",\n \"a requested relation is not a provider array\"\n );\n const rows = decoded.map(readRow);\n return shape.reversed ? rows.reverse() : rows;\n };\n }\n /**\n * One strict scalar decode per leaf, through the existing codec owners. A\n * value outside the column's declared domain is a malformed provider row,\n * never a value to coerce. `provider` is the physical value's continuation;\n * a CARRIED value — one a JSON document already holds — has none. `list` is\n * a list leaf's compiled container reader, and a list MEMBER's leaf is no\n * list.\n */\n private compileScalar(\n leaf: Leaf,\n internal: boolean,\n provider?: FieldReader,\n list?: Reader\n ): Reader {\n const readValue = list ?? this.#compileScalarValue(leaf, internal);\n const nullable = leaf.nullable;\n const allowsJsonNull = leaf.type === \"json\" && leaf.list !== true;\n const read: Reader = (raw) => {\n if (raw === null) {\n if (nullable) return null;\n if (!allowsJsonNull)\n throw new InvalidScalarResult(\n leaf.type,\n leaf.list ? \"a required list is null\" : \"a required scalar is null\"\n );\n }\n if (raw === undefined)\n throw new InvalidScalarResult(leaf.type, \"the value is absent\");\n return readValue(provider === undefined ? raw : provider(raw));\n };\n const join = this.#splitSum(leaf)?.join;\n return join ? (parts) => read(join(parts)) : read;\n }\n /** Bind the declared scalar codec once, preserving its provider-value checks. */\n #compileScalarValue(leaf: Leaf, internal: boolean): Reader {\n const identifier = leaf.id;\n if (identifier !== undefined) {\n return (value) => {\n const decoded = decodeIdentifier(identifier, value);\n if (decoded === undefined)\n throw new InvalidScalarResult(\n leaf.type,\n \"the value is not in this column's declared identifier domain\"\n );\n return internal && identifier.representation === \"text\"\n ? value\n : decoded;\n };\n }\n switch (leaf.type) {\n case \"string\":\n return decodeString;\n case \"boolean\":\n return decodeBoolean;\n case \"int\":\n return leaf.widened ? (sum) => decodeInt(sum, true) : decodeInt;\n case \"bigint\":\n return decodeBigint;\n case \"number\":\n // A number sum is already decoded by `joinNumberSum`.\n return leaf.widened ? (sum) => sum : decodeNumber;\n case \"decimal\":\n return (value) => {\n const decoded = decodeDecimalScalar(\n value,\n leaf.decimal!,\n leaf.widened === true,\n internal,\n this.adapter.result\n );\n if (decoded === undefined)\n throw new InvalidScalarResult(\n leaf.type,\n leaf.widened\n ? \"the sum is not an exact decimal at this column's scale\"\n : \"the value is not an exact decimal in this column's declared domain\"\n );\n return decoded;\n };\n case \"datetime\":\n return (value) => {\n if (leaf.dateTime !== undefined && leaf.dateTime !== \"text\") {\n const decoded = decodePhysicalDateTime(value, leaf.dateTime);\n if (decoded === undefined)\n throw new InvalidScalarResult(\n leaf.type,\n \"the value is not this column's declared physical timestamp\"\n );\n return decoded;\n }\n if (value instanceof Date) {\n if (isDateTimeInstant(value.getTime()))\n return new Date(value.getTime());\n throw new InvalidScalarResult(\n leaf.type,\n \"the Date is outside the public DateTime domain\"\n );\n }\n const parsed =\n typeof value === \"string\"\n ? decodeProviderTimestamp(value)\n : undefined;\n if (!parsed)\n throw new InvalidScalarResult(\n leaf.type,\n \"the value is not a valid provider timestamp in the public DateTime domain\"\n );\n // A TEXT-stored instant's PHYSICAL value is the spelling itself\n // (`encodePhysicalDateTime(iso, \"text\")` is the identity), and this\n // column admits more than one spelling of one instant, so an INTERNAL\n // read keeps the bytes the row holds and a public one materializes the\n // `Date` — the same split the decimal arm above takes through\n // `decodeDecimalScalar`. That is what makes a captured identity\n // address its own row: `Queries.scalarValue` binds this string back\n // unchanged, while a `Date` would be re-spelled by the admission\n // boundary and match a row only where the payload's spelling was that\n // one (FC-02B, which repaired N5 §6's residual).\n return internal ? value : parsed;\n };\n case \"date\":\n return (value) => {\n if (value instanceof Date) {\n const epoch = value.getTime();\n if (\n isDateTimeInstant(epoch) &&\n value.getUTCHours() === 0 &&\n value.getUTCMinutes() === 0 &&\n value.getUTCSeconds() === 0 &&\n value.getUTCMilliseconds() === 0\n )\n return new Date(epoch);\n throw new InvalidScalarResult(\n leaf.type,\n \"the Date is invalid or not UTC midnight\"\n );\n }\n const match =\n typeof value === \"string\" ? DATE_TEXT.exec(value) : null;\n const parsed = match\n ? decodeProviderTimestamp(\n `${match[1]}-${match[2]}-${match[3]}T00:00:00.000Z${match[4] ? \" BC\" : \"\"}`\n )\n : undefined;\n if (!parsed)\n throw new InvalidScalarResult(\n leaf.type,\n \"the value is not a valid ISO calendar date\"\n );\n return parsed;\n };\n case \"time\":\n return decodeTime;\n case \"enum\":\n return (value) => {\n if (typeof value === \"string\" && leaf.enumValues?.has(value) === true)\n return value;\n throw new InvalidScalarResult(\n leaf.type,\n \"the value is not a declared enum member\"\n );\n };\n case \"json\":\n return (value) => this.jsonValue(value);\n case \"blob\":\n return decodeBlob;\n case \"vector\":\n return (value) => {\n const decoded = providerJson(value);\n if (\n !Array.isArray(decoded) ||\n decoded.some(\n (member) => typeof member !== \"number\" || !Number.isFinite(member)\n )\n )\n throw new InvalidScalarResult(\n leaf.type,\n \"the value is not an array of finite numbers\"\n );\n if (leaf.dimension !== undefined && decoded.length !== leaf.dimension)\n throw new InvalidScalarResult(\n leaf.type,\n `the value does not have the configured dimension ${leaf.dimension}`\n );\n return [...decoded];\n };\n case \"point\":\n return (value) => {\n const decoded = providerJson(value);\n const point = validateGeoPoint(decoded);\n if (point.issues)\n throw new InvalidScalarResult(\n leaf.type,\n point.issues[0]?.message ??\n \"the value is not a canonical GeoPoint\"\n );\n return point.value;\n };\n default:\n return () => {\n throw new InvalidScalarResult(\n leaf.type,\n \"the scalar type is unsupported\"\n );\n };\n }\n }\n /**\n * A list leaf's container reader, compiled with its placement by\n * {@link compileReader}: the decimal whole-list codec or one container, then\n * each member through the element's own codec. The member's non-null leaf\n * is derived here, once per list placement of a decoded batch, never per\n * returned list. The reader runs after the NULL and absence checks and the\n * provider continuation, and each member is a carried value.\n */\n private compileList(leaf: Leaf, internal: boolean): Reader {\n if (leaf.type === \"decimal\")\n return (value) => {\n const members = decodeDecimalList(\n value,\n leaf.decimal!,\n internal,\n this.adapter.result\n );\n if (members === undefined)\n throw new InvalidScalarResult(\n leaf.type,\n \"the value is not an exact decimal list in this column's declared domain\"\n );\n return members;\n };\n const member: Leaf = freeze({\n ...leaf,\n list: undefined,\n nullable: false,\n });\n const readMember = this.compileScalar(member, internal);\n const arrayText =\n this.adapter.result.enumListRepresentation === \"arrayText\";\n return (value) => {\n const items: unknown =\n typeof value !== \"string\"\n ? value\n : arrayText && value.startsWith(\"{\")\n ? providerArrayMembers(value)\n : JSON.parse(value);\n if (!Array.isArray(items))\n throw new InvalidScalarResult(\n leaf.type,\n \"a list scalar did not return an array\"\n );\n return items.map((item, index) => {\n if (!Object.hasOwn(items, index))\n throw new InvalidScalarResult(\n leaf.type,\n \"a list scalar returned a sparse array\"\n );\n return readMember(item);\n });\n };\n }\n /**\n * The JSON value domain, normalized once.\n *\n * A provider's JSON is not JavaScript's: SQLite declares a `json` column\n * with NUMERIC affinity, so the bound text `\"42\"` comes back as `42n` and a\n * caller who wrote `42` must read `42` — and a non-finite number, a sparse\n * array or an exotic prototype is a malformed provider value rather than\n * something to publish. (The shipped `scalar-structured-parser.ts:144-200`.)\n *\n * A JavaScript value can also contain ITSELF, which provider text never can:\n * a recursive read's node row arrives as an object, not as text this decoder\n * parsed. That is the same fact as every other one here — the value is not\n * in the JSON domain — so this boundary answers it instead of recursing into\n * a `RangeError`. `enclosing` is the containers this value is being\n * normalized INSIDE, entered before a container's members and left after\n * them, so a document that merely REPEATS one object still normalizes it\n * twice and only a container reached from within itself is refused.\n */\n private jsonValue(value: unknown, enclosing?: Set<object>): unknown {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"boolean\"\n )\n return value;\n if (typeof value === \"number\") {\n if (Number.isFinite(value)) return value;\n throw new InvalidScalarResult(\"json\", \"a JSON number is not finite\");\n }\n if (typeof value === \"bigint\") {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) return parsed;\n throw new InvalidScalarResult(\n \"json\",\n \"a JSON integer is outside the finite Number domain\"\n );\n }\n if (Array.isArray(value)) {\n const path = this.#enterJsonContainer(value, enclosing);\n const members = new Array<unknown>(value.length);\n for (let index = 0; index < value.length; index += 1) {\n if (!Object.hasOwn(value, index))\n throw new InvalidScalarResult(\"json\", \"a JSON array is sparse\");\n members[index] = this.jsonValue(value[index], path);\n }\n path.delete(value);\n return members;\n }\n if (isPlainJsonRecord(value)) {\n const path = this.#enterJsonContainer(value, enclosing);\n const members: Record<string, unknown> = {};\n for (const [key, member] of Object.entries(value))\n Object.defineProperty(members, key, {\n configurable: true,\n enumerable: true,\n value: this.jsonValue(member, path),\n writable: true,\n });\n path.delete(value);\n return members;\n }\n throw new InvalidScalarResult(\n \"json\",\n \"the value is outside the JSON value domain\"\n );\n }\n /**\n * The one entry into a JSON container: the containers already being\n * normalized around it, plus this one. A container that is already open is\n * inside itself, which no JSON document is.\n */\n #enterJsonContainer(\n container: object,\n enclosing: Set<object> | undefined\n ): Set<object> {\n const path = enclosing ?? new Set<object>();\n if (path.has(container))\n throw new InvalidScalarResult(\"json\", \"a JSON value contains itself\");\n path.add(container);\n return path;\n }\n}\n\n/** A document, not a class instance: the shipped JSON record test. */\nfunction isPlainJsonRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nconst INTEGER_TEXT = /^(?:0|-?[1-9]\\d*)$/;\nconst DATE_TEXT = /^(\\d{4})-(\\d{2})-(\\d{2})(?: (BC))?$/;\nconst TIME_TEXT =\n /^(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,6})?(?:Z|[+-](\\d{2})(?::?(\\d{2}))?)?$/;\nconst TIME_ZONE_SUFFIX = /(?:Z|[+-]\\d{2}(?::?\\d{2})?)$/;\nconst TRAILING_FRACTION_ZEROS = /\\.?0+$/;\n\nfunction decodeString(value: unknown): unknown {\n if (typeof value === \"string\") return value;\n throw new InvalidScalarResult(\"string\", \"the value is not a string\");\n}\n\nfunction decodeBoolean(value: unknown): unknown {\n if (typeof value === \"boolean\") return value;\n if (value === 0 || value === 0n) return false;\n if (value === 1 || value === 1n) return true;\n throw new InvalidScalarResult(\n \"boolean\",\n \"the value is not true, false, zero, or one\"\n );\n}\n\n/** `sum`: an int `_sum` past 2^53 reads as the nearest double (a lossy sum). */\nfunction decodeInt(value: unknown, sum = false): unknown {\n const parsed =\n typeof value === \"bigint\"\n ? Number(value)\n : typeof value === \"string\" && INTEGER_TEXT.test(value)\n ? Number(value)\n : value;\n if (typeof parsed !== \"number\")\n throw new InvalidScalarResult(\n \"int\",\n \"the value is not a canonical integer\"\n );\n if (!(sum ? Number.isInteger(parsed) : Number.isSafeInteger(parsed)))\n throw new InvalidScalarResult(\n \"int\",\n \"the integer is outside the safe range\"\n );\n return parsed;\n}\n\nfunction decodeBigint(value: unknown): bigint {\n if (typeof value === \"bigint\") return value;\n if (typeof value === \"number\" && Number.isSafeInteger(value))\n return BigInt(value);\n if (typeof value === \"string\" && INTEGER_TEXT.test(value))\n return BigInt(value);\n throw new InvalidScalarResult(\n \"bigint\",\n \"the value is not a canonical integer\"\n );\n}\n\nfunction decodeNumber(value: unknown): number {\n const parsed =\n typeof value === \"string\" && value.trim() !== \"\" ? Number(value) : value;\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed))\n throw new InvalidScalarResult(\n \"number\",\n \"the value is not a canonical finite number\"\n );\n return parsed;\n}\n\n/** A widened `_sum`'s SQL and the join its reader reads. */\ntype SplitSumSql = ReturnType<DatabaseAdapter[\"aggregates\"][\"numberSum\"]>;\ninterface SplitSum {\n readonly sql: (expr: Sql) => SplitSumSql;\n readonly join: (parts: unknown) => unknown;\n}\n\n/** The divisor `aggregates.numberSum` scales its high part by. */\nconst NUMBER_SUM_SCALE = 2 ** 64;\n\n/**\n * A number `_sum` from its two `numberSum` parts: `high * 2^64 + low`, which\n * is the summed double, `±Infinity` past the double range. Each part is null\n * when none of its members is present, so both are for an empty window.\n */\nfunction joinNumberSum(value: unknown): number | null {\n const [first, second] = sumParts(value, \"number\");\n const high = first === null ? null : decodeNumber(first);\n const low = second === null ? null : decodeNumber(second);\n if (high === null) return low;\n return high * NUMBER_SUM_SCALE + (low ?? 0);\n}\n\n/** The factor `aggregates.integerSum` splits its high part at. */\nconst INTEGER_SUM_SCALE = 2n ** 32n;\n\n/**\n * An int64 `_sum` from its two `integerSum` parts, `high * 2^32 + low`, as\n * the integer text the bigint and decimal-coefficient decoders read. Both\n * parts sum the same members, so both are null for an empty window.\n */\nfunction joinIntegerSum(value: unknown, type: string): string | null {\n const [high, low] = sumParts(value, type);\n if (high === null) return null;\n return String(decodeBigint(high) * INTEGER_SUM_SCALE + decodeBigint(low));\n}\n\nfunction sumParts(value: unknown, type: string): [unknown, unknown] {\n if (!Array.isArray(value) || value.length !== 2)\n throw new InvalidScalarResult(type, \"the sum is not its two parts\");\n return [value[0], value[1]];\n}\n\nfunction decodeTime(value: unknown): string {\n if (typeof value !== \"string\")\n throw new InvalidScalarResult(\n \"time\",\n \"the value is not a valid provider time\"\n );\n const match = TIME_TEXT.exec(value);\n if (\n !(\n match &&\n isDateTimeClock(Number(match[1]), Number(match[2]), Number(match[3]))\n )\n )\n throw new InvalidScalarResult(\n \"time\",\n \"the value is not a valid provider time\"\n );\n if (Number(match[4] ?? 0) > 23 || Number(match[5] ?? 0) > 59)\n throw new InvalidScalarResult(\"time\", \"the timezone suffix is invalid\");\n let time = value.replace(TIME_ZONE_SUFFIX, \"\");\n if (time.includes(\".\")) time = time.replace(TRAILING_FRACTION_ZEROS, \"\");\n const fraction = time.split(\".\")[1];\n if (fraction && fraction.length > 3)\n throw new InvalidScalarResult(\n \"time\",\n \"the normalized precision exceeds milliseconds\"\n );\n return time;\n}\n\n/**\n * Every driver's binary spelling, normalized to one fresh Uint8Array by the one\n * binary-shape owner (`validation/primitives/binary-shapes.ts`); the refusal's\n * wording is this boundary's.\n */\nfunction decodeBlob(value: unknown): Uint8Array {\n const { bytes } = normalizeBinaryValue(value);\n if (bytes) return bytes;\n throw new InvalidScalarResult(\"blob\", \"the value is not a binary value\");\n}\n\n/** One dimension of a provider's own array output text: `{a,\"b,c\",NULL}`. */\nfunction providerArrayMembers(text: string): unknown[] {\n if (!(text.startsWith(\"{\") && text.endsWith(\"}\")))\n throw new InvalidScalarResult(\n \"enum\",\n \"a list scalar did not return an array\"\n );\n const body = text.slice(1, -1);\n if (body.length === 0) return [];\n const members: unknown[] = [];\n let index = 0;\n while (index <= body.length) {\n if (body[index] === '\"') {\n let member = \"\";\n index += 1;\n while (index < body.length && body[index] !== '\"') {\n member += body[index] === \"\\\\\" ? body[++index] : body[index];\n index += 1;\n }\n members.push(member);\n index += 2;\n continue;\n }\n const next = body.indexOf(\",\", index);\n const end = next === -1 ? body.length : next;\n const member = body.slice(index, end);\n members.push(member === \"NULL\" ? null : member);\n index = end + 1;\n if (next === -1) break;\n }\n return members;\n}\n","import type { BatchQuery } from \"@drivers/types\";\nimport type { UniqueConstraintError } from \"@errors\";\nimport type { AnyModel } from \"@schema\";\nimport { Sql } from \"@sql\";\nimport type { Member } from \"./operation-context\";\nimport type { Query } from \"./query\";\n\n/**\n * One assertion this attempt raises if its statement disagrees with the world.\n *\n * `readsBatchReference` states whether it asks about a value this unit\n * PRODUCED, read back from the batch reference scratch: the one premise a\n * rollback leaves unaskable, because the transaction took the scratch with it.\n * The attribution ladder reads it to know which premise it cannot re-probe.\n */\ntype AssertedPremise = {\n query: Query;\n present: boolean;\n failure: Error;\n readsBatchReference: boolean;\n};\n\n/**\n * One queued write that judges the row it produces and fails on its own\n * assertion when refused (R4): the refusal it raises, and, where it reads\n * no value of this unit's batch scratch, the SELECT it reads its rows from,\n * which fails the same way when asked again after a rollback.\n */\ntype JudgedWrite = {\n refusal: Error;\n probe?: Sql;\n};\n\n/**\n * One value this unit PRODUCED and stored in its own batch scratch: the\n * expression every statement of that unit binds it by, and the model field\n * whose codec reads it back at the unit's boundary (D-58).\n */\nexport type ScratchPublication = {\n readonly model: AnyModel;\n readonly field: string;\n readonly expression: Sql;\n};\n\nconst NO_PUBLICATIONS: readonly ScratchPublication[] = Object.freeze([]);\n\n/**\n * Disposable batch construction and rejection evidence; never committed progress.\n *\n * Only {@link pending} belongs to every attempt. The three evidence collections\n * exist from the first fact each one records, because an operation that records\n * none — every read, prepared or executed — would otherwise pay two `Map`s and a\n * `Set` per operation for collections nothing ever reads (rule 7,\n * `g4/perf2/note.md` §2). An absent collection IS empty: the drain accessors\n * below answer an empty copy, and {@link hasAssertedPremises} answers `false`,\n * so no reader can tell absent from empty.\n */\nexport class TransportAttempt {\n readonly pending: BatchQuery[] = [];\n rejectedInsert?: { error: UniqueConstraintError; producer: object };\n /**\n * The scratch of the unit being assembled — the DISPATCHED UNIT's, not this\n * attempt's (D-58). It is minted by the first statement that stores into it\n * and cleared where the unit ends, so the next unit that needs one makes its\n * own and no statement ever names a table its own segment did not create.\n */\n scratchId?: string;\n nextField = 0;\n #publications: ScratchPublication[] | undefined;\n #carriedValues: Map<Sql, unknown> | undefined;\n #producers: Map<BatchQuery, object> | undefined;\n #premises: Map<BatchQuery, AssertedPremise> | undefined;\n #judged: Map<BatchQuery, JudgedWrite> | undefined;\n #members: Set<Member> | undefined;\n /** Record one produced value this unit stored in its scratch (D-58). */\n publishScratchValue(publication: ScratchPublication): void {\n (this.#publications ??= []).push(publication);\n }\n /** The values this unit stored; the attempt keeps none of them. */\n drainScratchPublications(): readonly ScratchPublication[] {\n const published = this.#publications ?? NO_PUBLICATIONS;\n this.#publications = undefined;\n return published;\n }\n /** The literal one published expression was read back as at the boundary. */\n carryScratchValue(expression: Sql, value: unknown): void {\n (this.#carriedValues ??= new Map()).set(expression, value);\n }\n /**\n * One field's value as it stands NOW: the literal a segment boundary read\n * back for the expression that published it, or the value itself.\n *\n * A published expression names the scratch of the unit that stored it, and\n * that scratch dies with its unit — so once the boundary has read the value\n * back, the expression is spent and the literal is the value (D-58). Asked by\n * the estate's one reader of a field's runtime value, `CommandAttempt.read`.\n */\n carried(value: unknown): unknown {\n if (!(value instanceof Sql)) return value;\n const carried = this.#carriedValues;\n return carried?.has(value) ? carried.get(value) : value;\n }\n /** Attribute one queued INSERT to the producer whose row it writes. */\n recordInsertProducer(insert: BatchQuery, producer: object): void {\n (this.#producers ??= new Map()).set(insert, producer);\n }\n /** Record the failure one queued assertion raises when it disagrees. */\n assertPremise(assertion: BatchQuery, premise: AssertedPremise): void {\n (this.#premises ??= new Map()).set(assertion, premise);\n }\n /**\n * Record the refusal one queued WRITE raises when the row it produces is\n * not permitted: the statement fails on its own assertion before it\n * writes (R4). It is a write, never a premise ({@link holdsWrite}).\n */\n judgeWrite(write: BatchQuery, judged: JudgedWrite): void {\n (this.#judged ??= new Map()).set(write, judged);\n }\n /** The judged writes recorded so far; this attempt keeps none of them. */\n drainJudgedWrites(): Map<BatchQuery, JudgedWrite> {\n const judged = this.#judged ?? new Map<BatchQuery, JudgedWrite>();\n this.#judged = undefined;\n return judged;\n }\n /** Declare one queued statement as belonging to a record-series member. */\n recordMember(member: Member): void {\n (this.#members ??= new Set()).add(member);\n }\n /** Whether any assertion has been recorded, without creating the map. */\n get hasAssertedPremises(): boolean {\n return this.#premises !== undefined && this.#premises.size > 0;\n }\n /**\n * Is a WRITE waiting, or only premises?\n *\n * Two kinds of statement wait here before a dispatch: the premises a unit\n * proves, which commit nothing on their own, and the writes they protect.\n * A caller asking whether dispatching NOW would make someone else's write\n * durable asks this, and nothing finer.\n */\n get holdsWrite(): boolean {\n return this.pending.some((statement) => !this.#premises?.has(statement));\n }\n /**\n * Is a write of a record OTHER than this one's waiting?\n *\n * Every record's write is declared with the record it belongs to\n * ({@link recordMember}); a premise and the batch scratch's own statements\n * are declared with none. So a member asking this asks the one question its\n * boundary answers: has some other record of this series left an effect in\n * the queue that a read taken OUTSIDE the queue cannot see\n * ({@link OperationContext.executeMember})?\n */\n holdsOtherMemberWrite(member: Member): boolean {\n if (!this.#members) return false;\n for (const queued of this.#members) if (queued !== member) return true;\n return false;\n }\n /** The producers recorded so far; this attempt keeps none of them. */\n drainInsertProducers(): Map<BatchQuery, object> {\n const producers = this.#producers ?? new Map<BatchQuery, object>();\n this.#producers = undefined;\n return producers;\n }\n /**\n * The premises the next dispatch does not carry the write for.\n *\n * A premise is proved inside the atomic unit that contains the write it\n * protects, never in an earlier planning batch (Arnaud's D-29): proved early\n * it would close the window it exists for before the write opens it. The\n * queue's TRAILING premises are exactly those — nothing queued after them is\n * theirs to protect yet — so they step out of this dispatch and lead the\n * next one, in the order they were stated.\n */\n withholdPremises(): void {\n const premises = this.#premises;\n if (!premises) return;\n let first = this.pending.length;\n while (first > 0 && premises.has(this.pending[first - 1]!)) first--;\n this.#withheld.push(...this.pending.splice(first));\n }\n /** The withheld premises, back at the head of the queue that stated them. */\n restorePremises(): void {\n if (this.#withheld.length > 0)\n this.pending.unshift(...this.#withheld.splice(0));\n }\n readonly #withheld: BatchQuery[] = [];\n /**\n * The assertions recorded so far; this attempt keeps none of them, except a\n * withheld premise's own, which travels with it to the dispatch that proves\n * it.\n */\n drainAssertedPremises(): Map<BatchQuery, AssertedPremise> {\n const premises = this.#premises ?? new Map<BatchQuery, AssertedPremise>();\n const kept = new Map<BatchQuery, AssertedPremise>();\n for (const statement of this.#withheld) {\n const premise = premises.get(statement);\n if (!premise) continue;\n kept.set(statement, premise);\n premises.delete(statement);\n }\n this.#premises = kept.size > 0 ? kept : undefined;\n return premises;\n }\n /** The members declared so far; this attempt keeps none of them. */\n drainMembers(): Member[] {\n const members = this.#members ? [...this.#members] : [];\n this.#members = undefined;\n return members;\n }\n}\n","import {\n assembleAdapterSelect,\n getAdapterInternals,\n} from \"@adapters/adapter-internals\";\nimport { attachCommitCertainty } from \"@drivers/driver-error-context\";\nimport { batchMayContainAssertionCollision } from \"@drivers/error-mapping\";\nimport {\n bindExecutionTransactionPhases,\n deriveStatementExecutionContext,\n} from \"@drivers/execution-context\";\nimport type { AnyDriver } from \"@drivers/exports\";\nimport {\n borrowPositionalResult,\n resolvePositionalResultDriver,\n} from \"@drivers/positional-result\";\nimport { transferPreparedStatement } from \"@drivers/prepared-statement-provenance\";\nimport type {\n BatchQuery,\n QueryExecutionContext,\n QueryResult,\n} from \"@drivers/types\";\nimport {\n attachRecordSeriesProgress,\n isVibORMError,\n NESTED_WRITE_ASSERTION_FLOOR_MESSAGE,\n NestedWriteAssertionError,\n NestedWriteError,\n QueryEngineError,\n QueryError,\n type RecordSeriesProgress,\n retainWriteOutcomeFailure,\n TransactionError,\n UniqueConstraintError,\n UnsupportedOperationError,\n VibORMErrorCode,\n} from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport { type Sql, sql } from \"@sql\";\nimport { createFailureError } from \"../../batch-error-attribution\";\nimport {\n compileBindBudgetChunks,\n normalizedBindParameterLimit,\n} from \"../../bind-budget\";\nimport type {\n PreparedBatchGuard,\n PreparedBatchOperation,\n PreparedGuardFailure,\n} from \"../../types\";\nimport {\n GatedFieldRefusal,\n InvalidScalarResult,\n type PreparedProjection,\n type PreparedSelector,\n type ProjectionShape,\n Queries,\n type Query,\n type Read,\n RecursiveOutputOverBudget,\n returningSafeProjection,\n wholeValue,\n} from \"./query\";\nimport type { CallScope, RowJudgement } from \"./row-scope\";\nimport {\n type EngineSchema,\n type Input,\n isReadOperation,\n type Operation,\n record,\n} from \"./schema\";\nimport { linkJudgement, type Membership, physicalField } from \"./storage\";\nimport { type ScratchPublication, TransportAttempt } from \"./transport-attempt\";\n\nexport type Member = object;\n\n/**\n * The single-row mutations whose returned identity a batch-only, non-returning\n * driver cannot resolve inside its own atomic unit (the shipped\n * `ATOMIC_RESOLUTION_OPERATIONS`).\n */\nconst ATOMIC_RESOLUTION_OPERATIONS: ReadonlySet<string> = new Set([\n \"update\",\n \"delete\",\n \"upsert\",\n]);\n\nexport type MemberRollback = <T>(\n execute: (driver: AnyDriver) => Promise<T>,\n context: QueryExecutionContext\n) => Promise<T>;\n\n/**\n * Where this operation publishes the DURABLE PHASE of its own writes.\n *\n * The transport is the only thing that knows it, so the transport says it — at\n * the moment it learns it, not afterwards from an error's published meta. That\n * is where the shipped executor says it too: `committedWriteSegment` from the\n * segment's own acknowledgement (`write-engine/OperationExecutor.ts:974-990`)\n * and `writeMayBeVisible` from the branch that records a dispatch it cannot\n * prove rolled back (`:1050-1058`), both before the driver's error is\n * rethrown. The candidate's two corresponding sites are in {@link submit}.\n *\n * `recordSeriesProgress` is therefore the PUBLIC report of a record series and\n * nothing else; no consumer reads a cache signal back out of it\n * (`g4/regression/note.md` \"Seam round\").\n */\nexport interface WriteOutcomeSeam {\n /** A write segment of this operation is durable. */\n readonly committedSegment?: () => Promise<void>;\n /** A dispatched write segment cannot be proven rolled back. */\n readonly mayBeVisible?: () => Promise<void>;\n}\n\nexport type ExecutionBinding =\n | {\n readonly kind: \"borrowed-transaction\";\n readonly driver: AnyDriver;\n /** MEMBER isolation inside the caller's own scope (array fallback). */\n readonly memberRollback?: MemberRollback;\n /**\n * The caller transferred the OPERATION region: it opened none itself, and\n * the candidate opens exactly one when the operation needs more than one\n * statement. Supplied only by the callback-transaction route, never by\n * the array fallback, which mirrors the shipped `runLinearOn` and opens\n * no operation envelope at all (note §8.4, brief item 11 revision 4).\n */\n readonly operationRegion?: MemberRollback;\n readonly writeOutcome?: WriteOutcomeSeam;\n }\n /**\n * The root situation, stated by name: no borrowed driver and no grant, the\n * operation owns its own standalone envelope. It carries nothing but the\n * write-outcome seam, and an absent binding still means exactly this.\n */\n | { readonly kind: \"standalone\"; readonly writeOutcome?: WriteOutcomeSeam };\n\ntype ExecutionOwnership =\n | \"standalone\"\n | \"borrowed-transaction\"\n | \"batch-preparation\";\n\n/** One member's place in its record series, as a failure reports it. */\ntype MemberAttribution = {\n readonly path: readonly number[];\n readonly totalMembers: number;\n};\n\n/** What an operation that has queued nothing has queued. */\nconst NO_QUEUED_STATEMENTS: readonly BatchQuery[] = Object.freeze([]);\n\n/**\n * One premise a generated-output continuation re-states in EVERY later segment.\n *\n * A committed segment cannot be taken back, so what the next one trusts is\n * re-read in it: the created record's own identity, and the PARENT row whose\n * referenced value the membership correlates on — a membership is a VALUE, so\n * once another row holds that reference the correlation answers with it. Each\n * carries its own sentence, stated where the premise is declared.\n */\ninterface Continuation {\n readonly model: AnyModel;\n /**\n * The query this continuation's guard states, built when the GUARD is — a\n * LATER segment — and not when the continuation is declared. A parent whose\n * generated key this unit produced crosses the boundary as a LITERAL (D-58),\n * so a query built at declaration time would still name the spent scratch of\n * the unit that produced it. Stated once and kept ({@link query}).\n */\n readonly state: () => Query;\n query?: Query;\n readonly failure: () => Error;\n /**\n * Declared while THIS batch was being built: the segment that writes what it\n * re-pins has not committed yet, so there is nothing for it to say until the\n * next one ({@link OperationContext.submit} clears it as it dispatches).\n */\n declaring?: boolean;\n}\n/** What an operation that declared no generated-output continuation has. */\nconst NO_CONTINUATIONS: readonly Continuation[] = Object.freeze([]);\n/**\n * One value a dispatched unit stored in its own scratch and reads back at its\n * boundary, with the projection that decodes it through the field's codec.\n */\ntype ScratchCarry = {\n readonly query: Query;\n readonly publication: ScratchPublication;\n};\n/** What a unit that stored no produced value carries across its boundary. */\nconst NO_SCRATCH_CARRY: readonly ScratchCarry[] = Object.freeze([]);\n/**\n * The captured junction slots one attempt has already vacated, keyed by the\n * captured VALUES themselves: the edge's table, then its columns in the edge's\n * own order ({@link OperationContext.spendSlot}).\n */\ntype SpentSlots = Map<unknown, SpentSlots | true>;\n\n/**\n * The row a created record is a MEMBER of, as its interpreter holds it: the\n * parent's identity AND the value the membership correlates on, which is what\n * separates \"this parent\" from \"whatever row now answers the reference\".\n */\nexport interface MembershipParent {\n readonly model: AnyModel;\n /**\n * The parent's identity and correlated value AS THEY STAND when the guard\n * asks: a key this operation produced is an expression inside the unit that\n * stored it and a literal in every unit after it (D-58), and the interpreter\n * that holds the row answers whichever it now is.\n */\n readonly where: () => Input;\n readonly relation: string;\n readonly verb: string;\n}\n\n/** One operation owns its SQL scopes, transport binding, and batch scratch lifetime. */\n/**\n * What an ordered observation (N1) requires of the batch it reads in: a row\n * present, or no row outside a membership — asserted as a premise ahead of\n * the read, so the batch aborts before anything commits.\n */\nexport interface ObservationPremise {\n readonly query: Query;\n readonly present: boolean;\n readonly failure: () => Error;\n}\n/** A nested write's refusal of the row it produces (§5.3, R4). */\nexport function nestedRefusal(\n verb: string,\n relation: string\n): PreparedGuardFailure {\n return {\n kind: \"nestedWrite\",\n relation,\n message: `Cannot ${verb} relation '${relation}': the record it writes is not permitted.`,\n raceable: false,\n };\n}\n/**\n * A write whose statement judges the row it produces (R4): its model, and\n * what it reports when its assertion fails, before it writes.\n */\ninterface JudgedWrite {\n readonly model: AnyModel;\n readonly refusal: PreparedGuardFailure;\n}\nexport class OperationContext {\n readonly queries: Queries;\n readonly driver: AnyDriver;\n readonly usesBatch: boolean;\n readonly #ownership: ExecutionOwnership;\n /**\n * Whether this context PREPARES a package for the array owner instead of\n * executing: the one route that can issue no planning read of its own,\n * because every statement it produces rides the owner's batch. Read by the\n * plan to choose a form that needs no such read (D-46).\n */\n get preparesBatch(): boolean {\n return this.#ownership === \"batch-preparation\";\n }\n readonly #memberRollback: MemberRollback | undefined;\n readonly #operationRegion: MemberRollback | undefined;\n /** Where this operation states its own durable write phase ({@link WriteOutcomeSeam}). */\n readonly #writeOutcome: WriteOutcomeSeam | undefined;\n /** True only while the operation's OWN region is the current transport. */\n #ownRegionOpen = false;\n #transport: AnyDriver;\n #attemptStore: TransportAttempt | undefined;\n /**\n * The operation's disposable transport attempt, built on its FIRST use.\n *\n * A read that executes queues nothing — it dispatches its one statement\n * directly ({@link read}) — so it never has an attempt at all, and the write\n * machinery below is the same story field by field: rule 7, a pure read\n * allocates none of it. Every reader that only asks whether this operation\n * has queued anything reads {@link queued}, which answers an empty list\n * without creating an attempt, so no reader can tell absent from empty.\n */\n get #attempt(): TransportAttempt {\n return (this.#attemptStore ??= new TransportAttempt());\n }\n /** The statements queued on this operation's attempt; empty until one is. */\n private get queued(): readonly BatchQuery[] {\n return this.#attemptStore?.pending ?? NO_QUEUED_STATEMENTS;\n }\n #committedMemberSet: Set<Member> | undefined;\n #memberAttributionMap: WeakMap<Member, MemberAttribution> | undefined;\n #continuationList: Continuation[] | undefined;\n /** The captured junction slots this attempt has already vacated ({@link link}). */\n #vacatedMemberships: SpentSlots | undefined;\n /** Generated-output continuations declared so far; none until one is. */\n get #continuationCount(): number {\n return this.#continuationList?.length ?? 0;\n }\n #committedSegments = 0;\n #mayHaveCommittedSegment: true | undefined;\n #completedMembers = 0;\n /**\n * The shipped `hasCommittedRecordSeriesProgress` (`write-engine/routing.ts:197`),\n * and the ONE fact the recovery allowance is refused on (Arnaud's D-25).\n *\n * An operation that has acknowledged nothing can be re-planned: a fresh\n * occurrence tree over the same ADMITTED values re-reads committed state and\n * converges. One that has, or may have, committed a segment cannot — a\n * re-plan would write it twice. Dynamic member ADMISSION is not progress:\n * nothing was acknowledged by admitting a member, and requiring it here is\n * what made a raceable assertion over a captured member set unrecoverable.\n */\n get #committedProgress(): boolean {\n return (\n this.#committedSegments > 0 || this.#mayHaveCommittedSegment === true\n );\n }\n /**\n * Has this operation admitted a DYNAMIC member — one whose defaults and\n * transforms ran against a row this attempt read?\n *\n * It is not progress, and D-25 removed it from the progress rule above. It\n * still bounds the recovery that REPLAYS the tree that ran: a replayed\n * member would have to be admitted a second time, and admitted values are\n * never validated or transformed again (rule 10). The recovery that\n * RE-PLANS is not bounded by it — a fresh occurrence tree derives its\n * members from the committed state it re-reads.\n */\n #memberAdmissionStarted = false;\n /**\n * The transport window of the operation's OWN set-oriented statement, while\n * one is submitting ({@link setMutations}).\n *\n * A set mutation admits no member: it is the one atomic unit a folded root\n * write — or a relation-free bulk verb — issues on its own behalf, so its\n * window is a transport artifact and not a record-series member. That is the\n * one fact {@link failure} asks to decide whether an uncertain outcome is\n * PUBLIC progress or stays internal.\n */\n #setWindow: Member | undefined;\n /**\n * A write-outcome listener that failed while {@link submit} acknowledged its\n * committed segment, HELD until the operation's own answer to that batch is\n * known ({@link settleSubmitted}).\n *\n * The batch transport acknowledges BEFORE its responses are decoded, so it is\n * the one site where the listener fails first. The shipped `runAtomicBatch`\n * holds it in exactly the same place (`write-engine/OperationExecutor.ts`\n * `committed()` at `:1277-1289` captures `outcomeFailure` instead of throwing\n * it) and composes only once `operation.parse` has answered (`:1332-1343`).\n */\n private heldOutcomeFailure?: { readonly failure: unknown };\n #atomicAssertionRejection: unknown | undefined;\n #incompletePreparationSentinel: Error | undefined;\n /**\n * The preparation sentinel, built on its FIRST use and never before.\n *\n * It is a control-flow value, not a diagnostic: it is compared by identity\n * ({@link isIncompletePreparation}) and thrown by the four preparation-only\n * refusals, and no caller ever sees it — `prepareBatch`\n * (`commands/index.ts:204`) turns it into `undefined`. Constructing it in the\n * field block cost a full V8 stack capture on EVERY operation, prepared or\n * not, which the G4 cutover diagnosis measured as the dominant share of the\n * preparation regression (`g4/cutover/perf-diagnosis.md` §4.1). It stays an\n * `Error` — a branded object would lose the `cause` link\n * `attachRecordSeriesProgress` attaches only to an `Error`\n * (`src/errors/record-series-progress.ts:26-28`) on the one path that wraps\n * it (a batch-preparation prefix flush, `commands/execution.ts:382`).\n */\n private get incompletePreparation(): Error {\n return (this.#incompletePreparationSentinel ??= new Error(\n \"This operation requires dynamic execution\"\n ));\n }\n #preparedParser: ((results: QueryResult<unknown>[]) => unknown) | undefined;\n #preparedGuardList: PreparedBatchGuard[] | undefined;\n /**\n * Failures this operation has ALREADY ANSWERED with, which {@link failure}\n * returns unchanged: the premise it raised about the world (see `published`),\n * and the write-outcome answers the batch transport states once its hold is\n * released ({@link settleSubmitted}, {@link submit}'s catch) — the shipped\n * `runAtomicBatch` throws those exactly as built\n * (`write-engine/OperationExecutor.ts:1306-1309`, `:1336-1343`), while the\n * progress-bearing aggregate of its PROGRESSIVE path is a different failure\n * that is attributed (`:1037-1046`) and is not marked here.\n */\n #answeredFailureSet: WeakSet<object> | undefined;\n #correlationIdValue: string | undefined;\n /**\n * This operation's correlation id, minted on its FIRST read and then stable\n * for the operation's life. The client route always hands its own trusted\n * execution context down ({@link attribution}), so a minted id is read only\n * by an error's `meta` and by a statement context the caller did not supply —\n * paying `crypto.randomUUID()` in the field block spent it on every operation\n * for the ones that never ask (rule 7).\n */\n get #correlationId(): string {\n return (this.#correlationIdValue ??= crypto.randomUUID());\n }\n /**\n * The operation's physical envelope. `deferred` is the only state in which the\n * envelope has not been decided yet: it becomes `statement` when the operation\n * reaches its terminal statement without having issued any other, and `open`\n * when it does not (§ {@link run}).\n */\n #envelope: \"open\" | \"deferred\" | \"statement\" = \"open\";\n #performed = 0;\n #requiresEnvelopeSentinel: Error | undefined;\n /**\n * The envelope sentinel, built on its FIRST use and never before — the same\n * control-flow value as {@link incompletePreparation} and for the same\n * reason. It is raised by {@link dispatch} and caught by its one reader\n * ({@link run}), which compares it by identity; a successful operation never\n * materialises it, and an operation that does pays for exactly one.\n */\n private get requiresEnvelope(): Error {\n return (this.#requiresEnvelopeSentinel ??= new Error(\n \"This operation must execute through its driver context\"\n ));\n }\n readonly schema: EngineSchema;\n /** The call's row facts and instant; absent on a client without them. */\n readonly scope: CallScope | undefined;\n readonly modelName: string;\n readonly operation: Operation;\n /**\n * The caller's own trusted execution context. It already carries this\n * operation's model, verb, correlation id, instrumentation and resolved\n * extension chain, and the chain is held by the identity of that exact\n * object, so the candidate passes it through rather than minting a second\n * attribution (g4/unit03/note.md B-4).\n */\n readonly #callerAttribution: QueryExecutionContext | undefined;\n constructor(\n schema: EngineSchema,\n factoryDriver: AnyDriver,\n modelName: string,\n operation: Operation,\n binding?: ExecutionBinding,\n prepareBatch = false,\n callerAttribution?: QueryExecutionContext,\n scope?: CallScope\n ) {\n this.scope = scope;\n this.schema = schema;\n this.modelName = modelName;\n this.operation = operation;\n this.#callerAttribution = callerAttribution;\n this.#ownership = prepareBatch\n ? \"batch-preparation\"\n : (binding?.kind ?? \"standalone\");\n this.driver =\n binding?.kind === \"borrowed-transaction\" ? binding.driver : factoryDriver;\n this.#writeOutcome = binding?.writeOutcome;\n this.#memberRollback =\n binding?.kind === \"borrowed-transaction\"\n ? binding.memberRollback\n : undefined;\n this.#operationRegion =\n binding?.kind === \"borrowed-transaction\"\n ? binding.operationRegion\n : undefined;\n this.#transport = this.driver;\n this.usesBatch =\n this.#ownership === \"batch-preparation\" ||\n (this.#ownership === \"standalone\" && !this.driver.supportsTransactions);\n this.queries = new Queries(\n schema,\n this.driver.adapter,\n this.driver.result,\n scope?.domain,\n scope\n );\n }\n get attribution(): QueryExecutionContext {\n return (\n this.#callerAttribution ?? {\n model: this.modelName,\n operation: this.operation,\n correlationId: this.#correlationId,\n }\n );\n }\n /**\n * This operation's own facts for an error's meta. Attribution is the driver's\n * context (and may be the caller's trusted object); an error's meta is the\n * candidate's own record and keeps the exact fields it has always carried.\n */\n get #errorMeta(): Record<string, unknown> {\n return {\n model: this.modelName,\n operation: this.operation,\n correlationId: this.#correlationId,\n };\n }\n /**\n * The attribution ONE statement executes under. A statement compiled for a\n * nested record names that record's model, so a provider failure, a statement\n * transform and an observer name the model whose table the statement already\n * named. The rule: the operation's own context while the models agree, and\n * otherwise the SAME context re-attributed by the snapshot owner, which keeps\n * the correlation id, instrumentation and resolved extension chain\n * (`deriveStatementExecutionContext`). Without a caller context this engine\n * keeps its own minted attribution. (It is the V1 rule verbatim; V1 spelled it\n * in `statementExecutionContext`, retired with the pattern experiment under\n * D-15 and readable at `e8114ed9`.)\n */\n private statementContext(\n model: AnyModel,\n operation: string\n ): QueryExecutionContext {\n const name = model[\"~\"].names.ts!;\n const caller = this.#callerAttribution;\n if (!caller)\n return { model: name, operation, correlationId: this.#correlationId };\n return caller.model === name\n ? caller\n : deriveStatementExecutionContext(caller, name);\n }\n #queue(\n statement: Sql,\n context: QueryExecutionContext = this.attribution,\n member?: Member\n ): BatchQuery {\n const prepared = this.#transport._prepare(statement, context);\n // The DRIVER owns this query's identity. It defers the statement transform\n // and registers the typed `Sql` against the\n // object it returned (`drivers/driver-transaction-base.ts:246-264`), which\n // the statement onion reads back before dispatch — so a snapshot that does\n // not carry the provenance silently drops every deferred transform.\n const query = transferPreparedStatement(prepared, {\n ...prepared,\n context,\n });\n this.#attempt.pending.push(query);\n if (member) this.#attempt.recordMember(member);\n return query;\n }\n prepareMembers<T extends Member>(prepare: () => T[], parent?: Member): T[] {\n this.#memberAdmissionStarted = true;\n try {\n const members = prepare();\n const path = parent\n ? (this.#memberAttributionMap?.get(parent)?.path ?? [])\n : [];\n const attribution = (this.#memberAttributionMap ??= new WeakMap());\n for (const [index, member] of members.entries())\n attribution.set(member, {\n path: [...path, index],\n totalMembers: members.length,\n });\n return members;\n } catch (error) {\n throw this.failure(error, \"planning\", parent);\n }\n }\n /**\n * A member's boundary is the MEMBER's, and a dispatch commits the whole queue.\n *\n * On a batch-only transport a dispatch is a COMMITTED SEGMENT, so a boundary\n * taken while an enclosing write is still waiting makes that write durable\n * too — a record this series owns no member of, whose own children are not\n * done. Measured: a nested `createMany` of two literal rows committed\n * [INSERT parent, INSERT child#1] at the first member, and the second row's\n * duplicate key then left both behind, where the interactive route rolls the\n * operation back. D-51 admits a succession of segments as PACKAGING only\n * while the two routes keep ONE result, so a member takes its boundary here\n * only where nothing but its own members' writes is waiting.\n *\n * Where an enclosing write IS waiting the boundary is DEFERRED, never\n * dropped: the pendency decides WHEN the series segments, never whether a\n * later member gets to see an earlier one. That is decided where a member\n * OBSERVES — a probe, a choose, a lookup, a capture answered outside this\n * queue ({@link answer}) — because a read outside the queue cannot see a\n * write the queue still holds, and the dependency pass cannot place it for\n * them: a series' members carry no write of EACH OTHER —\n * `Commands.isSeriesMember` stops the SIBLING scan at the series in both\n * pairing walks (they still continue above it), so no member's read is ever\n * placed against another member's write (FC-01 places a member's OWN reads\n * at their execution point; it does not pair them across members). So order\n * is not visibility here, and the member that observes claims the boundary\n * the earlier member earned. Measured without it: a second\n * `INSERT INTO \"n5mb_authors\"` for the row the first member had already\n * created, `UniqueConstraintError` where the interactive twin answers `ok`.\n *\n * A series whose members only WRITE observes nothing, claims nothing, and\n * stays one unit with its parent — which is the rollback above. Two\n * alternatives were falsified: taking no member boundary at all collapses the\n * per-member packaging `post-prep/g29-member-dependency` and\n * `g29-dependency-choices` pin (10 cells), and claiming the boundary at every\n * read rather than a member's splits the unit an ordered observation is\n * stated inside (`g4/parity/ordered-observation.test.ts` \"nothing of the unit\n * commits\", `lax-to-one.test.ts`, 8 cells).\n */\n #executingMember: Member | undefined;\n async executeMember<T>(\n execute: () => Promise<T>,\n member?: Member\n ): Promise<T> {\n const enclosingWrite = this.#attemptStore?.holdsWrite === true;\n const observing = this.#executingMember;\n if (member) this.#executingMember = member;\n try {\n const output = await execute();\n if (this.#ownership !== \"batch-preparation\") {\n if (!enclosingWrite) await this.flush(undefined, member);\n this.#completedMembers++;\n }\n return output;\n } catch (error) {\n throw this.failure(error, \"member\", member);\n } finally {\n this.#executingMember = observing;\n }\n }\n async executeSkippableMember(\n execute: () => Promise<void>,\n rootProducer: object,\n member: Member\n ): Promise<boolean> {\n this.admitsSuppression(\"rows involving nested writes\");\n return this.executeMember(async () => {\n try {\n await this.#withMemberRollback(async () => execute());\n return true;\n } catch (error) {\n if (\n error instanceof UniqueConstraintError &&\n this.rejectedProducer(error) === rootProducer\n )\n return false;\n throw error;\n }\n }, member);\n }\n async #withMemberRollback<T>(\n execute: (driver: AnyDriver) => Promise<T>\n ): Promise<T> {\n const outer = this.#transport;\n const withinRollback = async (transaction: AnyDriver) => {\n this.#transport = transaction;\n try {\n return await execute(transaction);\n } finally {\n this.#transport = outer;\n }\n };\n // One rule: a member rollback opens inside whatever scope the operation is\n // CURRENTLY running in. While the operation holds a region of its own, the\n // caller's grant names the caller's scope, and re-entering it while this\n // nested one is active is the exact `TransactionError: … cannot be used\n // while its nested transaction is active` that note §8.4 measured.\n return this.#memberRollback && !this.#ownRegionOpen\n ? this.#memberRollback(withinRollback, this.attribution)\n : outer.withTransaction(withinRollback, undefined, this.attribution);\n }\n /** Member suppression requires rollback ownership before any provider effects. */\n admitsSuppression(rows: string): true {\n if (\n (this.#ownership === \"borrowed-transaction\" && !this.#memberRollback) ||\n this.usesBatch\n )\n throw new UnsupportedOperationError(\n `skipDuplicates cannot skip ${rows} on driver '${this.driver.driverName}' in this scope; a member savepoint is required.`,\n { meta: { model: this.modelName, operation: this.operation } }\n );\n return true;\n }\n failure(\n error: unknown,\n phase: RecordSeriesProgress[\"phase\"],\n member?: Member\n ): unknown {\n if (\n typeof error === \"object\" &&\n error !== null &&\n this.#answeredFailureSet?.has(error)\n )\n return error;\n let failure = error;\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 failure = new QueryError(\n `The \"${operation}\" result is incompatible with the ${scalarType} scalar domain: ${reason}.`,\n {\n code: VibORMErrorCode.QUERY_RESULT_INVALID,\n meta: { driver, model, operation, scalarType, reason },\n }\n );\n }\n if (\n error instanceof RecursiveOutputOverBudget ||\n error instanceof GatedFieldRefusal\n )\n failure = error.refusal(this.operation, this.modelName);\n const attribution = member\n ? this.#memberAttributionMap?.get(member)\n : undefined;\n // A failure carries record-series progress only when it BELONGS to a record\n // series. A committed segment and a prefix phase are the series the\n // operation already has; an UNCERTAIN outcome is not one on its own, so a\n // set-oriented statement's window ({@link setWindow}) reports nothing while\n // its outcome is merely unknown. That unknown outcome stays internal — the\n // fact itself is unchanged, still gates recovery, and still reaches the\n // cache through the seam `submit` states it on ({@link WriteOutcomeSeam}) —\n // exactly as the shipped executor keeps `progress.mayHaveCommittedSegment`\n // internal for a single operation and rethrows the driver's own error\n // (`write-engine/OperationExecutor.ts:1031-1072`; `attachProgress` :2308\n // reaches only record-series member and invalidation failures).\n // The narrowing is only that arm: a set window whose segment DID commit is\n // a committed segment like any other and keeps publishing its progress,\n // pinned by `tests/raptor3/g4/unit02/malformed-result-cuts.test.ts` cell 1b\n // and `lone-statement-transport.test.ts` row 6.\n const setStatement = member !== undefined && member === this.#setWindow;\n return this.usesBatch &&\n (phase === \"prefix\" ||\n this.#committedSegments > 0 ||\n (this.#mayHaveCommittedSegment && !setStatement))\n ? attachRecordSeriesProgress(failure, {\n atomicity: \"segment\",\n phase,\n committedSegments: this.#committedSegments,\n committedWriteMembers: this.#committedMemberSet?.size ?? 0,\n completedMembers: this.#completedMembers,\n ...(attribution?.path.length ? { memberPath: attribution.path } : {}),\n ...(attribution ? { totalMembers: attribution.totalMembers } : {}),\n ...(this.#mayHaveCommittedSegment\n ? { mayHaveCommittedSegment: this.#mayHaveCommittedSegment }\n : {}),\n })\n : failure;\n }\n /**\n * The operation's own region, or `undefined` when this ownership has none.\n *\n * A standalone operation on a transaction-capable driver owns one\n * transaction. A BORROWED operation owns one only when its caller SAID so, by\n * granting `operationRegion` — which the callback-transaction route supplies\n * because it opened no scope of its own. Without that grant a borrowed\n * operation owns none: its caller's scope is the unit, so every statement\n * runs directly on the borrowed driver and a failing one poisons that scope\n * exactly as the shipped `runStatementAtomic` and `runLinearOn` paths leave\n * it. The `memberRollback` grant is never mistaken for it — it is MEMBER\n * isolation only: `tests/raptor3/g3/suppression-retry-contract.test.ts` pins\n * one savepoint per suppressed member and none for the operation, and\n * `tests/raptor3/g3/scope-composition-native.test.ts` fails outright if this\n * operation opens a second scope on the caller's driver while that grant is\n * the array fallback's (note §8.4, measured).\n * An atomic batch and a batch preparation are already their own unit.\n */\n #region():\n | ((execute: (driver: AnyDriver) => Promise<unknown>) => Promise<unknown>)\n | undefined {\n if (this.usesBatch) return undefined;\n if (this.#ownership === \"borrowed-transaction\") {\n const granted = this.#operationRegion;\n return granted\n ? (execute) => granted(execute, this.attribution)\n : undefined;\n }\n if (this.#ownership !== \"standalone\") return undefined;\n // This transaction is the ONLY place this operation can learn whether its\n // writes became durable, so the client's cache rail is bound to its phases\n // here — the five steps of the shipped `runTransactionScope`\n // (`write-engine/OperationExecutor.ts:1130-1187`), owned by the context\n // because only the context opens the region.\n const attribution = this.#writeOutcome\n ? bindExecutionTransactionPhases(this.attribution, {\n readyToCommit: () => {\n this.#regionPhase = \"ready\";\n },\n committed: () => {\n this.#regionPhase = \"committed\";\n },\n })\n : this.attribution;\n return (execute) =>\n this.driver.withTransaction(execute, undefined, attribution);\n }\n /** How far the region this operation opened got, as its driver reported it. */\n #regionPhase: \"pending\" | \"ready\" | \"committed\" = \"pending\";\n #openRegionPhase(): void {\n this.#regionPhase = \"pending\";\n }\n /** Run the operation inside the one region it owns. */\n async #withinRegion<T>(\n region: (\n execute: (driver: AnyDriver) => Promise<unknown>\n ) => Promise<unknown>,\n body: () => Promise<T>\n ): Promise<T> {\n this.#openRegionPhase();\n let value: T;\n try {\n value = (await region(async (transaction) => {\n this.#transport = transaction;\n this.#ownRegionOpen = true;\n try {\n return await body();\n } finally {\n this.#transport = this.driver;\n this.#ownRegionOpen = false;\n }\n })) as T;\n } catch (error) {\n // The phase the region REACHED is the certainty: a driver that never\n // separated commit from success reports none, and this operation then\n // says nothing rather than guessing.\n const certainty =\n this.#regionPhase === \"committed\"\n ? \"committed\"\n : this.#regionPhase === \"ready\"\n ? \"may-have-committed\"\n : undefined;\n if (!certainty) throw error;\n const primary = isVibORMError(error)\n ? attachCommitCertainty(error, certainty)\n : error;\n await this.#stateWriteOutcome(\n this.#regionPhase === \"committed\"\n ? this.#writeOutcome?.committedSegment\n : this.#writeOutcome?.mayBeVisible,\n primary\n );\n throw primary;\n }\n await this.#stateWriteOutcome(this.#writeOutcome?.committedSegment);\n return value;\n }\n /**\n * ONE rule for the physical envelope: it opens at the first statement that is\n * not the operation's only statement.\n *\n * An operation that reaches its terminal statement having issued no other runs\n * that statement directly — no BEGIN/COMMIT standalone, no savepoint inside a\n * borrowed transaction — which is the shipped `runStatementAtomic` condition\n * (empty planning, exactly one non-guard step: `OperationExecutor.ts`\n * `compileSingleStatementCandidate` + `canExecuteDirectly`) restated in this\n * engine's vocabulary. Any other operation raises {@link requiresEnvelope}\n * BEFORE its first round trip, and the body runs again inside the region;\n * nothing has reached the provider at that point.\n *\n * `single` is the constructed plan's ADMISSIBILITY, not its count\n * (`Commands.plan`): a form whose shape rules one statement out never enters\n * the deferred state, so it opens its region immediately and is constructed\n * exactly once. Every other form is admitted optimistically and the COUNT is\n * answered here, by the construction itself — which is why the rule can be\n * stated in one place and still be the operative decision. `createMany` is\n * the shape that makes the difference observable, and the observable split is\n * the BIND BUDGET, not the spelling of the rows: `schema.scalars` normalizes\n * every row to one column set first, so rows presenting different keys are\n * still one grouped INSERT with no envelope (measured — review follow-up N2),\n * while a batch whose placeholders exceed the provider's limit is constructed\n * twice and raises the sentinel exactly once\n * (`g4/unit02/physical-envelope.test.ts`: 2 statements, 1 transaction,\n * every row written once).\n */\n async run<T>(body: () => Promise<T>, single = false): Promise<T> {\n if (\n !(\n this.#ownership === \"batch-preparation\" ||\n isReadOperation(this.operation)\n )\n )\n return await this.#runWrite(body, single);\n try {\n return await body();\n } catch (error) {\n throw this.#runFailure(error);\n }\n }\n /** A write's envelope, out of line from reads, which need none. */\n async #runWrite<T>(body: () => Promise<T>, single: boolean): Promise<T> {\n try {\n if (!single) this.#requireAtomicUnit();\n const region = this.#region();\n if (!region) return await this.#batchAttempt(body);\n if (!single) return await this.#regionAttempt(region, body);\n this.#envelope = \"deferred\";\n try {\n return await body();\n } catch (error) {\n if (error !== this.requiresEnvelope) throw error;\n }\n this.#restart();\n return await this.#regionAttempt(region, body);\n } catch (error) {\n throw this.#runFailure(error);\n }\n }\n /** What {@link run} raises for a failure of its body. */\n #runFailure(error: unknown): unknown {\n // A record series is a COMMITTED SEGMENT of this operation's own writes,\n // and nothing else asked here: a generated-output continuation is\n // declared behind the segment that published the identity it re-pins\n // ({@link insert}), so that segment is already counted, while a premise —\n // the parent a membership correlates on — is declared ahead of every\n // segment and is not a member of any series. Asking about continuations\n // instead published a series' progress for an ordinary UPDATE that had\n // committed nothing (`tests/raptor3/g2-transport.test.ts`, \"An ordinary\n // UPDATE must retain only acknowledged progress\").\n const decoding =\n error instanceof InvalidScalarResult ||\n error instanceof RecursiveOutputOverBudget ||\n error instanceof GatedFieldRefusal;\n if (decoding || (this.usesBatch && this.#committedSegments > 0))\n return this.failure(error, decoding ? \"result\" : \"member\");\n return error;\n }\n /**\n * The pre-dispatch capability gate, on the construction path and before the\n * operation's FIRST statement — the position of the shipped\n * `assertRoutedAtomicResolution` (`write-engine/routing.ts:104-164`).\n *\n * A form the physical-envelope rule has already ruled out of ONE statement\n * needs an atomic unit. A driver with neither transactions nor batch has\n * none, and a batch-only driver that cannot RETURN cannot resolve a\n * single-row mutation's identity inside its own unit — its public result is\n * parsed after the batch commits and that parse cannot be rolled back. Both\n * are one class and one `meta`, and neither reaches the provider: the\n * decision read of an `upsert` used to dispatch first and surface the\n * provider's own error instead of this refusal.\n */\n #requireAtomicUnit(): void {\n if (this.#ownership !== \"standalone\") return;\n const driver = this.driver;\n const meta = { driver: driver.driverName, operation: this.operation };\n if (!(driver.supportsTransactions || driver.supportsBatch))\n throw new TransactionError(\n `Driver \"${driver.driverName}\" supports neither transactions nor atomic batch execution.`,\n { meta }\n );\n if (\n driver.supportsBatch &&\n !driver.supportsTransactions &&\n !driver.adapter.capabilities.supportsReturning &&\n ATOMIC_RESOLUTION_OPERATIONS.has(this.operation)\n )\n throw new TransactionError(\n this.operation === \"upsert\"\n ? \"cannot execute non-returning upsert writes atomically because public result parsing cannot be rolled back after an atomic batch commits\"\n : `Driver '${driver.driverName}' cannot execute '${this.operation}' because public result parsing cannot be rolled back.`,\n { meta }\n );\n }\n /**\n * Every provider round trip crosses here, so the envelope rule has exactly one\n * site. `terminal` marks the operation's result-publishing transport, which is\n * followed by nothing.\n */\n private dispatch<T>(\n statements: number,\n terminal: boolean,\n execute: () => Promise<T>\n ): Promise<T> {\n try {\n if (this.#envelope === \"deferred\") {\n if (!(terminal && statements === 1 && this.#performed === 0))\n throw this.requiresEnvelope;\n this.#envelope = \"statement\";\n }\n this.#performed += statements;\n return execute();\n } catch (error) {\n return Promise.reject(error);\n }\n }\n /** Discard the un-executed plan so the body can be constructed again. */\n #restart(attempt = new TransportAttempt()): void {\n this.#attemptStore = attempt;\n this.#continuationList = undefined;\n this.#vacatedMemberships = undefined;\n this.#memberAdmissionStarted = false;\n this.#envelope = \"open\";\n }\n /**\n * The command interpreter's ONE replacement of both attempt regions, held by\n * the owner that opens the region so it can spend the recovery allowance\n * without knowing how a command attempt is built. It answers the replacement\n * transport region once, and `undefined` ever after.\n */\n attachRecovery(\n replace: () => TransportAttempt | undefined,\n acceptsInsert: (error: unknown) => boolean\n ): void {\n this.#replaceAttempt = replace;\n this.#acceptInsertRecovery = acceptsInsert;\n }\n #replaceAttempt: (() => TransportAttempt | undefined) | undefined;\n #acceptInsertRecovery: ((error: unknown) => boolean) | undefined;\n #recoverySpent = false;\n /**\n * The ONE recovery allowance, spent here and nowhere else.\n *\n * The interpreter owns HOW both attempt regions are replaced; this owner\n * states WHETHER they may be, because a recovery is a fact about the\n * operation, not about the interpreter that happens to be running it: a\n * re-plan builds a NEW interpreter (D-25), and a fresh interpreter must not\n * bring a fresh allowance with it.\n */\n spendRecovery(): TransportAttempt | undefined {\n if (this.#recoverySpent) return undefined;\n const replacement = this.#replaceAttempt?.();\n if (!replacement) return undefined;\n this.#recoverySpent = true;\n return replacement;\n }\n /**\n * May a replacement attempt replay IN PLACE?\n *\n * Only where this operation opened no region of its own. A region the\n * rejection aborted answers no further statement, so there the recovery is\n * {@link run}'s — a FRESH region — and never a replay inside the failed one.\n */\n get replaysInPlace(): boolean {\n return this.#ownership === \"standalone\" && !this.#ownRegionOpen;\n }\n /**\n * The operation's region, and the ONE recovery allowance that belongs to the\n * owner that opens it.\n *\n * A lost create race destroys the region it was rejected in, so the recovery\n * cannot be a replay inside it: it is a fresh region running the same body,\n * which is exactly what the shipped `executeRoutedOperation` did\n * (`write-engine/routing.ts:180-208`, \"Re-planning re-reads committed state,\n * so the loser now takes its adopt arm and converges\"). The attribution and\n * the correlation id are this operation's own and do not change;\n * {@link recoveryRejection} has already answered that nothing was\n * acknowledged, and the interpreter answers the allowance exactly once.\n */\n async #regionAttempt<T>(\n region: (\n execute: (driver: AnyDriver) => Promise<unknown>\n ) => Promise<unknown>,\n body: () => Promise<T>\n ): Promise<T> {\n try {\n return await this.#withinRegion(region, body);\n } catch (error) {\n if (\n this.recoveryRejection(error)?.kind !== \"insert\" ||\n !this.#acceptInsertRecovery?.(error)\n )\n throw error;\n const replacement = this.spendRecovery();\n if (!replacement) throw error;\n this.#restart(replacement);\n return await this.#withinRegion(region, body);\n }\n }\n /**\n * The batch route's own recovery: ONE re-plan, from the admitted values.\n *\n * A raceable atomic assertion aborted the whole unit before anything was\n * acknowledged, so this operation may be planned again — and it must be\n * planned AGAIN rather than replayed, because the tree that ran carries the\n * members it captured and a series occurrence is expanded exactly once. The\n * body re-derives the occurrence tree from the same ADMITTED arguments\n * (`commands/index.ts`), so nothing is re-validated and no transform runs\n * twice (rule 10), and the fresh plan-time read sees the committed state the\n * race produced and converges (Arnaud's D-25).\n *\n * An INSERT rejection is not this arm's: with no region open the interpreter\n * adopts the winner's row in place ({@link replaysInPlace}), which keeps \"a\n * missing winner never authorises a new INSERT\" where it is decided.\n */\n async #batchAttempt<T>(body: () => Promise<T>): Promise<T> {\n try {\n return await body();\n } catch (error) {\n if (this.recoveryRejection(error)?.kind !== \"assertion\") throw error;\n const replacement = this.spendRecovery();\n if (!replacement) throw error;\n this.#restart(replacement);\n return await body();\n }\n }\n /**\n * The ONE sanctioned direct read at array-route preparation: the upsert\n * locate of {@link CommandPlanner.rootUpsert}'s probe-first path (D-46),\n * whose answer the arm's packaged premise re-asserts inside the batch. Every\n * other read keeps {@link read}'s refusal there, terminal or not: the\n * interpreter's planning reads would run before the earlier members of the\n * same array have executed and answer a false absence — measured by the\n * unit's review (a `connect` to a row an earlier member inserts).\n */\n async planningLocate(query: Query, model: AnyModel): Promise<Input[]> {\n const response = await this.answer(query, false, model);\n return this.queries.decodeQuery(query, response.rows, true);\n }\n /**\n * One read. `model` is the model the statement addresses when that is not the\n * operation's own — a nested locate names the nested record, exactly as the\n * shipped executor's per-step derivation does ({@link statementContext}).\n */\n async read(\n query: Query,\n internal = false,\n terminal = false,\n model?: AnyModel\n ): Promise<Input[]> {\n if (this.#ownership === \"batch-preparation\") {\n throw this.incompletePreparation;\n }\n const response = await this.answer(query, terminal, model);\n return this.queries.decodeQuery(query, response.rows, internal);\n }\n /**\n * One statement's raw provider answer. The dispatcher both readers share, so\n * the terminal boundary ({@link publishedTerminal}) sees the rows the\n * provider handed back and an internal read sees the same rows decoded.\n *\n * It is also the ONE place this operation reads from OUTSIDE its own queue,\n * so it is where a member claims the boundary {@link executeMember} deferred:\n * a statement answered here cannot see a write the queue still holds. Only a\n * member claims it, and only for a write some OTHER record of the series left\n * waiting ({@link TransportAttempt.holdsOtherMemberWrite}). A read taken\n * outside every member is the record's OWN observation, and where it stands\n * relative to this unit's writes is the dependency pass's answer, not this\n * one's — an ordered observation is stated INSIDE the queued unit on purpose\n * (N1), and a boundary taken under it would commit the very writes its\n * premise exists to abort.\n */\n private async answer(\n query: Query,\n terminal: boolean,\n model?: AnyModel\n ): Promise<QueryResult<Input>> {\n const observer = this.#executingMember;\n if (observer && this.#attemptStore?.holdsOtherMemberWrite(observer))\n await this.flush();\n const context = model\n ? this.statementContext(model, this.operation)\n : this.attribution;\n return this.dispatch(1, terminal, () =>\n this.#transport._execute<Input>(query.sql, context)\n );\n }\n /**\n * The operation's ONE result boundary: the raw rows one projection answered,\n * decoded through the driver's `parseResult` middleware and then the\n * adapter's ({@link Queries.decodeResult}, Arnaud's D-28).\n *\n * Asked once per operation by each route's publisher and never per member or\n * per statement: a publication split across several windows is a BIND-BUDGET\n * split of ONE projection, so the middleware is asked about the operation's\n * rows and the operation has one result whatever the provider's limit was. A\n * set mutation that publishes an affected-row COUNT instead of rows is not\n * asked at all: a row count is a fact of the transport, not a result window.\n */\n private publishedProjection(shape: ProjectionShape, rows: Input[]): Input[] {\n return this.queries.decodeResult(rows, this.operation, (raw) =>\n this.queries.decodeProjection(shape, raw)\n );\n }\n /**\n * The terminal boundary: one window per terminal statement, in dispatch\n * order, published as ONE result ({@link publishedProjection}).\n *\n * Every window of a terminal carries the same SHAPE ({@link seriesQueries}\n * hands each chunk `prepared.shape`), and none of them carries the\n * operation's row count: {@link Queries.selectSeries} stamps each window\n * with its own identity count and its own registered refusal. So that fact\n * is decided per window, on the rows the PROVIDER answered, before the\n * middleware is asked anything — a total over the concatenation would\n * compare a whole terminal with one window's count, and a middleware that\n * legitimately replaces the operation's rows must not be judged against a\n * physical window count at all.\n */\n private publishedTerminal(\n queries: readonly Query[],\n windows: readonly Input[][]\n ): Input[] {\n const terminal = queries[0];\n if (!terminal) return [];\n for (const [index, statement] of queries.entries())\n this.queries.assertExpectedRows(statement, windows[index]!.length);\n return this.publishedProjection(\n terminal.shape,\n windows.length === 1 ? windows[0]! : windows.flat()\n );\n }\n /**\n * One read's published result, live or packaged. A prepared read is one\n * statement plus the operation's own cardinality decision; packaging queues\n * that exact statement and installs the SAME decoder and cardinality as the\n * package's parser, so a read member is statically packageable and no second\n * projection or decoder exists (g4/unit03/note.md D-2).\n */\n async publish(read: Read, missing?: () => Error): Promise<unknown> {\n if (this.#ownership === \"batch-preparation\")\n return this.publishPrepared(read, missing);\n const positional =\n this.#ownership === \"standalone\" && read.value.kind === \"collection\"\n ? resolvePositionalResultDriver(this.#transport)\n : undefined;\n if (positional) return this.#publishPositional(read, missing, positional);\n const response = await this.answer(read.query, true);\n return this.#decideRead(\n read,\n missing,\n this.publishedTerminal([read.query], [response.rows])\n );\n }\n /** A collection read over the positional transport, out of line. */\n async #publishPositional(\n read: Read,\n missing: (() => Error) | undefined,\n positional: NonNullable<ReturnType<typeof resolvePositionalResultDriver>>\n ): Promise<unknown> {\n const response = await this.dispatch(1, true, () =>\n positional(read.query.sql, this.attribution)\n );\n if (\n response.kind === \"positional\" &&\n resolvePositionalResultDriver(this.#transport) === positional\n ) {\n this.queries.assertExpectedRows(read.query, response.rows.length);\n return this.#decideRead(\n read,\n missing,\n this.queries.decodeProjection(\n read.query.shape,\n response.rows,\n false,\n response.columns\n )\n );\n }\n const borrowed =\n response.kind === \"borrowed\"\n ? response.result\n : borrowPositionalResult(response);\n return this.#decideRead(\n read,\n missing,\n this.publishedTerminal([read.query], [borrowed.rows.map(record)])\n );\n }\n /**\n * The batch-preparation arm of {@link publish}: queue this read's ONE\n * statement and state the parser for its one result. It reaches no driver,\n * so the package {@link preparedBatch} publishes is complete the moment this\n * returns — which is what lets a caller ask for a read's single prepared\n * query synchronously.\n */\n publishPrepared(read: Read, missing?: () => Error): undefined {\n const resultIndex = this.queued.length;\n this.#queue(read.query.sql);\n this.#preparedParser = (results) => {\n const response = results[resultIndex];\n if (!response)\n throw new TransactionError(\n `Driver '${this.driver.driverName}' omitted the prepared result for operation '${this.operation}'.`,\n { meta: this.#errorMeta }\n );\n return this.#decideRead(\n read,\n missing,\n this.publishedTerminal([read.query], [response.rows.map(record)])\n );\n };\n return undefined;\n }\n #decideRead(\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 async flush(\n query?: Query,\n member?: Member,\n premise?: ObservationPremise\n ): Promise<Input[]>;\n async flush(queries: Query[], member?: Member): Promise<Input[][]>;\n async flush(\n query?: Query | Query[],\n member?: Member,\n premise?: ObservationPremise\n ): Promise<Input[] | Input[][]> {\n const projections = Array.isArray(query) ? query : query ? [query] : [];\n // Arnaud's D-29, stated where planning reads become batches. A planning\n // read is not the operation's atomic unit: it carries no premise of its\n // own, and it must not turn the unit's premises into a batch that runs\n // BEFORE the write they protect — which is exactly what closes the window\n // a staleness premise exists for before the write opens it. So the unit's\n // waiting premises step aside here, and the read travels with the unit\n // only while the unit is being dispatched anyway (the values it reads are\n // the ones those statements produce). With nothing else waiting it is what\n // it is: a read, through the one owner of reads.\n //\n // An ordered observation (N1) is the other caller: a read the queued unit's\n // own writes can answer. The trailing premises step aside for it exactly as\n // for a planning read — they protect writes not yet queued — while the\n // premises stated before the queued writes ride with them. Its `premise`\n // (the row the consumer needs, or no row outside its membership) is\n // asserted inside the same batch, behind the writes and ahead of the read,\n // so a target that is not what the consumer needs aborts the batch before\n // anything commits.\n // Stated once, for every boundary this owner takes: a read follows each of\n // them — the projections below, or the caller's own read outside the queue\n // — so the waiting premises step aside whatever the caller passes. It used\n // to be asked of the projection list, which made the rule depend on the\n // caller's shape: the `choose` arm carried its own reference read-back\n // until D-58 moved that to the boundary, and the rule must not change with\n // it. Measured inert on the packaging pins either way.\n this.#attemptStore?.withholdPremises();\n try {\n if (!this.usesBatch || this.queued.length === 0) {\n // Nothing queued to ride with: an ABSENCE premise (no row outside the\n // membership) is checked here, at the observation, by its own read —\n // never left to a batch that will not run. A PRESENCE premise is the\n // observation itself: its query is the projection, and an empty answer\n // is the absence its consumer refuses.\n if (\n premise &&\n !premise.present &&\n (await this.read(premise.query, true)).length > 0\n )\n throw premise.failure();\n const rows: Input[][] = [];\n for (const projection of projections)\n rows.push(await this.read(projection, true));\n return Array.isArray(query) ? rows : (rows[0] ?? []);\n }\n return await this.#flushQueued(projections, query, member, premise);\n } finally {\n this.#attemptStore?.restorePremises();\n }\n }\n async #flushQueued(\n projections: Query[],\n query: Query | Query[] | undefined,\n member?: Member,\n premise?: ObservationPremise\n ): Promise<Input[] | Input[][]> {\n if (premise?.present) this.requirePresent(premise.query, premise.failure());\n else if (premise)\n await this.requireAbsent(premise.query, premise.failure());\n const resultIndex = this.queued.length;\n for (const projection of projections) this.#queue(projection.sql);\n const responses = await this.submit(false, member);\n return this.settleSubmitted(() => {\n try {\n const rows = projections.map((projection, index) =>\n this.queries.decodeQuery(\n projection,\n responses[resultIndex + index]!.rows,\n true\n )\n );\n return Array.isArray(query) ? rows : (rows[0] ?? []);\n } catch (error) {\n throw this.failure(error, \"result\", member);\n }\n });\n }\n async requireAbsent(query: Query, failure: Error): Promise<void> {\n if (this.usesBatch) {\n this.statePremise(query, false, failure);\n return;\n }\n if ((await this.read(query, true)).length) throw failure;\n }\n requirePresent(query: Query, failure: Error): void {\n this.statePremise(query, true, failure);\n }\n /**\n * Does this statement ask about a value THIS unit produced?\n *\n * It binds this UNIT's batch reference, so it reads the scratch through it,\n * and the rolled-back transaction takes that scratch with it: the attribution\n * ladder cannot ask it again ({@link submit}). Both halves of the fact — the\n * reference's identity and the statement that reads it — are here and only\n * here, for the premises {@link statePremise} states AND for the continuation\n * guards {@link submit} builds. Since D-58 only a premise stated INSIDE the\n * unit that made the scratch can bind it — a guard rides a LATER segment, and\n * the value it re-pins crossed that boundary as a literal — so the guard is\n * still DERIVED here rather than asserted to read nothing, which is what\n * keeps the two halves of the fact in one place.\n */\n #readsBatchReference(query: Query): boolean {\n const reference = this.#attemptStore?.scratchId;\n return reference !== undefined && query.sql.values.includes(reference);\n }\n /** Queue one premise's assertion and record what it requires of the batch. */\n private statePremise(query: Query, present: boolean, failure: Error): void {\n const assertions = this.driver.adapter.assertions;\n this.#attempt.assertPremise(\n this.#queue(\n present ? assertions.exists(query.sql) : assertions.notExists(query.sql)\n ),\n {\n query,\n present,\n failure,\n readsBatchReference: this.#readsBatchReference(query),\n }\n );\n }\n private async submit(publishingGeneratedOutput = false, member?: Member) {\n if (this.#ownership === \"batch-preparation\") {\n throw this.incompletePreparation;\n }\n const attempt = this.#attempt;\n this.#atomicAssertionRejection = undefined;\n attempt.rejectedInsert = undefined;\n const precedingSegments = this.#committedSegments;\n const declared = this.#continuationList;\n const continuations = declared\n ? declared.filter((continuation) => !continuation.declaring)\n : NO_CONTINUATIONS;\n if (declared)\n for (const continuation of declared) continuation.declaring = false;\n // A guard's query is STATED here, where the guard is built: it re-pins a\n // row an EARLIER segment wrote, and a value that segment produced reached\n // this one as a literal (D-58), so a query stated at declaration time would\n // name a scratch that no longer exists. The premise it raises is derived at\n // the same point, while this unit's scratch is still the one in hand.\n const guards = continuations.map((continuation) => {\n const query = (continuation.query ??= continuation.state());\n const context = this.statementContext(continuation.model, this.operation);\n return {\n statement: {\n ...this.#transport._prepare(\n this.driver.adapter.assertions.exists(query.sql),\n context\n ),\n context,\n },\n premise: {\n query,\n present: true,\n failure: continuation.failure(),\n readsBatchReference: this.#readsBatchReference(query),\n },\n };\n });\n // D-58: this unit's scratch ends with this unit. Every value it stored is\n // read back inside the same batch, at its end, and the table is dropped\n // with the unit that made it — so the next unit binds LITERALS and creates\n // its own scratch for whatever it produces itself.\n const carryIndex = guards.length + attempt.pending.length;\n const carried = this.#carryScratch();\n this.closeScratch();\n const statements = [\n ...guards.map((guard) => guard.statement),\n ...attempt.pending.splice(0),\n ];\n const insertProducers = attempt.drainInsertProducers();\n const assertionFailures = attempt.drainAssertedPremises();\n const judgedWrites = attempt.drainJudgedWrites();\n for (const { statement, premise } of guards)\n assertionFailures.set(statement, premise);\n const members = attempt.drainMembers();\n const acknowledged = async () => {\n if (members.length === 0) return;\n this.#committedSegments++;\n const committed = (this.#committedMemberSet ??= new Set());\n for (const member of members) committed.add(member);\n // This transport acknowledges before it has decoded anything, so the\n // listener's failure is HELD rather than thrown: the operation's own\n // answer is still to come, and it stays primary if it fails too\n // ({@link heldOutcomeFailure}, released by {@link settleSubmitted}).\n try {\n await this.#writeOutcome?.committedSegment?.();\n } catch (failure) {\n this.heldOutcomeFailure = { failure };\n }\n };\n let responses: QueryResult<Input>[];\n try {\n responses = await this.dispatch(statements.length, false, () =>\n this.#transport._executeBatch<Input>(\n statements,\n undefined,\n this.attribution,\n this.driver.supportsOrderedCommittedSegments\n ? acknowledged\n : undefined\n )\n );\n if (!this.driver.supportsOrderedCommittedSegments) await acknowledged();\n } catch (error) {\n // A listener that failed while this batch acknowledged is composed with\n // the batch's own failure, which stays primary, and the uncertain-outcome\n // arm below is not reached: a segment that acknowledged is known to have\n // committed. Shipped states both at the same point of its own catch\n // (`write-engine/OperationExecutor.ts:1306-1309`).\n const acknowledgedOutcomeFailure = this.heldOutcomeFailure;\n this.heldOutcomeFailure = undefined;\n if (acknowledgedOutcomeFailure)\n throw this.#answered(\n retainWriteOutcomeFailure(error, acknowledgedOutcomeFailure.failure)\n );\n // Atomic rejection is retryable only with exact effect attribution and a\n // direct provider cause. Cleanup aggregation retains an extra cause link.\n // And only while no dynamic member has been admitted: THIS route's\n // recovery is the interpreter's in-place REPLAY of the tree that ran\n // ({@link replaysInPlace}, the only arm reachable where the operation\n // opened no region), which a dynamically admitted member makes impossible\n // — its defaults and transforms already ran once against a row this\n // attempt read, and admitted values are never produced twice (rule 10).\n // The bound belongs to the site that RECORDS the producer, which is why\n // {@link recoveryRejection} asks about attribution and progress alone.\n // The non-batch attribution in {@link insert} carries no such bound: the\n // recovery IT feeds re-enters a fresh region with a fresh plan (D-25).\n if (\n this.driver.supportsBatch &&\n !this.#committedProgress &&\n !this.#memberAdmissionStarted &&\n error instanceof UniqueConstraintError &&\n error.meta.commitCertainty === undefined &&\n error.originalCause &&\n error.originalCause.cause === undefined &&\n typeof error.meta.statementIndex === \"number\"\n ) {\n const producer = insertProducers.get(\n statements[error.meta.statementIndex]!\n );\n if (producer) attempt.rejectedInsert = { error, producer };\n }\n // A weak native batch cannot prove rollback merely by rejecting after\n // dispatch — but a batch that rejected AT A PREMISE, with nothing but\n // premises ahead of it, dispatched no write at all, and the provider said\n // where it stopped. There is nothing to roll back and nothing to be\n // uncertain about. It is the companion of Arnaud's D-29: a premise now\n // rides the unit it protects, so a unit that loses its race rejects at\n // the premise, ahead of its own first write. A rejection at a WRITE keeps\n // the uncertainty it always had, whatever its position\n // (`g4/unit02/uncertain-outcome-meta.test.ts` cell 2).\n // And it is asked only where it can DECIDE the allowance. An operation\n // that has already acknowledged a segment is refused its recovery by\n // progress alone (D-25), so the proof could buy it nothing — while the\n // uncertainty such an operation reports for a LATER batch is a separate\n // registered fact (`transitions/staleness-live-pg.ts`\n // `g2-pg-series-parent-reference-reused`: \"the acknowledged prefix and\n // weak native dispatch uncertainty are distinct facts\").\n let failure: Error | undefined;\n let attributedIndex: number | undefined;\n if (error instanceof NestedWriteAssertionError) {\n const statementIndex = error.meta.statementIndex;\n if (typeof statementIndex === \"number\") {\n const statement = statements[statementIndex]!;\n failure =\n assertionFailures.get(statement)?.failure ??\n judgedWrites.get(statement)?.refusal;\n attributedIndex = statementIndex;\n } else {\n // Fresh-state diagnostics after rollback refine the error, not its\n // original statement index: a premise found false NOW may have held\n // when the batch ran (state moved on between the abort and the\n // re-probe, DESIGN §7.3 step 4), so the position they name is a\n // sentence, and the position claim below is bounded by the LAST\n // premise instead. An unindexed native failure identifies our sole\n // guard only when ordinary SQL cannot collide with it.\n const mayCollide = batchMayContainAssertionCollision(\n statements,\n this.driver.dialect\n );\n const soleGuard =\n assertionFailures.size + judgedWrites.size === 1 && !mayCollide;\n\n // A premise about a value this unit PRODUCED is not re-probable at\n // all (the guide, \"At the ladder, a premise stated BEHIND the unit's\n // own writes … is not re-probable after the rollback\"): it reads the\n // batch reference scratch, which the rolled-back transaction took\n // with it, so the statement would raise an undefined-table error\n // where the ladder owes an attribution. The inference below is that\n // premise's whole answer, and the ladder does not ask it. Every other\n // premise is asked, because the position it holds is not the fact —\n // a unit that states two premises behind its first write keeps the\n // correlated identity of the one the re-probe contradicts (N1,\n // `g4/parity/ordered-observation.test.ts`).\n for (const [index, statement] of statements.entries()) {\n const assertion = assertionFailures.get(statement);\n if (failure || !assertion || assertion.readsBatchReference)\n continue;\n const present = (await this.read(assertion.query, true)).length > 0;\n if (present !== assertion.present || soleGuard) {\n failure = assertion.failure;\n attributedIndex = index;\n break;\n }\n }\n // A premise stated BEHIND the unit's own writes may be about what\n // those writes did (an ordered observation's requirement, N1); the\n // rollback that preceded the re-probe undid them, so its answer now\n // says nothing about the abort. When every premise ahead of the\n // writes holds now and exactly one premise stands behind them, that\n // one is the only candidate the re-probe could not clear — the sole\n // guard's inference, applied to the one premise the rollback hides.\n if (failure === undefined && !mayCollide) {\n const firstWrite = statements.findIndex(\n (statement) => !assertionFailures.has(statement)\n );\n const blind = [...statements.entries()].filter(\n ([index, statement]) =>\n firstWrite >= 0 &&\n index > firstWrite &&\n assertionFailures.has(statement)\n );\n if (blind.length === 1) {\n const [index, statement] = blind[0]!;\n failure = assertionFailures.get(statement)!.failure;\n attributedIndex = index;\n }\n }\n // Every premise holds now: a write that judged the row it\n // produces failed on its own assertion, before it wrote. The one\n // such write is it; of several, the first whose rows, read again\n // from the values it wrote, are refused now (the batch ran them in\n // order and stopped at the refusal). A write reading this unit's\n // scratch is not asked again: the rollback took the scratch.\n if (failure === undefined && !mayCollide) {\n if (judgedWrites.size === 1)\n for (const [statement, judged] of judgedWrites) {\n failure = judged.refusal;\n attributedIndex = statements.indexOf(statement);\n }\n else\n for (const [index, statement] of statements.entries()) {\n const probe = judgedWrites.get(statement)?.probe;\n if (probe === undefined) continue;\n try {\n await this.#transport._execute(probe, this.attribution);\n } catch (refused) {\n if (!(refused instanceof NestedWriteAssertionError))\n throw refused;\n failure = judgedWrites.get(statement)!.refusal;\n attributedIndex = index;\n break;\n }\n }\n }\n }\n }\n const providerIndex =\n isVibORMError(error) && typeof error.meta.statementIndex === \"number\"\n ? error.meta.statementIndex\n : undefined;\n const rejectedIndex = providerIndex ?? attributedIndex;\n // Where the provider said where it stopped, that is the position. Where\n // only the re-probe did, the claim \"nothing but premises ahead\" must hold\n // for ANY premise that could have fired — the last one in the batch — so\n // a batch whose own committed write falsified an earlier premise is never\n // read as having dispatched no write. What the bound cannot see is an\n // ordinary statement arriving as the assertion class BEHIND the last\n // premise, with writes dispatched ahead of it: on the shipped index-free\n // transports (D1, Neon) the batch is atomic, so nothing survives that\n // abort; a transport that is neither atomic nor indexed owes its own\n // witness (D-53) before the claim is made there.\n let positionBound = rejectedIndex;\n if (providerIndex === undefined && typeof attributedIndex === \"number\") {\n let last = -1;\n for (const [index, statement] of statements.entries())\n if (assertionFailures.has(statement) || judgedWrites.has(statement))\n last = index;\n positionBound = last;\n }\n const rejectedBeforeAnyWrite =\n typeof rejectedIndex === \"number\" &&\n typeof positionBound === \"number\" &&\n this.#committedSegments === 0 &&\n statements.every(\n (statement, index) =>\n index > positionBound ||\n assertionFailures.has(statement) ||\n (index === rejectedIndex && judgedWrites.has(statement))\n );\n if (\n members.length > 0 &&\n !rejectedBeforeAnyWrite &&\n !this.driver.supportsOrderedCommittedSegments &&\n this.#committedSegments === precedingSegments &&\n !(error instanceof UniqueConstraintError)\n ) {\n this.#mayHaveCommittedSegment = true;\n // Said where it is learned and BEFORE the failure is attributed or\n // published, which is the shipped order (`OperationExecutor.ts:1050-1058`\n // sets the same internal flag, notifies, and only then rethrows).\n // Whether the meta reports it is a separate question, answered once in\n // `failure()`; whether the listener's own failure may replace this\n // operation's is answered once in {@link stateWriteOutcome}.\n await this.#stateWriteOutcome(this.#writeOutcome?.mayBeVisible, error);\n }\n let attributedError = error;\n if (failure && error instanceof NestedWriteAssertionError) {\n attributedError = failure;\n if (\n this.driver.supportsBatch &&\n !this.#committedProgress &&\n error.meta.commitCertainty === undefined &&\n // Only a premise its own owner declared RACEABLE may be answered by\n // another attempt. The mark is the estate's existing rule for\n // exactly this question (\"the `raceable` mark is what lets the\n // routed retry re-plan and converge\", `batch-error-attribution.ts`;\n // `errors/base.ts` \"the retry layer … re-runs the SPECIFIC raceable\n // ones by their own marking\"), and it is fixed by the guard's\n // premise class (`query-engine/types.ts`). A non-raceable premise —\n // the captured row's own presence — is a statement about IDENTITY:\n // re-planning it would retry against whatever row now answers the\n // selector, which is the one thing a captured-row replacement must\n // not do (`docs/architecture/retired/write-engine-ATOM.md` §\"A conditional-skip batch arm\",\n // `transitions/conditional-upsert.ts` \"Captured-row replacement or\n // deletion must not permit a retry against another identity\").\n isVibORMError(failure) &&\n failure.meta.raceable === true\n )\n this.#atomicAssertionRejection = failure;\n } else if (error instanceof NestedWriteAssertionError) {\n // The un-attributable floor (N3a, the shipped `batch-error-attribution`\n // floor): a batch assertion the ladder cannot attribute surfaces as\n // the typed, non-raceable NestedWriteError carrying the assertion code\n // — never the driver-mapped internal class, never a retry.\n attributedError = new NestedWriteError(\n NESTED_WRITE_ASSERTION_FLOOR_MESSAGE,\n \"\",\n {\n code: VibORMErrorCode.NESTED_WRITE_ASSERTION_FAILED,\n cause: error,\n }\n );\n }\n // The same fact at the dispatch that fails: this submission belongs to a\n // record series when it PUBLISHED generated output, or when it carried a\n // continuation guard — a guard rides only a segment AFTER the one that\n // wrote what it re-pins, so its presence is the committed prefix itself.\n // A continuation still being declared carries no guard and says nothing.\n throw publishingGeneratedOutput || continuations.length > 0\n ? this.failure(\n attributedError,\n this.#committedSegments > precedingSegments ? \"result\" : \"member\",\n member\n )\n : attributedError;\n }\n // The batch ANSWERED. A value this unit carries across its boundary is\n // decoded here, outside the transport's own catch: the statements all ran,\n // so a value the provider malformed is this operation's RESULT failure —\n // the same answer the terminal read gives for the same row — and never a\n // rejection of the unit that wrote it (D-58).\n //\n // It is the ONE throw that leaves a dispatch that SUCCEEDED, so it releases\n // the hold itself, exactly as the dispatch-failure arm above does: a\n // listener failure this batch HELD while it acknowledged would otherwise\n // reach no one — {@link settleSubmitted} captures the hold at its own entry,\n // which is after `submit` has already returned. The operation's own failure\n // stays primary, with the listener's retained beside it.\n try {\n for (const [offset, carry] of carried.entries())\n this.#settleCarry(carry, responses[carryIndex + offset]!, member);\n } catch (error) {\n const held = this.heldOutcomeFailure;\n this.heldOutcomeFailure = undefined;\n throw held\n ? this.#answered(retainWriteOutcomeFailure(error, held.failure))\n : error;\n }\n return responses.slice(guards.length);\n }\n /**\n * The operation's own answer to a batch {@link submit} returned, composed\n * with a listener failure that batch HELD while it acknowledged\n * ({@link heldOutcomeFailure}).\n *\n * The shipped `runAtomicBatch` order exactly\n * (`write-engine/OperationExecutor.ts:1332-1343`): the answer is decoded\n * first, a decode failure stays primary with the listener's retained beside\n * it, and a listener that failed beside an answer that SUCCEEDED is published\n * alone. Every caller of {@link submit} decodes here, so the hold is released\n * exactly once per submission — and on the plain transport there is nothing\n * to hold, because {@link dispatchSetMutations} decodes and acknowledges in\n * one frame and states its primary directly.\n */\n private async settleSubmitted<T>(\n answer: () => T | PromiseLike<T>\n ): Promise<T> {\n const held = this.heldOutcomeFailure;\n this.heldOutcomeFailure = undefined;\n let value: T;\n try {\n value = await answer();\n } catch (failure) {\n throw held\n ? this.#answered(retainWriteOutcomeFailure(failure, held.failure))\n : failure;\n }\n if (held) throw this.#answered(held.failure);\n return value;\n }\n rejectedProducer(error: unknown): object | undefined {\n const rejected = this.#attemptStore?.rejectedInsert;\n return rejected && rejected.error === error ? rejected.producer : undefined;\n }\n recoveryRejection(\n error: unknown\n ):\n | { readonly kind: \"assertion\" }\n | { readonly kind: \"insert\"; readonly producer: object }\n | undefined {\n // Rule 10: authority is not capability. The allowance asks who was rejected\n // and how far this operation got — never which transport carried it, which\n // is what let the shipped `routing.ts:180-208` replace a region the\n // transport opened. Attribution and progress are ALL it asks (Arnaud's\n // D-25): whether a rejected INSERT may be answered at all is decided where\n // the producer is RECORDED — bounded by member admission on the route whose\n // recovery REPLAYS in place ({@link submit}), unbounded on the route that\n // RE-PLANS ({@link insert}), which is what D-25 allows.\n if (\n this.#ownership !== \"standalone\" &&\n !(this.#ownership === \"borrowed-transaction\" && this.#operationRegion)\n )\n return undefined;\n if (this.#committedProgress) return undefined;\n // An ATOMIC ASSERTION is answered by a fresh PLAN over the same admitted\n // arguments, which re-reads committed state (D-25), so dynamic member\n // admission does not bound it: the new tree admits its own members.\n if (this.#atomicAssertionRejection === error) return { kind: \"assertion\" };\n const producer = this.rejectedProducer(error);\n return producer ? { kind: \"insert\", producer } : undefined;\n }\n get transportAttempt(): TransportAttempt {\n return this.#attempt;\n }\n restartRejectedInsert(attempt: TransportAttempt): void {\n this.#attemptStore = attempt;\n this.#atomicAssertionRejection = undefined;\n }\n /**\n * The operation's own cardinality over the rows a set-oriented mutation\n * published. A bulk verb publishes the set; a root single-row verb publishes\n * one row and owns the missing-row failure. The decision is stated here, in\n * the same closure that decodes, so a packaged operation states it too.\n */\n private published(rows: Input[], single?: () => Error): unknown {\n if (!single) return rows;\n const row = rows[0];\n if (!row) {\n // The operation's own PREMISE failed: the row it addressed is not there.\n // That is a statement about the world, not a report about the transport,\n // so it carries no record-series progress — the shipped engine's\n // `NotFoundError` meta for the same request is exactly\n // `{model, operation}` on every driver. A provider ANOMALY raised from\n // the same place (an INSERT that answered no row) throws from inside\n // `single()` instead of returning, is never marked, and keeps the\n // progress record its transport owes it.\n throw this.#answered(single());\n }\n return row;\n }\n /**\n * The same premise as {@link published}'s missing-row failure, moved INSIDE\n * the atomic unit for a packaged operation.\n *\n * `published` is a JavaScript postcondition, and a packaged operation only\n * reaches its parser after the array's one batch has committed — so a missing\n * row would raise the right error while every sibling member stayed durable.\n * A batch has no JS postcondition available, so the premise becomes a\n * statement: one `assertions.exists` over the same selector, queued ahead of\n * the mutation and declared to the array owner, which aborts the whole batch\n * and reconstructs this operation's own `NotFoundError` from the guard's\n * model and verb. This is exactly the shipped fold's batch shape\n * (`DeleteOperation` `foldGuard`/`buildRootPresenceGuard`, `UpdateOperation`'s\n * equivalent): `[presence guard, mutation … RETURNING]`, one round trip.\n */\n #packagedPresence(\n model: AnyModel,\n selector: PreparedSelector,\n single?: () => Error\n ): void {\n if (!single || this.#ownership !== \"batch-preparation\") return;\n const probe = this.queries.select(\n model,\n {\n select: Object.fromEntries(\n this.schema.keys(model).map((field) => [field, true])\n ),\n },\n undefined,\n { selector }\n );\n this.packageGuard(model, probe.sql, \"exists\", {\n kind: \"notFound\",\n // Never user-facing: `createFailureError` ignores this message for\n // `kind: \"notFound\"` and rebuilds the shipped sentence from the guard's\n // model and verb. It is read only by `sameAttribution`\n // (`batch-error-attribution.ts`), where being CONSTANT per model and\n // verb is what makes two guards of the same shape agree.\n message: `${this.operation} found no '${model[\"~\"].names.ts!}' row matching its unique selector.`,\n raceable: false,\n });\n }\n /**\n * One premise a packaged operation states INSIDE the array's atomic unit:\n * the assertion is queued ahead of the statements it protects and declared\n * to the array owner, which aborts the whole batch and rebuilds `failure`\n * from the guard (`batch-error-attribution.ts`). An asserted premise\n * ({@link requireAbsent}) cannot ride a package, because only this\n * operation's own transport reads its answer.\n */\n packageGuard(\n model: AnyModel,\n probe: Sql,\n premise: PreparedBatchGuard[\"premise\"],\n failure: PreparedGuardFailure\n ): void {\n (this.#preparedGuardList ??= []).push({\n queryIndex: this.queued.length,\n premise,\n probe,\n failure,\n model: model[\"~\"].names.ts!,\n operation: this.operation,\n });\n const assertions = this.driver.adapter.assertions;\n this.#queue(\n premise === \"exists\"\n ? assertions.exists(probe)\n : assertions.notExists(probe),\n this.statementContext(model, this.operation)\n );\n }\n emptyBulkResult(projection?: PreparedProjection): unknown {\n const result = () => (projection ? [] : { count: 0 });\n if (this.#ownership === \"batch-preparation\") {\n this.#preparedParser = result;\n return undefined;\n }\n return result();\n }\n seriesQueries(\n projection: PreparedProjection,\n identities: Input[],\n operation: \"createMany\" | \"updateMany\" = \"createMany\"\n ): Query[] {\n if (identities.length === 0) return [];\n const limit = normalizedBindParameterLimit(\n this.driver.maxBindParametersPerStatement\n );\n const preparedQueries = new WeakMap<Sql, Query>();\n const chunks = compileBindBudgetChunks(\n identities.length,\n limit,\n (start, end) => {\n const query = this.queries.selectSeries(\n projection,\n identities.slice(start, end),\n operation\n );\n preparedQueries.set(query.sql, query);\n return query.sql;\n }\n );\n return chunks.map(({ statement }) => preparedQueries.get(statement)!);\n }\n finish(): Promise<void> {\n return this.finishValue(undefined);\n }\n finishValue<T>(value: T): Promise<T> {\n return this.finishTerminals([], () => value);\n }\n finishOne(query: Query): Promise<Input | undefined> {\n return this.finishTerminals([query], (rows) => rows[0]);\n }\n finishMany(queries: readonly Query[]): Promise<Input[]> {\n return this.finishTerminals(queries, (rows) => rows);\n }\n #decodeTerminalResults(\n queries: readonly Query[],\n results: readonly QueryResult<unknown>[],\n resultIndex: number\n ): Input[] {\n const windows: Input[][] = [];\n for (const offset of queries.keys()) {\n const response = results[resultIndex + offset];\n if (!response)\n throw new TransactionError(\n `Driver '${this.driver.driverName}' omitted the ${this.#ownership === \"batch-preparation\" ? \"prepared\" : \"terminal\"} result for operation '${this.operation}'.`,\n { meta: this.#errorMeta }\n );\n windows.push(response.rows.map(record));\n }\n return this.publishedTerminal(queries, windows);\n }\n private async finishTerminals<T>(\n queries: readonly Query[],\n result: (rows: Input[]) => T\n ): Promise<T> {\n if (!this.usesBatch) {\n const windows: Input[][] = [];\n for (const terminal of queries)\n windows.push(\n (await this.answer(terminal, queries.length === 1)).rows.map(record)\n );\n return result(this.publishedTerminal(queries, windows));\n }\n const resultIndex = this.queued.length;\n for (const terminal of queries) this.#queue(terminal.sql);\n // The operation's last unit — and the ONE unit a prepared package is —\n // ends here, so its scratch is dropped here and nothing is read back out\n // of it: no statement follows that could bind the value (D-58).\n this.closeScratch();\n if (this.#ownership === \"batch-preparation\") {\n this.#preparedParser = (results) =>\n result(this.#decodeTerminalResults(queries, results, resultIndex));\n return result([]);\n }\n if (this.queued.length === 0) return result([]);\n const responses = await this.submit();\n return this.settleSubmitted(() => {\n try {\n return result(\n this.#decodeTerminalResults(queries, responses, resultIndex)\n );\n } catch (error) {\n throw queries.length ? this.failure(error, \"result\") : error;\n }\n });\n }\n isIncompletePreparation(error: unknown): boolean {\n return error === this.incompletePreparation;\n }\n preparedBatch(): PreparedBatchOperation<unknown> | undefined {\n const parse = this.#preparedParser;\n if (parse === undefined) return undefined;\n if (this.#attemptStore?.hasAssertedPremises) return undefined;\n return {\n queries: this.queued.map((query) =>\n transferPreparedStatement(query, {\n sql: query.sql,\n params: query.params ?? [],\n context: query.context ?? this.attribution,\n })\n ),\n ...(this.#preparedGuardList?.length\n ? { guards: this.#preparedGuardList }\n : {}),\n parseResult: (results) => {\n try {\n return parse(results);\n } catch (error) {\n throw this.failure(error, \"result\");\n }\n },\n };\n }\n async #setMutation(\n statement: Sql,\n context: QueryExecutionContext,\n parse: (result: QueryResult<unknown>) => unknown,\n judged?: JudgedWrite\n ): Promise<unknown> {\n return this.setMutations(\n [{ sql: statement, context }],\n (results) => {\n const result = results[0];\n if (!result)\n throw new TransactionError(\n `Driver '${this.driver.driverName}' omitted the result for operation '${this.operation}'.`,\n { meta: this.#errorMeta }\n );\n return parse(result);\n },\n judged\n );\n }\n private async setMutations(\n statements: readonly {\n readonly sql: Sql;\n readonly context: QueryExecutionContext;\n /** A judged statement's own judgement, asked again after a rollback ({@link submit}). */\n readonly probe?: Sql | undefined;\n }[],\n parse: (results: readonly QueryResult<unknown>[]) => unknown,\n judged?: JudgedWrite\n ): Promise<unknown> {\n if (this.#ownership === \"batch-preparation\") {\n const firstResult = this.queued.length;\n for (const statement of statements)\n this.#queueJudged(statement.sql, statement.context, undefined, judged);\n this.#preparedParser = (results) => {\n const window = results.slice(\n firstResult,\n firstResult + statements.length\n );\n if (window.length !== statements.length) {\n // One sentence for one condition: `publish` and\n // `decodeTerminalResults` state it the same way, and a root write now\n // reaches this owner through the fold.\n throw new TransactionError(\n `Driver '${this.driver.driverName}' omitted the prepared result for operation '${this.operation}'.`,\n { meta: this.#errorMeta }\n );\n }\n return parse(window);\n };\n return undefined;\n }\n // ONE rule for the physical envelope, asked here of this owner's two\n // transports: a set statement that is the operation's ONLY statement needs\n // no envelope, so it takes the plain execute path on a batch-only driver\n // exactly as on every other. That is the shipped transport rule — the same\n // `runStatementAtomic` condition {@link run} already restates for the\n // envelope (`write-engine/OperationExecutor.ts` `canExecuteDirectly` at\n // `:241` and its `:346-357` call site), which sends this shape through\n // `_execute` and never through `_executeBatch`. Arnaud's D-7 decision\n // (2026-09-15) is to take it exactly: a ONE-STATEMENT BATCH is what makes\n // the driver seam attribute `statementIndex: 0` to a rejection the shipped\n // engine attributes no index to (`drivers/driver-diagnostics.ts:35-36`),\n // for the folded root write and for every relation-free bulk verb alike.\n //\n // Each conjunct is a different way of not being the only statement: a plan\n // of several statements; something already queued on this attempt that\n // would ride the same batch (`requireAbsent`/`requirePresent`); a\n // generated-output continuation whose guard must precede the mutation\n // inside one atomic unit ({@link submit}).\n const lone =\n statements.length === 1 &&\n this.queued.length === 0 &&\n this.#continuationCount === 0;\n if (this.usesBatch && !lone) {\n const windowMember: Member = {};\n this.#setWindow = windowMember;\n // A premise queued ahead rides the same batch and answers first: the\n // window is these statements' own positions.\n const first = this.queued.length;\n for (const statement of statements)\n this.#queueJudged(\n statement.sql,\n statement.context,\n windowMember,\n judged,\n statement.probe\n );\n const results = await this.submit(true, windowMember);\n return this.settleSubmitted(() => {\n try {\n return parse(results.slice(first, first + statements.length));\n } catch (error) {\n throw this.failure(error, \"result\", windowMember);\n }\n });\n }\n return this.dispatchSetMutations(statements, parse, judged);\n }\n /**\n * The operation's own set-oriented statements on the plain execute path, and\n * the durable phase of the write it just made.\n *\n * This is the shipped `runBorrowedStatementAtomic` situation\n * (`write-engine/OperationExecutor.ts:1558-1645`): no envelope, so this\n * transport is the only one that learns whether the write became durable, and\n * it says so on the same rail {@link submit} uses ({@link WriteOutcomeSeam}) —\n * `mayBeVisible` when its statement fails without proving rollback, and\n * `committedSegment` once its statement has returned, whether or not the\n * result then decodes. Only a STANDALONE operation running outside any region\n * owns that answer: a borrowed operation's caller owns the scope (the shipped\n * `runLinearOn` notifies nothing), and this operation's own region answers\n * with its rollback.\n */\n private dispatchSetMutations(\n statements: readonly {\n readonly sql: Sql;\n readonly context: QueryExecutionContext;\n }[],\n parse: (results: readonly QueryResult<unknown>[]) => unknown,\n judged?: JudgedWrite\n ): Promise<unknown> {\n return this.dispatch(statements.length, true, async () => {\n const owned = this.#ownership === \"standalone\" && !this.#ownRegionOpen;\n const results: QueryResult<unknown>[] = [];\n try {\n for (const statement of statements)\n results.push(\n await this.#judging(judged, () =>\n this.#transport._execute(statement.sql, statement.context)\n )\n );\n } catch (error) {\n // The same sentence {@link submit}'s catch states about its batch: a\n // dispatched write whose rollback the transport cannot prove may be\n // visible, and a unique rejection is the one class that proves it.\n if (owned && !(error instanceof UniqueConstraintError))\n await this.#stateWriteOutcome(\n this.#writeOutcome?.mayBeVisible,\n error\n );\n throw error;\n }\n let decoded: { readonly failure: unknown } | { readonly value: unknown };\n try {\n decoded = { value: parse(results) };\n } catch (error) {\n // Translated HERE, once, so the one value this arm holds is the one the\n // caller would have received: {@link run}'s catch is the only other\n // translator of a decoding failure, and it no longer recognises this\n // one once {@link stateWriteOutcome} has composed it with a listener's.\n // The registered malformed-scalar refusal must stay primary, so the\n // public failure — not the internal `InvalidScalarResult` — is what is\n // both published to the cache seam and thrown.\n decoded = { failure: this.failure(error, \"result\") };\n }\n if (owned)\n await this.#stateWriteOutcome(\n this.#writeOutcome?.committedSegment,\n \"failure\" in decoded ? decoded.failure : undefined\n );\n if (\"failure\" in decoded) throw decoded.failure;\n return decoded.value;\n });\n }\n /**\n * Say ONE durable write phase on the client's cache rail, keeping the\n * OPERATION's own failure primary when the client's listener throws.\n *\n * The composition itself is not this engine's rule to state: it belongs to\n * `retainWriteOutcomeFailure` (`@errors`), the ONE owner the client, the\n * deferred operation and this context all reach — the primary stays primary\n * and `cause`, and the listener failures are flattened out of the publication\n * owner's aggregate and retained beside it, in registration order. It was\n * restated here while it lived in `@extensions/query`, an import this engine\n * does not take: no file under `raptor3/**` imports `@extensions/*` today,\n * and importing the publication owner would add `src/extensions/query.ts`\n * and `src/query-engine/routed-operations.ts` to this file's runtime closure\n * (181 → 183). A directory cycle is not what that avoids — the shipped\n * `query-engine/pending-operation.ts` already holds the engine→extensions\n * runtime edge. FC-05 moved the pure rule to the boundary both layers\n * already depend on and deleted the restatement.\n * `primary` absent means the operation has not failed, which was the shipped\n * `throw outcomeFailure` arm.\n */\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 this.#answered(retainWriteOutcomeFailure(primary, outcomeFailure));\n }\n }\n /** Mark a failure as this operation's own answer ({@link answeredFailures}). */\n #answered<T>(failure: T): T {\n if (typeof failure === \"object\" && failure !== null)\n (this.#answeredFailureSet ??= new WeakSet()).add(failure);\n return failure;\n }\n /**\n * Lower one INSERT shape; callers own grouping, chunking, and output. A\n * `judged` create reads its rows from their own values under their\n * placement (R4, {@link Queries.producedSource}), in the same statement.\n */\n #insertStatement(\n model: AnyModel,\n columns: readonly string[],\n rows: readonly Input[],\n skipDuplicates = false,\n judged?: PreparedSelector\n ): Sql {\n const q = this.queries;\n const mutations = this.driver.adapter.mutations;\n if (columns.length === 0) {\n // A row of defaults only has no value to judge before it is written.\n if (judged)\n throw new UnsupportedOperationError(\n `Cannot create a '${model[\"~\"].names.ts!}' row that writes no field: its placement is judged on the values it writes.`\n );\n return mutations.insertDefault(q.table(model));\n }\n const duplicate = skipDuplicates\n ? mutations.skipDuplicates(q.columnName(model, columns[0]!))\n : undefined;\n const select = judged && q.producedSource(model, columns, rows, judged);\n const statement = mutations.insert(\n q.table(model),\n columns.map((field) => q.columnName(model, field)),\n select\n ? { select }\n : rows.map((row) =>\n columns.map((field) => q.fieldValue(model, field, row[field]))\n ),\n duplicate?.prefix\n );\n return duplicate?.suffix\n ? sql`${statement} ${duplicate.suffix}`\n : statement;\n }\n /** Complete one set mutation through its single count/projection tail. */\n #completeSetMutation(\n model: AnyModel,\n statement: Sql,\n projection?: PreparedProjection,\n single?: () => Error,\n judged?: JudgedWrite\n ): Promise<unknown> {\n const q = this.queries;\n const output = projection\n ? sql`${statement} ${this.driver.adapter.mutations.returning(\n sql.join(q.lowerProjection(projection), \", \")\n )}`\n : statement;\n return this.#setMutation(\n output,\n this.statementContext(model, this.operation),\n (result) =>\n projection\n ? this.published(\n this.publishedProjection(\n projection.shape,\n result.rows.map(record)\n ),\n single\n )\n : { count: result.rowCount },\n judged\n );\n }\n /** Child-free inserts may share a statement inside this operation's own region. */\n async insertMany(\n model: AnyModel,\n rows: () => Input[],\n refusal?: PreparedGuardFailure\n ): Promise<number | undefined> {\n if (!this.#ownRegionOpen || this.usesBatch) return undefined;\n return (\n (await this.createMany(\n model,\n rows(),\n undefined,\n false,\n undefined,\n refusal\n )) as { count: number }\n ).count;\n }\n createMany(\n model: AnyModel,\n rows: Input[],\n projection?: undefined,\n skipDuplicates?: boolean,\n single?: () => Error,\n refusal?: PreparedGuardFailure\n ): Promise<{ count: number }>;\n createMany(\n model: AnyModel,\n rows: Input[],\n projection?: PreparedProjection,\n skipDuplicates?: boolean,\n single?: () => Error,\n refusal?: PreparedGuardFailure\n ): Promise<unknown>;\n /**\n * `refusal`: what a refused row reports (R4); a root write's\n * {@link forbidden} by default.\n */\n async createMany(\n model: AnyModel,\n rows: Input[],\n projection?: PreparedProjection,\n skipDuplicates = false,\n single?: () => Error,\n refusal?: PreparedGuardFailure\n ): Promise<unknown> {\n // A DIRECT empty `createMany` is Prisma's documented `{ count: 0 }` no-op.\n // A batch-PREPARED one is a different question, and the shipped engine\n // refused it: `$transaction([createMany({ data: [] })])` built its plan\n // during array preparation and `buildCreateManyPlan` raised \"No data to\n // insert for createMany.\" there (`assertBatchPreparable`). The mode is the\n // fact, and this is the owner that holds it — admission cannot, because the\n // same payload is admitted on both routes.\n if (rows.length === 0) {\n if (this.#ownership === \"batch-preparation\")\n throw new QueryEngineError(\"No data to insert for createMany.\");\n return this.emptyBulkResult(projection);\n }\n const q = this.queries;\n const adapter = this.driver.adapter;\n const placed = this.#produced(model);\n const judged = placed && { model, refusal: refusal ?? this.#forbidden };\n const recoverableSkip =\n skipDuplicates &&\n adapter.mutations.skipDuplicatesStrategy === \"recoverableUniqueError\";\n if (\n recoverableSkip ||\n (projection && !adapter.capabilities.supportsReturning)\n ) {\n if (this.#ownership === \"batch-preparation\")\n throw this.incompletePreparation;\n const suppress =\n recoverableSkip && this.admitsSuppression(\"duplicate rows\");\n const identityPlans = projection\n ? rows.map((row) => {\n const missing = this.schema\n .keys(model)\n .filter((field) => row[field] === undefined);\n const generated = this.#insertIdField(model, missing);\n if (missing.length > 0 && generated === undefined)\n throw new TransactionError(\n `Driver '${this.driver.driverName}' cannot locate one selected createMany row after insertion.`,\n { meta: this.#errorMeta }\n );\n return generated;\n })\n : undefined;\n const members = this.prepareMembers(() => rows);\n const identities: Input[] = [];\n let count = 0;\n for (const [index, row] of members.entries()) {\n const columns = Object.keys(row);\n const statement = this.#insertStatement(\n model,\n columns,\n [row],\n false,\n placed\n );\n const context = this.statementContext(model, this.operation);\n let response: QueryResult<unknown> | undefined;\n if (suppress) {\n response = await this.executeMember(async () => {\n try {\n return await this.dispatch(1, false, () =>\n this.#withMemberRollback((driver) =>\n this.#judging(judged, () =>\n driver._execute(statement, context)\n )\n )\n );\n } catch (error) {\n if (error instanceof UniqueConstraintError) return undefined;\n throw error;\n }\n }, row);\n } else {\n response = await this.executeMember(\n () =>\n this.dispatch(1, false, () =>\n this.#judging(judged, () =>\n this.#transport._execute(statement, context)\n )\n ),\n row\n );\n }\n if (!response) continue;\n count += response.rowCount;\n if (!identityPlans) continue;\n const generated = identityPlans[index];\n if (generated && response.insertId === undefined)\n throw new TypeError(\n \"INSERT did not produce the required record identity\"\n );\n identities.push({\n ...this.schema.identity(model, row),\n ...(generated ? { [generated]: response.insertId } : {}),\n });\n }\n if (!projection) return { count };\n return identities.length\n ? this.finishTerminals(\n this.seriesQueries(projection, identities),\n (published) => this.published(published, single)\n )\n : this.published([], single);\n }\n const returning = projection\n ? adapter.mutations.returning(\n sql.join(q.lowerProjection(projection), \", \")\n )\n : undefined;\n const groups: { readonly columns: string[]; readonly rows: Input[] }[] = [];\n for (const row of rows) {\n const columns = Object.keys(row);\n const preceding = groups.at(-1);\n if (\n columns.length === 0 ||\n !preceding ||\n preceding.columns.length !== columns.length ||\n columns.some((column, index) => preceding.columns[index] !== column)\n )\n groups.push({ columns, rows: [row] });\n else preceding.rows.push(row);\n }\n const limit = normalizedBindParameterLimit(\n this.driver.maxBindParametersPerStatement\n );\n const statements: {\n sql: Sql;\n context: QueryExecutionContext;\n probe?: Sql | undefined;\n }[] = [];\n for (const group of groups) {\n if (group.columns.length === 0) {\n for (const _row of group.rows) {\n let statement = this.#insertStatement(\n model,\n [],\n [_row],\n false,\n placed\n );\n if (returning) statement = sql`${statement} ${returning}`;\n statements.push({\n sql: statement,\n context: this.statementContext(model, this.operation),\n });\n }\n continue;\n }\n const chunks = compileBindBudgetChunks(\n group.rows.length,\n limit,\n (start, end) => {\n const mutation = this.#insertStatement(\n model,\n group.columns,\n group.rows.slice(start, end),\n skipDuplicates,\n placed\n );\n return returning ? sql`${mutation} ${returning}` : mutation;\n }\n );\n // A batch that rolls back on one chunk's refusal names that chunk by\n // asking each its SELECT again, as a lone create does ({@link submit}).\n for (const chunk of chunks)\n statements.push({\n sql: chunk.statement,\n context: this.statementContext(model, this.operation),\n probe:\n placed && this.usesBatch\n ? q.producedSource(\n model,\n group.columns,\n group.rows.slice(chunk.start, chunk.end),\n placed\n )\n : undefined,\n });\n }\n return this.setMutations(\n statements,\n (results) => {\n const written = results.reduce(\n (count, result) => count + result.rowCount,\n 0\n );\n // Triggers may legitimately suppress rows. The provider's affected count\n // is the completed write's answer, never a reason to fail after commit.\n if (!projection) return { count: written };\n const raw: Input[] = [];\n for (const result of results) raw.push(...result.rows.map(record));\n // A grouped insert split by the provider's bind budget answers in\n // several windows of the SAME projection and carries no per-window row\n // count of its own — the shortfall above is this fold's own contract.\n return this.published(\n this.publishedProjection(projection.shape, raw),\n single\n );\n },\n judged\n );\n }\n /**\n * A top-level upsert as ONE statement — the shipped engine's first upsert\n * path (\"an eligible `ON CONFLICT` fold has no planning read\", the retired\n * `write-engine/ATOM.md` §15, `operations/upsert.ts` `buildUpsert`): the\n * create's INSERT, the adapter's conflict clause over the addressed unique\n * key carrying the update language's assignments, and the projection's\n * RETURNING. The plan admits it only where the conditional form cannot run\n * at all — the array route, which can issue no planning read (D-46) — so\n * every other route keeps the conditional form and its pins. Zero rows back\n * is a provider anomaly, not a premise: `single` throws it.\n *\n * Each assignment is the payload's value over the CONFLICTING row's own\n * column, named through its table (`Queries.updateValue`): a counter reads\n * `\"<table>\".\"visits\" + $n`, because PostgreSQL also sees `excluded` there\n * and refuses a bare column as ambiguous.\n */\n async upsertOne(\n model: AnyModel,\n row: Input,\n updates: Input,\n target: readonly string[],\n projection?: PreparedProjection,\n single?: () => Error\n ): Promise<unknown> {\n const q = this.queries;\n const adapter = this.driver.adapter;\n const columns = Object.keys(row);\n const placed = this.#produced(model);\n const insert = this.#insertStatement(model, columns, [row], false, placed);\n const table = model[\"~\"].names.sql!;\n const conflict = adapter.mutations.onConflict(\n sql.join(\n target.map((field) =>\n adapter.identifiers.escape(q.columnName(model, field))\n ),\n \", \"\n ),\n adapter.mutations.onConflictUpdate(\n sql.join(\n Object.entries(updates).map(([field, value]) =>\n adapter.set.assign(\n q.column(model, field),\n q.updateValue(model, field, value, q.column(model, field, table))\n )\n ),\n \", \"\n )\n )\n );\n return this.#completeSetMutation(\n model,\n sql`${insert} ${conflict}`,\n projection,\n single,\n placed && { model, refusal: this.#forbidden }\n );\n }\n async updateMany(\n model: AnyModel,\n selector: PreparedSelector,\n values: Input,\n limit?: number,\n projection?: PreparedProjection,\n single?: () => Error\n ): Promise<unknown> {\n const q = this.queries;\n const adapter = this.driver.adapter;\n const assignments = this.#updateAssignments(model, values);\n // The rows this update produces, judged at the predicates that judged\n // its candidates (R4); a tombstone's are a delete's, and none.\n const produced = (target: PreparedSelector, limited?: number) =>\n this.#produce(\n model,\n values,\n selector.judgement,\n (alias) => q.lowerSelector(target, alias),\n limited\n );\n const judged = { model, refusal: this.#forbidden };\n // A relation carrier reads other rows, which no RETURNING can carry: the\n // post-image is re-read by identity, as without RETURNING.\n if (\n projection &&\n !(\n adapter.capabilities.supportsReturning &&\n returningSafeProjection(projection)\n )\n ) {\n const identities = await this.captureMutationIdentities(\n model,\n selector,\n limit\n );\n if (identities.length === 0) return this.published([], single);\n const captured = produced(\n q.andSelectors(model, [\n selector,\n q.includeIdentities(model, identities),\n ])\n );\n await this.#capturedMutation(\n model,\n selector,\n identities,\n limit,\n (target) =>\n adapter.mutations.update(\n q.table(model),\n sql.join(assignments, \", \"),\n captured ?? target\n ),\n // A delete that writes a tombstone still answers as a delete.\n this.operation === \"delete\" || this.operation === \"deleteMany\"\n ? \"deleteMany\"\n : \"updateMany\",\n captured && judged\n );\n return this.finishTerminals(\n this.seriesQueries(\n projection,\n identities.map((identity) =>\n this.#updatedIdentity(model, identity, values)\n ),\n \"updateMany\"\n ),\n (published) => this.published(published, single)\n );\n }\n this.#packagedPresence(model, selector, single);\n let where: Sql | undefined;\n const statement = q.sharing(() => {\n where = produced(selector, limit);\n const limited = where\n ? { where }\n : q.lowerMutationLimit(model, selector, limit);\n const mutation = adapter.mutations.update(\n q.table(model),\n sql.join(assignments, \", \"),\n limited.where\n );\n return limited.suffix ? sql`${mutation} ${limited.suffix}` : mutation;\n });\n return this.#completeSetMutation(\n model,\n statement,\n projection,\n single,\n where && judged\n );\n }\n async deleteMany(\n model: AnyModel,\n selector: PreparedSelector,\n limit?: number,\n projection?: PreparedProjection,\n single?: () => Error\n ): Promise<unknown> {\n const q = this.queries;\n const adapter = this.driver.adapter;\n // A relation carrier reads rows a DELETE is removing, so it can never ride\n // that statement's RETURNING: the row's shape is captured BEFORE the\n // removal, under the same locked capture the non-returning branch owns.\n if (\n projection &&\n !(\n adapter.capabilities.supportsReturning &&\n returningSafeProjection(projection)\n )\n ) {\n const identities = await this.captureMutationIdentities(\n model,\n selector,\n limit\n );\n if (identities.length === 0) return this.published([], single);\n const rows: Input[] = [];\n for (const query of this.seriesQueries(projection, identities))\n rows.push(...(await this.read(query, false, false, model)));\n await this.#capturedMutation(\n model,\n selector,\n identities,\n limit,\n (target) => adapter.mutations.delete(q.table(model), target),\n \"deleteMany\"\n );\n return this.published(rows, single);\n }\n this.#packagedPresence(model, selector, single);\n const statement = q.sharing(() => {\n const limited = q.lowerMutationLimit(model, selector, limit);\n const mutation = adapter.mutations.delete(q.table(model), limited.where);\n return limited.suffix ? sql`${mutation} ${limited.suffix}` : mutation;\n });\n return this.#completeSetMutation(model, statement, projection, single);\n }\n private async captureMutationIdentities(\n model: AnyModel,\n selector: PreparedSelector,\n limit: number | undefined\n ): Promise<Input[]> {\n if (this.#ownership === \"batch-preparation\")\n throw this.incompletePreparation;\n const keys = this.schema.keys(model);\n const query = this.queries.select(\n model,\n {\n select: Object.fromEntries(keys.map((field) => [field, true])),\n take: limit,\n },\n undefined,\n { selector, forUpdate: !this.usesBatch }\n );\n // An interactive session takes `FOR UPDATE`, so the ROWS IT CAPTURED\n // cannot change underneath it until the mutation. A row that JOINS the\n // selection afterwards is a different guarantee, which no row lock gives —\n // and it is not this mutation's row: the captured set is the set this\n // statement is about (D-65). A batch-only transport holds nothing across\n // two statements, so N4 (plan §4, D-52) gives the capture the shape the\n // series capture already has: it is a SEGMENT OF ITS OWN — the barrier\n // submits whatever this unit has queued and reads in the same native\n // batch — and the premises {@link requireCapturedSet} states inside the\n // MUTATION's batch are what protect it there. No lock is claimed where\n // none exists.\n const rows = this.usesBatch\n ? await this.flush(query)\n : await this.read(query, true, false, model);\n return rows.map((row) => this.schema.identity(model, row));\n }\n /**\n * What the captured set claims, asserted inside the batch that mutates it.\n *\n * The capture named the rows that matched when it ran, and rule 5 forbids\n * treating an observed set as a lasting truth. So the mutation's own batch\n * carries the claim as statements AHEAD OF THE WRITE: as the unit begins,\n * every captured row is present and a member of the selection, and — when\n * the capture took the whole selection rather than a limited slice — no row\n * has joined it. A capture already stale there aborts the atomic unit before\n * anything is written, which is what a count after the mutation cannot do.\n *\n * These premises answer WHERE THEY STAND and claim nothing about the effect:\n * between the last of them and the write a row can still stop matching, as\n * `g4/release/closure/fcpg/` measured on native PostgreSQL. That window\n * belongs to the write, which carries the selector itself\n * ({@link capturedTarget}, D-65) — such a row is not mutated, and the\n * cardinality sentence is the answer for it.\n *\n * Only on the batch route: an interactive session captured `FOR UPDATE`.\n */\n private async requireCapturedSet(\n model: AnyModel,\n selector: PreparedSelector,\n identities: readonly Input[],\n limit: number | undefined,\n changed: () => Error\n ): Promise<void> {\n if (!this.usesBatch) return;\n const q = this.queries;\n for (const identity of identities)\n this.requirePresent(\n q.select(model, { take: 1 }, undefined, { selector, identity }),\n changed()\n );\n // A LIMITED capture took one valid slice of the selection; another row\n // joining it does not make that slice the wrong answer, so the complement\n // is claimed only for a capture that took the whole set.\n if (limit !== undefined) return;\n await this.requireAbsent(\n q.select(model, { take: 1 }, undefined, {\n selector: q.andSelectors(model, [\n selector,\n q.excludeIdentities(model, identities),\n ]),\n }),\n changed()\n );\n }\n /**\n * A root selected UPDATE/DELETE over the set {@link captureMutationIdentities}\n * captured: the premises that set owes, its own statement, and the one\n * judgement of the row count it affected, on either transport. On the batch\n * route the statement rides the same batch its premises are in, so the write\n * never runs when a premise disagrees. What the two verbs do NOT share stays\n * with them: an UPDATE reads its final rows after this returns, a DELETE\n * read them before calling it.\n *\n * ONE fact at two positions, and the count is how the second one is read.\n * The premises {@link requireCapturedSet} queues ahead of the write say the\n * captured rows are still the selection AS THE UNIT BEGINS; the write's own\n * selector ({@link capturedTarget}, handed to the verb's `mutation`) says it\n * AT THE EFFECT (D-65). A captured row this statement did not match is a row\n * the operation was asked to change and did not — the verb's registered\n * cardinality sentence, never a silent success publishing the captured rows.\n * The verb is named, not read from {@link operation}: a root `delete` that\n * captures answers with `deleteMany`'s sentence, as it always has. The statement is built after the premises, where a lowered\n * target's aliases continue the last premise statement's scope.\n *\n * Failure and commit stay separate facts there. On an operation-owned\n * interactive transaction the owner rolls back; on a batch that already\n * ACKNOWLEDGED, what it committed stands and the sentence is a RESULT-phase\n * failure that says so ({@link failure}: `atomicity: \"segment\"` with this\n * operation's committed segments). It replays nothing and erases no\n * progress, because a check after dispatch cannot undo the batch it judges.\n *\n * The count is judged HERE, INSIDE {@link settleSubmitted}, because this is\n * the boundary at which the operation's answer to its batch is known. Read\n * one statement later it would be read after the hold was already released:\n * the batch acknowledged, a write-outcome listener that failed while it did\n * is HELD, and a settlement that saw only the decoded response would call\n * that an answer that SUCCEEDED and publish the listener's failure alone —\n * losing both the operation's own failure and the progress attached to it.\n * Transport success is not result success, and a settlement region holds\n * every judgement that can still turn this operation's answer into a failure\n * (repair prompt §3). The premises {@link requireCapturedSet} states owe the\n * same sentence.\n */\n async #capturedMutation(\n model: AnyModel,\n selector: PreparedSelector,\n identities: readonly Input[],\n limit: number | undefined,\n mutation: (target: Sql | undefined) => Sql,\n verb: \"updateMany\" | \"deleteMany\",\n judged?: JudgedWrite\n ): Promise<void> {\n const changed = () =>\n new TransactionError(\n `${verb} selected-row cardinality changed during its locked mutation.`,\n { meta: this.#errorMeta }\n );\n await this.requireCapturedSet(model, selector, identities, limit, changed);\n const statement = this.queries.sharing(() =>\n mutation(this.capturedTarget(model, selector, identities))\n );\n const context = this.statementContext(model, this.operation);\n const answered = (response: QueryResult<unknown>) => {\n if (response.rowCount !== identities.length)\n throw this.failure(changed(), \"result\");\n };\n if (!this.usesBatch) {\n answered(\n await this.dispatch(1, false, () =>\n this.#judging(judged, () =>\n this.#transport._execute(statement, context)\n )\n )\n );\n return;\n }\n // Its own answer, by its own position: the batch also carries this\n // mutation's premises ahead of it, {@link submit} answers the queued\n // statements alone (its guards are sliced off), and the row count this\n // mutation reports is the one the captured set is judged against.\n const index = this.queued.length;\n // A set-oriented statement's window: a merely uncertain outcome is no\n // record series of its own ({@link failure}), as `setMutations` states it.\n const member: Member = {};\n this.#setWindow = member;\n this.#queueJudged(statement, context, member, judged);\n const responses = await this.submit(true, member);\n await this.settleSubmitted(() => {\n const response = responses[index];\n if (!response)\n throw new TransactionError(\n `Driver '${this.driver.driverName}' omitted the prepared result for operation '${this.operation}'.`,\n { meta: this.#errorMeta }\n );\n answered(response);\n });\n }\n /**\n * WHERE a captured root mutation writes: the rows the capture named, AND the\n * selector it captured them by (D-65).\n *\n * The identity set alone addresses a row by a key that WAS in the selection;\n * the selector is what that row must still satisfy for this statement to be\n * about it. Carrying both leaves a row that stopped matching alone — the\n * answer the interactive route's `FOR UPDATE` already gave, now given by the\n * statement itself on every route — and the row count each verb checks turns\n * the shortfall into its cardinality sentence. It is the prepared meaning the\n * capture already ran, composed at `Queries` and never respelled as public\n * syntax, in one statement: no lock, no protocol, no second reading.\n *\n * A `limit` is not restated here. The capture took that slice already\n * ({@link captureMutationIdentities}'s `take`), so the identity set IS the\n * bound, and a row that joined the selection since is outside this set.\n */\n private capturedTarget(\n model: AnyModel,\n selector: PreparedSelector,\n identities: readonly Input[]\n ): Sql | undefined {\n const q = this.queries;\n return q.lowerMutationLimit(\n model,\n q.andSelectors(model, [selector, q.includeIdentities(model, identities)]),\n undefined\n ).where;\n }\n #updatedIdentity(model: AnyModel, identity: Input, values: Input): Input {\n const q = this.queries;\n return Object.fromEntries(\n this.schema\n .keys(model)\n .map((field) => [\n field,\n Object.hasOwn(values, field)\n ? q.updateValue(\n model,\n field,\n values[field],\n q.fieldValue(model, field, identity[field])\n )\n : identity[field],\n ])\n );\n }\n /**\n * The scratch of the unit being assembled, made by the first statement that\n * stores into it.\n *\n * It belongs to the DISPATCHED UNIT and not to the attempt (D-58). Where the\n * transport admits temporaries the table is session-scoped, and a transport\n * that pins no session (Neon HTTP) ends its session with the batch, so a unit\n * that named a table an EARLIER segment created named nothing at all; where it\n * does not (D1) the adapter spells an ordinary table that outlives the batch.\n * Either way every unit that needs one mints its own batch id, and\n * {@link closeScratch} deletes that id's rows where the unit ends.\n */\n private ensureScratch(): string {\n const attempt = this.#attempt;\n if (attempt.scratchId) return attempt.scratchId;\n const references = getAdapterInternals(this.driver.adapter).batchRefs;\n attempt.scratchId = crypto.randomUUID();\n for (const setup of references.setup(attempt.scratchId)) this.#queue(setup);\n return attempt.scratchId;\n }\n /**\n * A value this unit PRODUCED, read back at the unit's boundary so the next\n * one binds it as a literal (D-58).\n *\n * One SELECT per value stored, at the end of the batch that stored it and\n * inside it — the scratch is alive exactly there — through the SAME owner\n * that reads a produced value back anywhere else\n * ({@link Queries.scalarQuery}), so the literal arrives through the field's\n * own codec and binds exactly as a spelled key would. A unit with no next —\n * the operation's terminal statements, and the one unit a prepared package IS\n * — has closed its scratch already ({@link finishTerminals}) and reads\n * nothing back: there is no later statement to bind it.\n */\n #carryScratch(): readonly ScratchCarry[] {\n const attempt = this.#attemptStore;\n if (attempt?.scratchId === undefined) return NO_SCRATCH_CARRY;\n const carried: ScratchCarry[] = [];\n for (const publication of attempt.drainScratchPublications()) {\n const query = this.queries.scalarQuery(\n publication.model,\n publication.field,\n publication.expression\n );\n this.#queue(query.sql);\n carried.push({ query, publication });\n }\n return carried;\n }\n /**\n * The literal one read-back answered, held where the scratch id is held.\n *\n * Exactly one row, by construction: the read-back is\n * {@link Queries.scalarQuery}'s projection-only `SELECT <expression>` — no\n * FROM, no cardinality of its own — so every provider answers it with one\n * row, and the assertion is the statement of that. A guard here would be a\n * check whose unique coverage cannot be named, and it would fail in the one\n * way this unit exists to prevent: an uncarried value leaves the NEXT unit\n * binding a scratch its own segment never created.\n */\n #settleCarry(\n carry: ScratchCarry,\n response: QueryResult<Input>,\n member?: Member\n ): void {\n let row: Input;\n try {\n row = this.queries.decodeQuery(carry.query, response.rows, true)[0]!;\n } catch (error) {\n throw this.failure(error, \"result\", member);\n }\n this.#attempt.carryScratchValue(\n carry.publication.expression,\n row[carry.publication.field]\n );\n }\n /**\n * The scratch dies with the unit that made it: its rows are deleted inside\n * that unit's own batch, and the id is spent, so the next unit that stores a\n * produced value creates its own ({@link ensureScratch}).\n */\n private closeScratch(): void {\n const attempt = this.#attemptStore;\n if (attempt?.scratchId === undefined) return;\n this.#queue(\n getAdapterInternals(this.driver.adapter).batchRefs.cleanup(\n attempt.scratchId\n )\n );\n attempt.scratchId = undefined;\n }\n #insertIdField(\n model: AnyModel,\n produced: readonly string[]\n ): string | undefined {\n if (produced.length !== 1) return undefined;\n const field = produced[0]!;\n return model[\"~\"].state.scalars[field]![\"~\"].state.autoGenerate?.kind ===\n \"increment\"\n ? field\n : undefined;\n }\n async insert(\n model: AnyModel,\n values: Input,\n demanded: ReadonlySet<string>,\n member: Member,\n operation = \"create\",\n producer?: object,\n membership?: MembershipParent,\n refusal?: PreparedGuardFailure\n ): Promise<Input> {\n const q = this.queries;\n const adapter = this.driver.adapter;\n const fields = Object.keys(values);\n const placed = this.#produced(model);\n const judged = placed && { model, refusal: refusal ?? this.#forbidden };\n let statement = this.#insertStatement(\n model,\n fields,\n [values],\n false,\n placed\n );\n // The SELECT the judged INSERT reads its row from: asked again after a\n // batch rolled back, it fails as the INSERT did ({@link submit}).\n const probe =\n placed && this.usesBatch && fields.length > 0\n ? q.producedSource(model, fields, [values], placed)\n : undefined;\n const produced = [...demanded].filter(\n (field) => values[field] === undefined\n );\n const context = this.statementContext(model, operation);\n if (!this.usesBatch) {\n const producedProjection = produced.length\n ? q.prepareProjection(\n model,\n {\n select: Object.fromEntries(\n produced.map((field) => [field, true])\n ),\n },\n true\n )\n : undefined;\n const insertIdField = adapter.capabilities.supportsReturning\n ? undefined\n : this.#insertIdField(model, produced);\n if (\n produced.length &&\n !adapter.capabilities.supportsReturning &&\n insertIdField === undefined\n )\n throw new Error(\n \"Returning generated values requires RETURNING support or one generated increment field\"\n );\n if (producedProjection && adapter.capabilities.supportsReturning)\n statement = sql`${statement} ${adapter.mutations.returning(\n sql.join(q.lowerProjection(producedProjection), \", \")\n )}`;\n this.#attempt.rejectedInsert = undefined;\n let response: QueryResult<Input>;\n try {\n response = await this.dispatch(1, false, () =>\n this.#judging(judged, () =>\n this.#transport._execute<Input>(statement, context)\n )\n );\n } catch (error) {\n if (producer && error instanceof UniqueConstraintError)\n this.#attempt.rejectedInsert = { error, producer };\n throw error;\n }\n const producedRows =\n insertIdField === undefined\n ? response.rows\n : response.insertId === undefined\n ? []\n : [{ [insertIdField]: response.insertId }];\n const producedValues = producedProjection\n ? q.decodeProjection(producedProjection.shape, producedRows, true)[0]\n : undefined;\n if (produced.length && producedValues === undefined)\n throw new TypeError(\"INSERT did not produce the required record\");\n return {\n ...values,\n ...producedValues,\n };\n }\n // The row this one is a MEMBER of, re-pinned in every segment AFTER the one\n // that writes it. A membership correlates BY VALUE, so once another row\n // holds the parent's referenced value the correlation answers with IT — and\n // a segment that has committed cannot be taken back, so what the next one\n // trusts is re-read in it. Inside the segment that writes the membership\n // there is nothing to re-pin: the write is still this unit's own and its\n // rollback takes it back, which is what {@link Continuation.declaring}\n // says. The sentence and the query are the pair\n // `CommandExecution.captureSeries` states for the same fact on a captured\n // series — one owner, restated here for the row a continuation follows.\n if (membership)\n (this.#continuationList ??= []).push({\n declaring: true,\n model: membership.model,\n state: () =>\n q.select(membership.model, {\n where: membership.where(),\n select: Object.fromEntries(\n this.schema.keys(membership.model).map((field) => [field, true])\n ),\n }),\n failure: () =>\n new NestedWriteError(\n `Cannot ${membership.verb} relation '${membership.relation}': parent record changed across a committed segment.`,\n membership.relation\n ),\n });\n const published: Input = { ...values };\n if (produced.length) {\n const references = getAdapterInternals(adapter).batchRefs;\n const insertIdField = this.#insertIdField(model, produced);\n // The exact identity scratch carries ONE generated increment key through\n // the batch: the dialect stores it from the statement that produced it —\n // its own RETURNING inside a data-modifying CTE where the provider can\n // mutate in one (PostgreSQL, D-50), or the statement-local last insert\n // id (SQLite, MySQL) — and every later statement reads the reference\n // back with the key's own width. How it is stored is the dialect's\n // (`batchRefs.storeInsertedKey`), not chosen here.\n const storeInsertedKey = references.storeInsertedKey;\n const carriesIdentity =\n insertIdField !== undefined && storeInsertedKey !== undefined;\n if (!carriesIdentity) {\n if (\n !adapter.capabilities.supportsReturning ||\n adapter.capabilities.supportsCteWithMutations\n )\n throw new Error(\n \"The driver cannot return generated values for this atomic batch without an exact row identity\"\n );\n // The next segment must prove the actual stored owner, including supplied row-key fields.\n const returned = [\n ...new Set([...this.schema.keys(model), ...demanded]),\n ];\n const select = Object.fromEntries(\n returned.map((field) => [field, true])\n );\n const projection = q.prepareProjection(model, { select }, true);\n const resultIndex = this.queued.length;\n const inserted = this.#queueJudged(\n sql`${statement} ${adapter.mutations.returning(\n sql.join(q.lowerProjection(projection), \", \")\n )}`,\n context,\n member,\n judged,\n probe\n );\n if (producer) this.#attempt.recordInsertProducer(inserted, producer);\n const responses = await this.submit(true, member);\n const stored = await this.settleSubmitted(() => {\n try {\n const rows = q.decodeProjection(\n projection.shape,\n responses[resultIndex]!.rows,\n true\n );\n if (!rows[0])\n throw new TypeError(\n \"INSERT RETURNING did not produce the required record\"\n );\n return rows[0];\n } catch (error) {\n throw this.failure(error, \"result\", member);\n }\n });\n (this.#continuationList ??= []).push({\n model,\n state: () =>\n q.select(model, {}, undefined, {\n projection,\n identity: stored,\n }),\n failure: () =>\n new TransactionError(\n `Created record '${model[\"~\"].names.ts!}' changed across a generated-output segment boundary.`,\n { meta: { model: this.modelName, operation: this.operation } }\n ),\n });\n return { ...values, ...stored };\n }\n const scratchId = this.ensureScratch();\n const key = String(this.#attempt.nextField++);\n const [producing, ...storing] = storeInsertedKey(\n scratchId,\n key,\n statement,\n adapter.identifiers.escape(q.columnName(model, insertIdField))\n );\n const inserted = this.#queueJudged(\n producing!,\n context,\n member,\n judged,\n probe\n );\n if (producer) this.#attempt.recordInsertProducer(inserted, producer);\n for (const store of storing) this.#queue(store);\n const expression = adapter.expressions.cast(\n references.read(scratchId, key),\n physicalField(this.schema, model, insertIdField).scalar[\"~\"].state\n .type === \"bigint\"\n ? \"bigint\"\n : \"integer\"\n );\n this.#attempt.publishScratchValue({\n model,\n field: insertIdField,\n expression,\n });\n published[insertIdField] = expression;\n } else {\n const inserted = this.#queueJudged(\n statement,\n context,\n member,\n judged,\n probe\n );\n if (producer) this.#attempt.recordInsertProducer(inserted, producer);\n }\n return published;\n }\n /**\n * @param current The row's values as they stand NOW, before this statement:\n * its identity and every value an assignment of this update computes from.\n * ONE meaning answers all three of this path's questions — which row the\n * statement addresses, what the arithmetic starts from, and which row the\n * non-RETURNING readback names — because they are all the same row at the\n * same moment. A correlated arm may already have moved it (`ON UPDATE\n * CASCADE`) before this statement runs, and the caller's one reader of a\n * field's runtime value (`CommandAttempt.read`, D-58) answers the key the\n * cascade left it at. An address beside a STALE capture named two different\n * rows, and the readback then found none (FC-02A). The row's ORIGINAL\n * observation is a different fact and belongs to the consumers that need\n * what was SEEN — a choice's conditional skip, a captured junction row —\n * not to this statement.\n */\n async update(\n model: AnyModel,\n current: Input,\n values: Input,\n member: Member,\n operation = \"update\",\n demanded: ReadonlySet<string> = new Set(),\n missing?: () => Error,\n judgement?: RowJudgement,\n refusal?: PreparedGuardFailure\n ): Promise<Input> {\n if (Object.keys(values).length === 0) return {};\n const q = this.queries;\n const adapter = this.driver.adapter;\n const identity = this.schema.identity(model, current);\n const written = { ...values };\n // What this update PUBLISHES to its dependents: the values it observed,\n // never the payload it submitted. The payload is the update language and\n // `Queries.prepareUpdate` is its one interpreter (U4); the question \"which\n // value will this field hold?\" is the key-reconciliation reader's, and\n // `CommandAttempt.read` already answers it from `Assignments.stated` for\n // every field this update does not observe.\n const published: Input = {};\n // The demanded fields whose value only the PROVIDER can compute and the\n // batch scratch cannot carry: the scratch reads back as an integer, so an\n // `int` field is the only domain that travels as an expression. N4 (plan\n // §4, D-52) stops refusing the rest — under N1 a value an earlier write of\n // this operation produces is taken as an ORDERED OBSERVATION of the row\n // AFTER that write, through the same barrier a dependent lookup uses\n // ({@link flush}: the queued unit and the read in one native batch, the\n // consumer's own write in the next). The scratch keeps carrying the\n // integer keys it carries today, and the observation owns nothing else:\n // it is the existing read, placed behind the existing write.\n const observed: string[] = [];\n if (this.usesBatch) {\n for (const field of demanded) {\n const value = values[field];\n // A payload that NAMES a value — a literal, a bound expression, or the\n // `{ set: … }` envelope — leaves nothing for the provider to evaluate,\n // so it needs no scratch and no capability refusal: the reader resolves\n // the same value the row's own write submits. Only an OPERATION\n // (`{ increment: 2 }`) has a value that exists after the provider\n // computes it, and only that value has to travel through the scratch.\n if (wholeValue(value)) continue;\n const state = physicalField(this.schema, model, field).scalar[\"~\"]\n .state;\n // R-D3 (Arnaud, 2026-09-15) gave the batch-only publication gap a\n // public identity because the engine had no answer for it. N4 gives it\n // an answer instead: the value is OBSERVED after the write rather than\n // published through a scratch that cannot hold it. A package prepared\n // for the array owner can issue no read of its own, and {@link submit}\n // states that fact when the observation is flushed — this operation\n // requires dynamic execution (D-46), the array owner's control-flow\n // value, not a refusal the caller sees.\n if (state.type !== \"int\") {\n observed.push(field);\n continue;\n }\n const references = getAdapterInternals(adapter).batchRefs;\n const scratchId = this.ensureScratch();\n const key = String(this.#attempt.nextField++);\n // The UPDATE and every consumer use this one evaluated value in the same batch.\n this.#queue(\n references.store(\n scratchId,\n key,\n q.updateValue(\n model,\n field,\n value,\n q.fieldValue(model, field, current[field])\n )\n )\n );\n const expression = adapter.expressions.cast(\n references.read(scratchId, key),\n \"integer\"\n );\n this.#attempt.publishScratchValue({ model, field, expression });\n written[field] = published[field] = expression;\n }\n }\n // The row this update produces, judged at the predicates that judged\n // the row it located (R4).\n // Its candidate is the identity alone: what judged the row it located\n // is stated again over the row it produces, in this statement.\n let produced: Sql | undefined;\n const statement = q.sharing(() => {\n produced = this.#produce(\n model,\n written,\n judgement,\n (alias) => q.lowerIdentity(model, identity, alias),\n undefined,\n false\n );\n return adapter.mutations.update(\n q.table(model),\n sql.join(this.#updateAssignments(model, written), \", \"),\n produced ?? q.lowerIdentity(model, identity)\n );\n });\n const judged = produced\n ? { model, refusal: refusal ?? this.#forbidden }\n : undefined;\n const context = this.statementContext(model, operation);\n if (!this.usesBatch && demanded.size) {\n const fields = [...demanded];\n const select = Object.fromEntries(fields.map((field) => [field, true]));\n const projection = q.prepareProjection(model, { select }, true);\n if (!adapter.capabilities.supportsReturning) {\n await this.dispatch(1, false, () =>\n this.#judging(judged, () =>\n this.#transport._execute(statement, context)\n )\n );\n // This read answers \"which row did the UPDATE just write?\", and only a\n // CURRENT read can: under REPEATABLE READ a consistent read answers\n // from the snapshot this transaction opened plus its OWN changes, so a\n // statement that affected NO row leaves the snapshot's copy standing\n // and the check below sees a row that is not there. The lock is the\n // same one the UPDATE itself took on every row it did write, so on the\n // ordinary path it costs nothing and the comment it replaces — the\n // mutation's locked capture protects this read — becomes true of this\n // statement rather than of a plan-time probe that may no longer hold\n // it (`Selection.insertsWhenAbsent`).\n const rows = await this.read(\n q.select(model, {}, undefined, {\n forUpdate: true,\n projection,\n identity: this.#updatedIdentity(model, identity, values),\n }),\n true\n );\n if (!rows[0])\n throw (\n missing?.() ??\n new TypeError(\"UPDATE did not produce the required record\")\n );\n return { ...published, ...rows[0] };\n }\n const response = await this.dispatch(1, false, () =>\n this.#judging(judged, () =>\n this.#transport._execute<Input>(\n sql`${statement} ${adapter.mutations.returning(\n sql.join(q.lowerProjection(projection), \", \")\n )}`,\n context\n )\n )\n );\n const rows = q.decodeProjection(projection.shape, response.rows, true);\n if (!rows[0])\n throw (\n missing?.() ??\n new TypeError(\"UPDATE RETURNING did not produce the required record\")\n );\n return { ...published, ...rows[0] };\n }\n await this.#effect(statement, context, member, judged);\n if (observed.length === 0) return published;\n // The ordered observation: the write is queued, and the read that answers\n // the dependent rides the same native batch BEHIND it, so what it reads is\n // what this update wrote. The row is addressed by the identity this update\n // leaves it at — `updatedIdentity` names every key the payload changes —\n // and the value comes back decoded, a literal for the consumer's own write\n // in the next batch (D-51's succession of statements).\n const projection = q.prepareProjection(\n model,\n { select: Object.fromEntries(observed.map((field) => [field, true])) },\n true\n );\n const rows = await this.flush(\n q.select(model, {}, undefined, {\n projection,\n identity: this.#updatedIdentity(model, identity, values),\n }),\n member\n );\n if (!rows[0])\n throw new TypeError(\"UPDATE did not produce the required record\");\n return { ...published, ...rows[0] };\n }\n /**\n * Has this captured slot already been spent — and, if it had not, spend it.\n *\n * One walk down {@link SpentSlots}, so the ask and the record are one act:\n * no caller can spend a slot without asking, and none can ask without\n * spending. The leaf's presence IS the answer.\n */\n #spendSlot(table: string, values: readonly unknown[]): boolean {\n let level = (this.#vacatedMemberships ??= new Map());\n const path: unknown[] = [table, ...values];\n let spent = true;\n for (const [index, key] of path.entries()) {\n const leaf = index === path.length - 1;\n let next = level.get(key);\n if (next === undefined) {\n spent = false;\n next = leaf ? true : new Map();\n level.set(key, next);\n }\n if (!leaf) level = next as SpentSlots;\n }\n return spent;\n }\n async link(\n edge: Extract<Membership, { kind: \"junction\" }>,\n values: Input,\n member: Member,\n captured?: Input\n ): Promise<void> {\n const adapter = this.driver.adapter;\n const q = this.queries;\n const columns = [\n ...edge.sourceSide.members,\n ...edge.targetSide.members,\n ].map((pair) => pair.junctionField);\n if (captured) {\n if (columns.every((field) => Object.is(captured[field], values[field]))) {\n return;\n }\n // ONE captured pair is ONE slot transition. Entries that resolve to the\n // same target carry the SAME captured owner — the plan read the slot once\n // — so a second vacate would delete a row THIS operation already removed,\n // and the direct arm's postcondition would read its own effect as a\n // concurrent change. The transition is spent here, once per captured\n // pair, and the membership INSERT that follows is idempotent either way\n // (the conflict clause, or the anti-join select where the dialect has no\n // targeted upsert). The postcondition keeps the race it exists for: the\n // FIRST vacate of a pair another owner took.\n //\n // The spent pairs are a TREE keyed by the captured VALUES themselves —\n // the edge's table, then its columns in the edge's own order — because a\n // junction column carries whatever domain the referenced key carries. A\n // `Map` compares with SameValueZero, so a `bigint` key is compared as the\n // bigint it is; spelling the pair instead could not: `JSON.stringify`\n // THROWS on a `bigint` (`TypeError: Do not know how to serialize a\n // BigInt`, escaping this engine's error surface) and COLLIDES on a value\n // whose class carries no `toJSON`, where two distinct `decimal` pairs\n // both spell `{}` and the second would skip a vacate it never spent.\n // A value-keyed level compares two decoded objects by identity, which\n // errs the safe way: a pair the plan did not capture twice is vacated,\n // and the postcondition still guards that vacate.\n const slot = columns.map((field) => captured[field]);\n if (!this.#spendSlot(edge.table, slot)) {\n const remove = adapter.mutations.delete(\n adapter.identifiers.table(edge.table),\n q.junctionWhere(edge, captured)\n );\n const context = this.statementContext(edge.source, \"update\");\n if (this.usesBatch) this.#queue(remove, context, member);\n else {\n const response = await this.dispatch(1, false, () =>\n this.#transport._execute(remove, context)\n );\n if (response.rowCount !== 1) {\n const failure = new TransactionError(\n `Concurrent membership change on the singular polymorphic member of relation '${edge.name}': the captured owner's membership was already removed; retry to converge.`\n );\n failure.meta.raceable = true;\n throw failure;\n }\n }\n }\n }\n const operands = [edge.sourceSide, edge.targetSide].flatMap((side) =>\n side.members.map((pair) =>\n q.fieldValue(\n side.model,\n pair.referencedField,\n values[pair.junctionField]\n )\n )\n );\n if (!adapter.capabilities.supportsTargetedUpsert) {\n const targetAlias = q.alias();\n const membershipAlias = q.alias();\n // The target membership is an outer join, not a target-table subquery.\n const select = assembleAdapterSelect(adapter, {\n columns: sql.join(operands, \", \"),\n from: q.table(edge.target, targetAlias),\n joins: [\n adapter.joins.left(\n adapter.identifiers.table(edge.table, membershipAlias),\n q.junctionWhere(edge, values, membershipAlias)\n ),\n ],\n where: adapter.operators.and(\n ...edge.targetSide.members.map((pair) =>\n adapter.operators.eq(\n q.column(edge.target, pair.referencedField, targetAlias),\n q.fieldValue(\n edge.target,\n pair.referencedField,\n values[pair.junctionField]\n )\n )\n ),\n adapter.operators.isNull(\n adapter.identifiers.column(membershipAlias, columns[0]!)\n )\n ),\n });\n await this.#effect(\n adapter.mutations.insert(\n adapter.identifiers.table(edge.table),\n columns,\n { select }\n ),\n this.statementContext(edge.source, \"update\"),\n member\n );\n return;\n }\n const insert = adapter.mutations.insert(\n adapter.identifiers.table(edge.table),\n columns,\n [operands]\n );\n await this.#effect(\n sql`${insert} ${adapter.mutations.onConflict(\n sql.join(\n columns.map((column) => adapter.identifiers.escape(column)),\n \", \"\n ),\n sql`NOTHING`\n )}`,\n this.statementContext(edge.source, \"update\"),\n member\n );\n }\n async captureMembership(\n edge: Extract<Membership, { kind: \"junction\" }>,\n addressed: Input\n ): Promise<Input | undefined> {\n const query = this.queries.junction(edge, addressed, !this.usesBatch);\n const rows = await this.read(query, true);\n const captured = rows[0] ? { ...addressed, ...rows[0] } : undefined;\n if (this.usesBatch) {\n const failure = new NestedWriteError(\n `Concurrent membership change on the singular polymorphic member of relation '${edge.name}': ${captured ? \"the captured membership is gone\" : \"another owner holds the target\"}; retry to converge.`,\n edge.name\n );\n // One sentence, one raceability answer (Arnaud's D-32). Both arms state\n // a MEMBERSHIP fact this operation OBSERVED — the pair it captured is\n // gone, or the slot it read empty is now held — and neither states an\n // identity the caller named: the two rows this write connects are the\n // ones the arguments spell, and the membership row is state the plan\n // discovered. So the loss of an observed membership is a race like any\n // other (rule 5, \"initial absence and loss after observation are distinct\n // failure roles\" — distinct ROLES, one raceability): the unit aborts, the\n // operation re-plans ONCE from the admitted values, and the fresh capture\n // reads the membership the race produced and converges. A repeated race\n // propagates this sentence, which is what it says to do.\n failure.meta.raceable = true;\n if (captured)\n this.requirePresent(this.queries.junction(edge, captured), failure);\n else await this.requireAbsent(query, failure);\n }\n return captured;\n }\n async remove(\n edge: Membership,\n source: Input | undefined,\n target: Input | undefined,\n keep: Input[],\n member: Member\n ): Promise<void> {\n const a = this.driver.adapter;\n const q = this.queries;\n // A removal takes related rows whose link the call may write, as its\n // lookups do: a member it cannot see keeps its link. A clear refuses a\n // member it sees and may not unlink (R3), as a disconnect naming it does.\n const domain = q.domainOf(edge.target, \"related\", linkJudgement(edge));\n const visible = q.domainOf(edge.target, \"related\");\n const keeping = (alias?: string) =>\n keep.length\n ? a.operators.not(\n a.operators.or(\n ...keep.map((row) =>\n q.lowerIdentity(\n edge.target,\n this.schema.identity(edge.target, row),\n alias\n )\n )\n )\n )\n : undefined;\n const kept = keeping();\n if (target === undefined && domain !== visible)\n await this.requireAbsent(\n q.select(\n edge.target,\n {\n take: 1,\n select: Object.fromEntries(\n this.schema.keys(edge.target).map((field) => [field, true])\n ),\n },\n { edge, parent: source! },\n { selector: visible, unless: domain, condition: kept }\n ),\n new NestedWriteError(\n `Cannot clear relation '${edge.name}': a connected record may not be disconnected by this call.`,\n edge.name\n )\n );\n if (edge.kind === \"junction\") {\n const statement = q.sharing(() => {\n const conditions: Sql[] = [];\n for (const [side, values] of [\n [edge.sourceSide, source],\n [edge.targetSide, target],\n ] as const) {\n if (!values) continue;\n conditions.push(...q.junctionSideConditions(side, undefined, values));\n }\n if (domain) {\n // The join row is the DELETE's own table: its columns are qualified\n // by that table's name, never left to resolve inside the subquery.\n const member = q.alias();\n conditions.push(\n a.operators.exists(\n a.subqueries.existsCheck(\n q.table(edge.target, member),\n a.operators.and(\n ...edge.targetSide.members.map((pair) =>\n a.operators.eq(\n a.identifiers.column(edge.table, pair.junctionField),\n q.column(edge.target, pair.referencedField, member)\n )\n ),\n q.lowerSelector(domain, member)!\n )\n )\n )\n );\n }\n if (keep.length)\n conditions.push(\n a.operators.not(\n a.operators.or(\n ...keep.map((row) =>\n a.operators.and(\n ...q.junctionSideConditions(edge.targetSide, undefined, row)\n )\n )\n )\n )\n );\n return a.mutations.delete(\n a.identifiers.table(edge.table),\n a.operators.and(...conditions)\n );\n });\n await this.#effect(\n statement,\n this.statementContext(edge.source, \"update\"),\n member\n );\n return;\n }\n // The rows it unlinks, addressed under `alias` (none: the UPDATE's own\n // table).\n const unlinked = (alias?: string) => {\n const others = keeping(alias);\n return a.operators.and(\n ...edge.pairs.map((pair) =>\n a.operators.eq(\n q.column(edge.target, pair.target, alias),\n q.fieldValue(edge.target, pair.target, source![pair.source])\n )\n ),\n ...(edge.discriminator\n ? [\n a.operators.eq(\n q.column(edge.target, edge.discriminator.field, alias),\n q.value(edge.discriminator.value)\n ),\n ]\n : []),\n ...(target\n ? [\n q.lowerIdentity(\n edge.target,\n this.schema.identity(edge.target, target),\n alias\n ),\n ]\n : []),\n ...(others ? [others] : []),\n ...(domain ? [q.lowerSelector(domain, alias)!] : [])\n );\n };\n const clearability = edge.clearability as Extract<\n Membership[\"clearability\"],\n { kind: \"columns\" }\n >;\n const cleared = Object.fromEntries(\n clearability.fields.map((field) => [field, null])\n );\n // Each row it unlinks produces a row without the link, judged at what\n // judged its link (R4).\n let produced: Sql | undefined;\n const statement = q.sharing(() => {\n produced = this.#produce(\n edge.target,\n cleared,\n linkJudgement(edge),\n unlinked\n );\n return a.mutations.update(\n q.table(edge.target),\n sql.join(this.#updateAssignments(edge.target, cleared), \", \"),\n produced ?? unlinked()\n );\n });\n await this.#effect(\n statement,\n this.statementContext(edge.target, \"update\"),\n member,\n produced\n ? {\n model: edge.target,\n refusal: nestedRefusal(\"disconnect\", edge.name),\n }\n : undefined\n );\n }\n /** One admitted payload, one prepared update: `Queries` is the sole interpreter. */\n #updateAssignments(model: AnyModel, values: Input): Sql[] {\n return Object.entries(values).map(([field, value]) =>\n this.queries.updateAssignment(model, field, value)\n );\n }\n /**\n * What the row a write of `model` produces is judged at under this call's\n * domain (R4): its placement for a create (no `judgement`), the\n * predicates that judged its old row for an update. `undefined` where\n * nothing judges it.\n */\n #produced(\n model: AnyModel,\n judgement?: RowJudgement\n ): PreparedSelector | undefined {\n return this.queries.domain?.produced(model, judgement);\n }\n /**\n * The WHERE of an UPDATE of `model` that judges the rows it produces\n * (R4, {@link Queries.producedWhere}): the rows `candidates` selects (the\n * first `limit` in key order), each at the predicates that judged its old\n * row (`judgement`) and outside its own subtree for the acyclic relations\n * whose key it writes. `judgedCandidates`: `candidates` states the old\n * row's judgement in the same statement, so a judgement the write cannot\n * change is not stated again. `undefined` where nothing judges them: the\n * statement keeps its own WHERE and its bytes.\n */\n #produce(\n model: AnyModel,\n values: Input,\n judgement: RowJudgement | undefined,\n candidates: (alias: string) => Sql | undefined,\n limit?: number,\n judgedCandidates = true\n ): Sql | undefined {\n const domain = this.queries.domain;\n if (judgement === undefined || domain === undefined) return undefined;\n return this.queries.producedWhere(\n model,\n candidates,\n values,\n domain.produced(\n model,\n judgement,\n judgedCandidates ? Object.keys(values) : undefined\n ),\n domain.cycles(model, judgement),\n limit\n );\n }\n /** A root write's refusal of the row it produces (§5.3). */\n get #forbidden(): PreparedGuardFailure {\n return {\n kind: \"forbidden\",\n message: `${this.operation} produced a row that is not permitted.`,\n raceable: false,\n };\n }\n /**\n * Dispatch one judged statement: its assertion failing is the write's\n * refusal, raised as `refusal` says, with nothing written.\n */\n async #judging<T>(\n judged: JudgedWrite | undefined,\n run: () => Promise<T>\n ): Promise<T> {\n if (judged === undefined) return run();\n try {\n return await run();\n } catch (error) {\n if (!(error instanceof NestedWriteAssertionError)) throw error;\n throw this.#refusal(judged);\n }\n }\n #refusal({ model, refusal }: JudgedWrite): Error {\n return createFailureError(refusal, model[\"~\"].names.ts!, this.operation);\n }\n /**\n * Queue one judged statement: the batch that carries it attributes its\n * assertion to `refusal` ({@link submit}); an array owner, to its packaged\n * guard at the same position.\n */\n #queueJudged(\n statement: Sql,\n context: QueryExecutionContext,\n member: Member | undefined,\n judged: JudgedWrite | undefined,\n probe?: Sql\n ): BatchQuery {\n if (judged === undefined) return this.#queue(statement, context, member);\n if (this.#ownership === \"batch-preparation\")\n (this.#preparedGuardList ??= []).push({\n queryIndex: this.queued.length,\n premise: \"exists\",\n probe: sql`SELECT 1`,\n failure: judged.refusal,\n model: judged.model[\"~\"].names.ts!,\n operation: this.operation,\n });\n const queued = this.#queue(statement, context, member);\n const reference = this.#attemptStore?.scratchId;\n this.#attempt.judgeWrite(queued, {\n refusal: this.#refusal(judged),\n ...(probe &&\n !(reference !== undefined && probe.values.includes(reference)) && {\n probe,\n }),\n });\n return queued;\n }\n /**\n * A nested `updateMany` / `deleteMany` as ONE correlated statement.\n *\n * The membership and the member filter are both predicates this statement\n * carries, so the operation needs no planning read: the provider answers\n * `WHERE fk = parent AND filter` after every earlier statement of the body\n * has run, which is the shipped `buildUpdateMany` / `buildDeleteMany` shape\n * (`write-engine/RelationWritePart.ts:484-504`, `:674-693`) and rule 6's\n * \"keep scalar bulk work set-oriented\". Zero matched rows is a silent\n * success, so there is no postcondition to state.\n */\n async mutateMembers(\n edge: Membership,\n parent: Input,\n selector: PreparedSelector,\n values: Input | undefined,\n member: Member\n ): Promise<void> {\n const q = this.queries;\n const a = this.driver.adapter;\n const model = edge.target;\n let produced: Sql | undefined;\n const statement = q.sharing(() => {\n const filter = q.lowerMutationLimit(model, selector, undefined).where;\n // The rows it produces, judged at what judged them (R4).\n produced =\n values &&\n this.#produce(model, values, selector.judgement, (alias) =>\n a.operators.and(\n q.memberWhere(edge, parent, alias),\n ...(selector.predicate ? [q.lowerSelector(selector, alias)!] : [])\n )\n );\n const where = a.operators.and(\n // The target's own table name is the correlation alias, exactly as the\n // shipped builders passed `getTableName(childScope.model)`.\n q.memberWhere(edge, parent, model[\"~\"].names.sql!),\n ...(filter ? [filter] : [])\n );\n return values\n ? a.mutations.update(\n q.table(model),\n sql.join(this.#updateAssignments(model, values), \", \"),\n produced ?? where\n )\n : a.mutations.delete(q.table(model), where);\n });\n await this.#effect(\n statement,\n this.statementContext(model, values ? \"updateMany\" : \"deleteMany\"),\n member,\n produced\n ? { model, refusal: nestedRefusal(\"updateMany\", edge.name) }\n : undefined\n );\n }\n async delete(model: AnyModel, row: Input, member: Member): Promise<void> {\n await this.#effect(\n this.driver.adapter.mutations.delete(\n this.queries.table(model),\n this.queries.lowerIdentity(model, this.schema.identity(model, row))\n ),\n this.statementContext(model, \"delete\"),\n member\n );\n }\n async #effect(\n statement: Sql,\n context: QueryExecutionContext,\n member: Member,\n judged?: JudgedWrite\n ): Promise<void> {\n if (this.usesBatch) this.#queueJudged(statement, context, member, judged);\n else\n await this.dispatch(1, false, () =>\n this.#judging(judged, () =>\n this.#transport._execute(statement, context)\n )\n );\n }\n}\n","import { ValidationError } from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\nimport type { Operation } from \"../../types\";\nimport { namedGatedFields, type PreparedDomain } from \"./query\";\nimport type { Arguments, EngineSchema, Input } from \"./schema\";\n\n/**\n * Projection keys a domain declares, admitted beside the shared schema (K5).\n *\n * The `select` and `include` schemas are the schema's, shared by every chain\n * over it, and refuse a key they do not declare. So a call whose domain\n * declares a projection key has that key taken out of every node of its\n * projection before admission and put back, by path, into the node admission\n * returned; the node's read-gated fields the caller named are marked on the\n * `select` admission returned, which names every scalar of a node an\n * `include` or an `omit` spelled. Nothing else changes: a call that names no\n * key and no gated field is admitted as it was written.\n */\n\n/** The verbs whose results are rows: the only ones a projection reaches. */\nconst ROW_RESULTS: ReadonlySet<Operation> = new Set<Operation>([\n \"findMany\",\n \"findFirst\",\n \"findUnique\",\n \"create\",\n \"update\",\n \"upsert\",\n \"delete\",\n \"createMany\",\n \"updateMany\",\n \"deleteMany\",\n]);\n\ntype Container = \"select\" | \"include\";\n\n/** What one node of a call's projection said that admission does not keep. */\ninterface Plan {\n /** The declared key the node named, in which container, with its value. */\n readonly key?: {\n readonly name: string;\n readonly container: Container;\n readonly value: unknown;\n };\n /** Its `select` named the key alone: a key field stood in for admission. */\n readonly bare: boolean;\n /** Its read-gated fields the caller named. */\n readonly named: ReadonlySet<string>;\n readonly children: readonly {\n readonly path: readonly string[];\n readonly model: AnyModel;\n readonly plan: Plan;\n }[];\n}\n\n/**\n * One node, its declared key taken out: `undefined` where neither it nor a\n * node below says anything admission would not keep. Each container is read\n * once and every container on the path is copied, so admission reads the\n * values this walk read.\n */\nfunction strip(\n domain: PreparedDomain,\n schema: EngineSchema,\n model: AnyModel,\n node: unknown\n): readonly [Input, Plan] | undefined {\n if (!isPlainRecord(node)) return undefined;\n const facts = domain.projected(model);\n const read = {\n select: node.select,\n include: node.include,\n };\n const omit = isPlainRecord(node.omit) ? node.omit : undefined;\n const copies: Partial<Record<Container, Record<string, unknown>>> = {};\n const children: { path: readonly string[]; model: AnyModel; plan: Plan }[] =\n [];\n let key: Plan[\"key\"];\n for (const container of [\"select\", \"include\"] as const) {\n const given = read[container];\n if (!isPlainRecord(given)) continue;\n let copy: Record<string, unknown> | undefined;\n for (const name of Object.keys(given)) {\n const value = given[name];\n if (facts?.keys.has(name)) {\n key = { name, container, value };\n copy ??= { ...given };\n delete copy[name];\n continue;\n }\n const resolved = model[\"~\"].state.relations[name]\n ? schema.index.get(model)?.get(name)\n : undefined;\n if (resolved === undefined) continue;\n const variant =\n !resolved.member &&\n (resolved.edge.kind === \"variantRowCarrier\" ||\n resolved.edge.kind === \"variantJunctionCarrier\");\n if (variant) {\n if (!isPlainRecord(value)) continue;\n const many = resolved.edge.kind === \"variantJunctionCarrier\";\n const arms = many ? value.variants : value;\n if (!isPlainRecord(arms)) continue;\n let nextArms: Record<string, unknown> | undefined;\n for (const member of resolved.edge.members) {\n const target = schema.membership(model, name, member.variant).target;\n const child = strip(domain, schema, target, arms[member.variant]);\n if (child === undefined) continue;\n (nextArms ??= { ...arms })[member.variant] = child[0];\n children.push({\n path: [\n container,\n name,\n ...(many ? [\"variants\"] : []),\n member.variant,\n ],\n model: target,\n plan: child[1],\n });\n }\n if (nextArms)\n (copy ??= { ...given })[name] = many\n ? { ...value, variants: nextArms }\n : nextArms;\n continue;\n }\n const target = schema.membership(model, name).target;\n const child = strip(domain, schema, target, value);\n if (child === undefined) continue;\n (copy ??= { ...given })[name] = child[0];\n children.push({ path: [container, name], model: target, plan: child[1] });\n }\n if (copy) copies[container] = copy;\n }\n const select = isPlainRecord(read.select) ? read.select : undefined;\n const named = new Set<string>();\n for (const field of facts?.gates.keys() ?? []) {\n const given = select\n ? select[field] === true && omit?.[field] !== true\n : omit?.[field] === false;\n if (given) named.add(field);\n }\n if (key === undefined && children.length === 0 && named.size === 0)\n return undefined;\n // An `include` that named the key alone is no `include`.\n const emptied =\n copies.include !== undefined && Object.keys(copies.include).length === 0;\n const { include: _included, ...rest } = node;\n const next: Input = emptied ? rest : { ...node };\n let bare = false;\n if (copies.select) {\n bare = Object.keys(copies.select).length === 0;\n next.select = bare ? { [schema.keys(model)[0]!]: true } : copies.select;\n }\n if (copies.include && !emptied) next.include = copies.include;\n return [next, { key, bare, named, children }];\n}\n\n/** A key's admitted value: `true`, `false` or a list of the names it declares. */\nfunction admitKey(\n domain: PreparedDomain,\n model: AnyModel,\n key: NonNullable<Plan[\"key\"]>,\n path: string,\n operation: Operation\n): unknown {\n const { value } = key;\n if (typeof value === \"boolean\") return value;\n const names = domain.projected(model)!.keys.get(key.name)!.names;\n if (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every(\n (name) =>\n typeof name === \"string\" &&\n names.some(([declared]) => declared === name)\n )\n )\n return Object.freeze([...value]);\n throw new ValidationError(\n operation,\n [\n {\n path: `${path}${key.container}.${key.name}`,\n message: `expected true, false or a list of ${names.map(([name]) => name).join(\", \")}`,\n },\n ],\n { meta: { model: model[\"~\"].names.ts! } }\n );\n}\n\n/** `admitted`, one node admission returned, with what its plan kept aside. */\nfunction attach(\n domain: PreparedDomain,\n schema: EngineSchema,\n model: AnyModel,\n admitted: Input,\n plan: Plan,\n path: string,\n operation: Operation\n): Input {\n const next: Input = { ...admitted };\n for (const child of plan.children) {\n let holder = next;\n for (const [index, name] of child.path.entries()) {\n const value = holder[name];\n if (!isPlainRecord(value)) break;\n const nextValue =\n index === child.path.length - 1\n ? attach(\n domain,\n schema,\n child.model,\n value,\n child.plan,\n `${path}${child.path.join(\".\")}.`,\n operation\n )\n : { ...value };\n holder[name] = nextValue;\n holder = nextValue;\n }\n }\n if (plan.key) {\n const value = admitKey(domain, model, plan.key, path, operation);\n const { container } = plan.key;\n if (plan.bare) next.select = {};\n if (value !== false) {\n const holder = next[container];\n next[container] = {\n ...(isPlainRecord(holder) ? holder : {}),\n [plan.key.name]: value,\n };\n }\n }\n if (plan.named.size > 0 && isPlainRecord(next.select))\n namedGatedFields.set(next.select, plan.named);\n return next;\n}\n\n/**\n * `raw` admitted by `admit` with the projection keys and named gated fields\n * of `domain` kept: as `admit(raw)` where the call names neither.\n */\nexport function admitProjected(\n domain: PreparedDomain,\n schema: EngineSchema,\n model: AnyModel,\n operation: Operation,\n raw: unknown,\n admit: (raw: unknown) => Arguments\n): Arguments {\n const stripped = ROW_RESULTS.has(operation)\n ? strip(domain, schema, model, raw)\n : undefined;\n if (stripped === undefined) return admit(raw);\n const [node, plan] = stripped;\n return attach(\n domain,\n schema,\n model,\n admit(node) as Input,\n plan,\n \"\",\n operation\n ) as Arguments;\n}\n","import { NestedWriteError, UnsupportedOperationError } from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport { type SelectorFacts, wholeValue } from \"../shared/query\";\nimport type { Input } from \"../shared/schema\";\nimport type { Membership } from \"../shared/storage\";\n\nexport type Origin = {\n relation: string;\n operation: string;\n order: number;\n slot?: string;\n};\nexport type MembershipContribution = {\n origin: Origin;\n scope: Membership[\"scope\"];\n identity?: SelectorFacts;\n};\n/**\n * One requested final value, and — where the write is a relation's — the\n * RELATION that value has to be able to represent.\n *\n * `relation` is stated by the one reader of the resolved edge\n * ({@link Commands.assignMembership}) and by nothing else, so it marks exactly\n * the components a concrete reference supplies out of another row: a\n * `disconnect`'s explicit NULL is a literal this row asked for and carries no\n * relation, and a junction's captured pair is not a row's own field at all.\n * Its consumer is the requirement every such component must meet\n * ({@link CommandExecution.stored}).\n */\nexport type FieldValue = (\n | { kind: \"literal\"; value: unknown }\n | { kind: \"field\"; producer: Assignments; field: string }\n) & { relation?: string };\n\nfunction literal(value: unknown): FieldValue {\n return { kind: \"literal\", value };\n}\n\n/** One row's requested final fields and exact symbolic consumers. */\nexport class Assignments {\n readonly demands = new Set<string>();\n readonly #writes = new Map<string, FieldValue>();\n readonly #requested = new Set<string>();\n readonly #held = new Map<\n string,\n { readonly value: FieldValue; readonly holder: Assignments }\n >();\n #refusal: Error | undefined;\n readonly model: AnyModel;\n readonly operation: \"create\" | \"update\" | \"select\";\n readonly captured: Assignments | undefined;\n private readonly forwarded: Assignments[];\n readonly deferred: boolean;\n constructor(\n model: AnyModel,\n operation: \"create\" | \"update\" | \"select\",\n values: Input = {},\n explicit: Input = values,\n captured?: Assignments,\n forwarded: Assignments[] = [],\n deferred = false\n ) {\n this.model = model;\n this.operation = operation;\n this.captured = captured;\n this.forwarded = forwarded;\n this.deferred = deferred;\n for (const [field, value] of Object.entries(values)) {\n this.#writes.set(field, literal(value));\n if (explicit[field] !== undefined) this.#requested.add(field);\n }\n }\n /**\n * The VALUE a stored payload names, or `undefined` when it names an\n * OPERATION instead (`{ increment: 2 }`).\n *\n * `Assignments` stores the ADMITTED payload verbatim — that payload is what\n * the row's own write submits, and `Queries.prepareUpdate` is its ONE\n * interpreter. Reading the value out of the update envelope is a question\n * only the key-reconciliation readers ask (\"which value will this key\n * hold?\"), so the answer is computed HERE, lazily, and never written back:\n * unwrapping at storage time made `prepareUpdate` interpret a second time,\n * which is `Unknown update operation: z` for a JSON document and a silent\n * rewrite for a document that carries its own `set` key.\n *\n * The envelope exists only in the UPDATE language. A create's payload is\n * already the value, so a created document spelled `{ set: … }` is that\n * document and nothing is unwrapped.\n */\n #named(assignment: FieldValue): FieldValue | undefined {\n if (assignment.kind !== \"literal\" || this.operation !== \"update\")\n return assignment;\n const whole = wholeValue(assignment.value);\n return whole ? { ...assignment, value: whole.value } : undefined;\n }\n /** Whether the caller spelled this value, independently of generated defaults. */\n isRequested(field: string): boolean {\n return this.#requested.has(field);\n }\n /**\n * What this field will hold, as far as the payload states it: the named\n * value when there is one, and otherwise the payload itself — an operator's\n * result is not knowable before the provider computes it, and the reader\n * that consumes this one keeps the shipped behaviour for that shape.\n */\n stated(field: string): FieldValue | undefined {\n const assignment = this.#writes.get(field);\n if (assignment === undefined) return undefined;\n return this.#named(assignment) ?? assignment;\n }\n field(field: string): FieldValue {\n this.demands.add(field);\n for (const producer of this.forwarded) producer.field(field);\n return { kind: \"field\", producer: this, field };\n }\n /**\n * A value this row is already KNOWN to hold, stated by the fact that\n * selected it rather than requested by a payload.\n *\n * The one teller is a correlated relation arm (`RelationBody`): its target\n * is the row the parent's own membership value names, so the edge's\n * referenced fields hold that value before anything is read. It is not a\n * request — nothing is `requested`, so it conflicts with nothing and no\n * write submits it — and the observation still wins, because\n * `CommandAttempt.read` answers a bound row first: the located bytes remain\n * the contract a `connect` writes.\n */\n restate(field: string, value: FieldValue): void {\n this.#writes.set(field, value);\n }\n forward(producer: Assignments): void {\n this.forwarded.push(producer);\n for (const field of this.demands) producer.field(field);\n }\n known(field: string): FieldValue | undefined {\n const assignment = this.#writes.get(field);\n if (assignment?.kind === \"field\")\n return assignment.producer.known(assignment.field);\n return assignment && this.#named(assignment);\n }\n writesField(field: string): boolean {\n return this.#writes.has(field);\n }\n /**\n * A value an effect of this operation has ALREADY left this row holding.\n *\n * A CORRELATED arm's target is the row this one's membership already names,\n * so when that arm's own write moves the key it references the provider\n * moves this row with it (`ON UPDATE CASCADE`) — before this row's own\n * statement runs. That value is neither the payload, which states what this\n * row's statement will LEAVE, nor a request, which that statement submits:\n * it is the row BETWEEN the two, and every consumer placed after the arm —\n * the row's own statement, its later children, the terminal read — names the\n * row by it (N5). A correlated CHOICE holds it and requests it both: its\n * found arm is the row this one points at, its missing arm a row only this\n * row's own write can point it at.\n */\n hold(field: string, value: FieldValue, holder: Assignments): void {\n this.#held.set(field, { value, holder });\n }\n /**\n * What an effect of this operation already moved on this row — nothing, or\n * the values the observation it holds of the row is re-addressed from.\n *\n * A hold is stated at PLAN time, from the HOLDER's payload: that write is\n * what the provider would carry this row along with. Which arm RAN is an\n * execution fact, so the caller answers `ran` — a held pair whose holder did\n * not run moved nothing, and the row is still where the observation located\n * it. {@link Assignments.movesField} asks the plan-time question instead\n * (MIGHT this move), because an ordering must hold for both arms.\n */\n moved(\n ran: (holder: Assignments) => boolean\n ): Record<string, FieldValue> | undefined {\n const moved: Record<string, FieldValue> = {};\n for (const [field, { value, holder }] of this.#held)\n if (ran(holder)) moved[field] = value;\n return Object.keys(moved).length === 0 ? undefined : moved;\n }\n movesField(field: string): boolean {\n return this.#held.has(field);\n }\n /** Whether a stated value of this write is read from `producer` (N1: the cycle test). */\n consumes(producer: Assignments): boolean {\n for (const value of this.#writes.values())\n if (value.kind === \"field\" && value.producer === producer) return true;\n return false;\n }\n contribute(field: string, value: FieldValue, failure: string): void {\n const previous = this.#writes.get(field);\n if (previous && this.#requested.has(field) && !this.#equal(previous, value))\n this.reject(new UnsupportedOperationError(failure));\n this.#writes.set(field, value);\n this.#requested.add(field);\n }\n requireLiteral(field: string, relation: string): void {\n const assignment = this.#writes.get(field);\n if (!assignment || assignment.kind === \"field\") return;\n // The relation key must be given a VALUE. `{ set: 'x' }` names one and is\n // legal (the sentence says so); `{ increment: 1 }` names an operation the\n // relation write cannot reconcile, and a whole object is not a key.\n const value = this.#named(assignment);\n if (\n value?.kind === \"literal\" &&\n (value.value === null || typeof value.value !== \"object\")\n )\n return;\n this.reject(\n new NestedWriteError(\n `Cannot update relation key field '${field}' with a non-literal operation while mutating relation '${relation}'. Use a literal value or '{ set: ... }'.`,\n relation,\n { meta: { operation: \"update\", field, relation } }\n )\n );\n }\n reject(failure: Error): void {\n if (!this.deferred) throw failure;\n this.#refusal ??= failure;\n }\n activate(): void {\n if (this.#refusal) throw this.#refusal;\n }\n absorb(\n field: string,\n source: Assignments,\n referenced: string,\n failure: string\n ): void {\n const previous = this.#writes.get(field);\n if (!previous) return;\n const known = source.known(referenced);\n if (\n !known ||\n known.kind !== \"literal\" ||\n known.value === null ||\n !this.#equal(known, previous)\n )\n this.reject(new UnsupportedOperationError(failure));\n this.#writes.delete(field);\n this.#requested.delete(field);\n }\n writtenFields(): readonly string[] {\n return [...this.#writes.keys()];\n }\n contributions(): ReadonlyMap<string, FieldValue> {\n return this.#writes;\n }\n #equal(left: FieldValue, right: FieldValue): boolean {\n if (\n left.kind === \"field\" &&\n right.kind === \"field\" &&\n left.producer === right.producer &&\n left.field === right.field\n )\n return true;\n const a =\n left.kind === \"literal\"\n ? this.#named(left)\n : left.producer.known(left.field);\n const b =\n right.kind === \"literal\"\n ? this.#named(right)\n : right.producer.known(right.field);\n return (\n a?.kind === \"literal\" &&\n b?.kind === \"literal\" &&\n Object.is(a.value, b.value)\n );\n }\n select(fields: readonly string[]): Record<string, FieldValue> {\n return Object.fromEntries(\n fields.map((field) => [field, this.field(field)])\n );\n }\n}\n","import type { Query } from \"../shared/query\";\nimport type { Input } from \"../shared/schema\";\nimport { TransportAttempt } from \"../shared/transport-attempt\";\nimport type { Assignments, FieldValue } from \"./assignments\";\nimport type {\n Choose,\n CommandOccurrence,\n Deletion,\n JunctionCapture,\n RecordCommand,\n Selection,\n SeriesOccurrence,\n} from \"./commands\";\n\n/** Database observations and field transports belonging to one command attempt. */\nexport class CommandAttempt {\n constructor(readonly transport = new TransportAttempt()) {}\n readonly rows = new Map<Selection, Input>();\n readonly retained = new Set<Selection>();\n readonly junctions = new Map<JunctionCapture, Input>();\n readonly missingChoices = new Map<object, Choose>();\n readonly conditionalSkips = new Map<unknown, Choose>();\n readonly series = new Map<\n CommandOccurrence<SeriesOccurrence>,\n {\n readonly members: CommandOccurrence<RecordCommand | Deletion>[];\n readonly parentRequirement?: {\n readonly query: Query;\n readonly failure: Error;\n };\n }\n >();\n readonly #bindings = new Map<Assignments, Input>();\n\n bind(fields: Assignments, values: Input): void {\n this.#bindings.set(fields, values);\n }\n /**\n * The runtime VALUE of one field: a bound row value, else what the payload\n * states. `stated` is the key-reconciliation reader — it resolves the update\n * envelope — while {@link values} submits the admitted payload verbatim, so\n * a referenced key crosses as `'u1'` and the row's own write still carries\n * `{ set: 'u1' }` to its one interpreter.\n */\n read(fields: Assignments, field: string): unknown {\n const bound = this.#bindings.get(fields);\n // A value this operation PRODUCED is an expression inside the unit that\n // stored it and the literal that unit read back in every unit after it\n // (D-58, `TransportAttempt.carried`); one reader, so every statement,\n // premise and guard names the same value.\n if (bound && Object.hasOwn(bound, field))\n return this.transport.carried(bound[field]);\n const value = fields.stated(field);\n return value\n ? this.#resolveValue(value)\n : fields.captured && this.read(fields.captured, field);\n }\n #resolveValue(value: FieldValue): unknown {\n return value.kind === \"literal\"\n ? value.value\n : this.read(value.producer, value.field);\n }\n resolve(fields: Record<string, FieldValue>): Input {\n return Object.fromEntries(\n Object.entries(fields).map(([field, value]) => [\n field,\n this.#resolveValue(value),\n ])\n );\n }\n values(fields: Assignments): Input {\n return Object.fromEntries(\n [...fields.contributions()].map(([field, value]) => [\n field,\n this.#resolveValue(value),\n ])\n );\n }\n select(fields: Assignments, names: Iterable<string>): Input {\n return Object.fromEntries(\n [...names].map((field) => [field, this.read(fields, field)])\n );\n }\n materialize(fields: Assignments, values: Input): void {\n this.bind(fields, { ...this.#bindings.get(fields), ...values });\n }\n}\n","import { type AnyModel, getModelKeyCatalog } from \"@schema/model\";\nimport type {\n PreparedProjection,\n PreparedSelector,\n SelectorFacts,\n} from \"../shared/query\";\nimport type { RowJudgement, RowPurpose } from \"../shared/row-scope\";\nimport type { Input } from \"../shared/schema\";\nimport type { Membership } from \"../shared/storage\";\nimport { storedFields } from \"../shared/storage\";\nimport { Assignments, type Origin } from \"./assignments\";\nimport type { CommandExecution } from \"./execution\";\n\nexport interface BoundMembership {\n readonly edge: Membership;\n readonly parent: Assignments;\n}\n/**\n * A failure a PLAN knows how to build, not one it owns.\n *\n * Every one of these sentences is a pure function of construction-time facts —\n * the verb and the relation name — so the plan carries the recipe and the one\n * site that actually raises it builds it. Constructing them while nothing has\n * failed ran the whole `VibORMError` constructor (two stack captures, two\n * metadata sanitisations) on the success path of every nested write, which the\n * G4 cutover diagnosis measured (`g4/cutover/perf-diagnosis.md` §4.1, cause\n * 1b). The thunk is called EXACTLY where the old value was raised or handed to\n * an assertion, so the error a caller sees is byte-identical.\n */\nexport type DeferredFailure = () => Error;\nexport type SelectionSource =\n | {\n readonly kind: \"query\";\n readonly where?: Input;\n /**\n * `where` was admitted as a UNIQUE selector whose shipped counterpart is\n * `buildWhereUnique`, so its addressable entries name the row through the\n * constraint (`Queries.prepareSelector`). The root verbs' lookups state\n * it themselves; for a nested write's target the one owner of the answer\n * is {@link nestedTargetAddressesConstraint}. A bulk member's `where`\n * (`updateMany` / `deleteMany`) is a filter by contract and never asks.\n * Ignored when the caller prepares `selector` itself.\n */\n readonly unique?: boolean;\n readonly selector?: PreparedSelector;\n readonly membership?: BoundMembership;\n /**\n * Whose rows this lookup takes: the call's own (`root`) or rows reached\n * through a relation (`related`), conjoined with its selector. Absent,\n * the lookup is a premise or physical and takes its selector as handed.\n */\n readonly purpose?: RowPurpose;\n /** Beside `purpose`, the verb a write's lookup is judged at (R3). */\n readonly judgement?: RowJudgement;\n }\n | {\n readonly kind: \"producer\";\n readonly where?: Input;\n readonly unique?: boolean;\n readonly selector?: PreparedSelector;\n readonly producer: Assignments;\n readonly purpose?: RowPurpose;\n readonly judgement?: RowJudgement;\n };\n\n/**\n * The nested verbs that address a single target row, spelled as the case labels\n * of `RelationBody.relation`'s own switch. The type is the wiring: a nested verb\n * added to the filter family that forgets to consult the predicate below is a\n * typecheck error at its call site, not a silent \"discriminator\" default.\n */\nexport type NestedTargetVerb =\n | \"connect\"\n | \"connectOrCreate\"\n | \"delete\"\n | \"disconnect\"\n | \"set\"\n | \"update\"\n | \"upsert\";\n\n/**\n * Whether a nested write's unique target selector names its row through the\n * constraint. The shipped engine answers this from the EDGE's own compiler,\n * not from the verb alone:\n *\n * - a JUNCTION target is a discriminator in both phases. Its planning probe is\n * `buildFindUnique` (`write-engine/RelationJunctionPart.ts:1509`, `:1629`,\n * `:1663`) and its batch statement passes the selector as `whereUnique`\n * (`:1698`, `:2146`, `:2259`), which `JunctionStatements.ts:322-323`\n * compiles with `buildWhereUnique` — whichever verb addressed it.\n * - a REFERENCE-held target of `disconnect` / `delete` / `update` is the one\n * family the shipped engine recombines as `{ field: { equals: value } }`\n * through `uniqueSelectorConjuncts` (`write-engine/shared.ts:671`, reached\n * from `RelationWritePart.ts:987`, `UpdateOperation.ts:469` and\n * `RecordUpdateCompiler.ts:3722`) and hands to `buildWhere`, so it is a\n * FILTER and keeps the engine's case-sensitivity contract.\n */\nexport function nestedTargetAddressesConstraint(\n edge: Membership,\n verb: NestedTargetVerb\n): boolean {\n return (\n edge.kind === \"junction\" ||\n (verb !== \"disconnect\" && verb !== \"delete\" && verb !== \"update\")\n );\n}\n\nexport function membershipFields(edge: Membership): string[] {\n return edge.kind === \"reference\"\n ? [\n ...edge.pairs.map((pair) => pair.source),\n ...(edge.discriminator?.side === \"source\"\n ? [edge.discriminator.field]\n : []),\n ]\n : edge.sourceSide.members.map((pair) => pair.referencedField);\n}\n/**\n * One junction row's columns: each present side's referenced fields, read\n * through `read` — the planned assignment, or the attempt's executed value.\n */\nexport function junctionPairs<T>(\n edge: Extract<Membership, { kind: \"junction\" }>,\n read: (owner: Assignments, field: string) => T,\n source?: Assignments,\n target?: Assignments\n): Record<string, T> {\n const pairs: [string, T][] = [];\n for (const [side, owner] of [\n [edge.sourceSide, source],\n [edge.targetSide, target],\n ] as const)\n if (owner)\n for (const pair of side.members)\n pairs.push([pair.junctionField, read(owner, pair.referencedField)]);\n return Object.fromEntries(pairs);\n}\n\n/** A prepared row selection; observations and transport values belong to execution. */\nexport class Selection {\n readonly kind = \"lookup\";\n readonly fields: Assignments;\n readonly facts: SelectorFacts;\n readonly selector: PreparedSelector;\n readonly #rowProjection: PreparedProjection;\n readonly #identityProjection: PreparedProjection;\n origin?: Origin;\n retained?: DeferredFailure;\n membershipOnly?: boolean;\n /**\n * The answer depends on an earlier write of this operation (N1): the read is\n * taken at its execution point, after that write — on the batch route through\n * the barrier that submits the queued unit with its premises and reads in the\n * same native batch ({@link OperationContext.flush}), never the raw read that\n * would race a queued write.\n */\n dependent?: boolean;\n /**\n * THIS operation inserts the key this selector names when the row is absent:\n * the missing arm of an `upsert` or a `connectOrCreate`. Such a probe reads\n * without locking — the PROBE alone ({@link query}); the other reads this\n * selection answers keep the lock their own answer earns.\n *\n * A locking read cannot protect an absence, and asking for one costs the\n * operation its own convergence. MySQL answers a miss on a unique index with\n * a gap lock over the index supremum; the two racers hold that same gap lock\n * AT ONCE (gap locks do not exclude each other), and the insert-intention\n * each of them then requests waits for the other's gap — a cycle InnoDB\n * breaks by aborting one whole transaction (`ER_LOCK_DEADLOCK`). Measured\n * both ways under `r2c/receipts/`: with the lock, two `X GRANTED` gaps on the\n * supremum pseudo-record and a deadlock; without it, no lock at all, and the\n * loser's INSERT is refused by the unique constraint.\n *\n * That refusal is the arbiter the create arm already relies on (Pin Rule 2:\n * no `notExists` premise precedes the create INSERT), and the retryable\n * signal {@link CommandExecution.recover} converges on. PostgreSQL locks\n * nothing for a miss and the batch route asks for no lock at all, so an\n * unlocked probe is the answer the other two routes already give.\n */\n insertsWhenAbsent?: boolean;\n /**\n * A LAX lookup judged at its verb (R3) answers \"nothing\" for an empty slot\n * and for a member the verb may not take alike; only the first is a no-op.\n * `addressed` is what the lookup takes before the verb's judgement, and\n * `failure` refuses a member there outside its candidates\n * ({@link outsideVerb}), so the call never succeeds keeping it.\n */\n unjudged?: {\n readonly addressed: PreparedSelector;\n readonly failure: DeferredFailure;\n };\n\n private readonly execution: CommandExecution;\n readonly model: AnyModel;\n readonly source: SelectionSource;\n /**\n * The verb a write of the row this selection locates is judged at (R3),\n * and so the row it produces (R4); `undefined` where nothing judges it.\n */\n readonly judgement: RowJudgement | undefined;\n readonly required: DeferredFailure | undefined;\n\n constructor(\n execution: CommandExecution,\n model: AnyModel,\n source: SelectionSource,\n required?: DeferredFailure,\n facts?: SelectorFacts\n ) {\n this.execution = execution;\n this.model = model;\n this.source = source;\n this.required = required;\n const queries = execution.context.queries;\n this.fields = new Assignments(model, \"select\");\n const selector =\n source.selector ??\n queries.prepareSelector(model, source.where, source.unique === true);\n this.selector =\n source.purpose === undefined\n ? selector\n : queries.candidates(\n selector,\n source.purpose,\n undefined,\n source.judgement\n );\n this.judgement = source.judgement ?? this.selector.judgement;\n this.facts = facts ?? queries.selectorFacts(this.selector);\n this.#rowProjection = queries.prepareProjection(\n model,\n {\n select: Object.fromEntries(\n storedFields(execution.context.schema, model).map((field) => [\n field,\n true,\n ])\n ),\n },\n true\n );\n this.#identityProjection = queries.prepareProjection(\n model,\n {\n select: Object.fromEntries(\n execution.context.schema.keys(model).map((field) => [field, true])\n ),\n },\n true\n );\n }\n membership() {\n return this.source.kind === \"query\" ? this.source.membership : undefined;\n }\n /** Whether this selector states only the captured row's complete identity. */\n identityOnly(): boolean {\n const selected = this.selector.uniqueKey;\n return (\n this.selector.scoped === undefined &&\n selected !== undefined &&\n selected === getModelKeyCatalog(this.model).rowKey &&\n this.facts.keys.size === selected.fields.length\n );\n }\n #bindMembership(membership: BoundMembership | undefined) {\n return (\n membership && {\n edge: membership.edge,\n parent: this.execution.attempt.select(\n membership.parent,\n membershipFields(membership.edge)\n ),\n }\n );\n }\n #rowQuery(\n selector: PreparedSelector,\n membership: BoundMembership | undefined,\n identity?: Input,\n unlocked = false\n ) {\n const ctx = this.execution.context;\n return ctx.queries.select(\n this.model,\n {\n take: 1,\n },\n this.#bindMembership(membership),\n {\n forUpdate: !(ctx.usesBatch || unlocked),\n identity,\n projection: this.#rowProjection,\n selector,\n }\n );\n }\n /**\n * The CURRENT, protected confirmation of a row this selection FOUND: a read\n * whose answer is the row this operation is about to consume, so it keeps its\n * lock whatever the PROBE of the same selection does ({@link insertsWhenAbsent}\n * reaches {@link query} alone).\n *\n * It is the membership confirmation a correlated nested `upsert` already\n * issued, with the two facts that were that arm's own turned into arguments —\n * the MEMBERSHIP it proves, and the CONDITION it proves (this selection's own\n * selector, the narrowing selector of a probe taken over it, or the\n * conjunction of every such probe's, which is why the argument is prepared\n * MEANING and not another selection). The three facts that make it a\n * confirmation rather than a second lookup are fixed: it addresses the\n * located row by IDENTITY, so it can adopt no replacement record; it keeps\n * `forUpdate`, so the requirement it proves survives into the effect that\n * spends it; and it returns the whole stored row, which is the authoritative\n * binding of every value that row supplies\n * ({@link CommandExecution.confirmFound}).\n */\n confirm(\n membership: BoundMembership | undefined,\n condition: PreparedSelector = this.selector\n ) {\n return this.#rowQuery(\n condition,\n membership,\n this.execution.identity(this.fields)\n );\n }\n /**\n * This located row, holding NULL in ONE component the consumer is about to\n * spend: the complement premise of the reference fold\n * ({@link CommandExecution.folded}).\n *\n * Where the value is folded it is a sub-select, so the literal the probe read\n * exists nowhere after and the shared representability requirement\n * ({@link CommandExecution.requireRepresentable}) can only be asked of the\n * capture. This states the same requirement of the row the fold will READ,\n * inside the unit that spends it, and states it as an ABSENCE so a row that\n * has GONE satisfies it — that loss is the presence premise's, with the\n * sentence that premise owns, and this one keeps the field-exact attribution\n * its own sentence names. One component per premise, for the same reason.\n */\n unrepresentable(field: string) {\n const ctx = this.execution.context;\n return ctx.queries.select(this.model, { take: 1 }, undefined, {\n condition: ctx.driver.adapter.operators.isNull(\n ctx.queries.column(this.model, field)\n ),\n identity: this.execution.identity(this.fields),\n projection: this.#identityProjection,\n });\n }\n /**\n * The rows the selector names OUTSIDE the membership: a batch premise of\n * the observation that finds this row (N1) — absent, the row is either not\n * there or a member, which is what a found requirement asks.\n */\n outsideMembership(membership: BoundMembership) {\n const bound = this.#bindMembership(membership);\n return this.execution.context.queries.select(\n this.model,\n { take: 1 },\n bound && { ...bound, outside: true },\n { projection: this.#identityProjection, selector: this.selector }\n );\n }\n /** A member of this lookup's slot it addresses and its verb may not take. */\n outsideVerb() {\n return this.execution.context.queries.select(\n this.model,\n { take: 1 },\n this.#bindMembership(this.membership()),\n {\n projection: this.#identityProjection,\n selector: this.unjudged!.addressed,\n unless: this.selector,\n }\n );\n }\n query() {\n const identity =\n this.source.kind === \"producer\"\n ? this.execution.identity(this.source.producer)\n : undefined;\n return this.#rowQuery(\n this.selector,\n this.membership(),\n identity,\n this.insertsWhenAbsent\n );\n }\n /**\n * The premise that states a requirement this operation still owns: the\n * located row, addressed by its IDENTITY, under the membership it is\n * consumed through and the condition it matched.\n *\n * `held` is what makes it PROTECT that requirement rather than merely\n * observe it. A premise and the effect it stands in front of are two\n * statements, and a batch is one transaction, not one statement: under READ\n * COMMITTED every statement takes its own snapshot, so a commit landing\n * between them is visible to the second and the first has already answered.\n * A held read keeps the row for the rest of the transaction, which is where\n * the consuming effect is ({@link CommandExecution.holdMember}).\n */\n captured(\n condition: Selection = this,\n membership: BoundMembership | undefined = condition.membership(),\n take?: 1,\n held = false\n ) {\n const ctx = this.execution.context;\n return ctx.queries.select(\n this.model,\n {\n take,\n },\n this.#bindMembership(membership),\n {\n forUpdate: held,\n identity: this.execution.identity(this.fields),\n projection: this.#identityProjection,\n selector: condition.selector,\n }\n );\n }\n}\n","import { getAdapterInternals } from \"@adapters/adapter-internals\";\nimport {\n NestedWriteError,\n NotFoundError,\n UniqueConstraintError,\n UnsupportedOperationError,\n} from \"@errors\";\nimport { type AnyModel, getModelKeyCatalog } from \"@schema/model\";\nimport type { PreparedGuardFailure } from \"../../types\";\nimport {\n type Member,\n type MembershipParent,\n nestedRefusal,\n type ObservationPremise,\n} from \"../shared/operation-context\";\nimport type {\n PreparedProjection,\n PreparedSelector,\n Query,\n} from \"../shared/query\";\nimport { parseStamped } from \"../shared/row-scope\";\nimport { type Arguments, entries, type Input, record } from \"../shared/schema\";\nimport {\n type Membership,\n physicalField,\n storedFields,\n} from \"../shared/storage\";\nimport type { TransportAttempt } from \"../shared/transport-attempt\";\nimport type { Assignments } from \"./assignments\";\nimport { CommandAttempt } from \"./command-attempt\";\nimport type {\n Choose,\n Command,\n CommandOccurrence,\n Commands,\n MembershipRequirement,\n RecordCommand,\n SelectedSeriesMember,\n SeriesOccurrence,\n} from \"./commands\";\nimport {\n isRecordOccurrence,\n isSeriesOccurrence,\n membershipRaceFailure,\n} from \"./commands\";\nimport {\n type BoundMembership,\n type DeferredFailure,\n junctionPairs,\n membershipFields,\n type Selection,\n} from \"./selection\";\n\n/** What a captured series prepared, as its owner (`CommandAttempt`) states it. */\ntype PreparedSeries = NonNullable<ReturnType<CommandAttempt[\"series\"][\"get\"]>>;\n\n/** Interprets the prepared command tree through one replaceable execution attempt. */\nexport class CommandExecution {\n readonly commands: Commands;\n readonly context;\n #currentAttempt: CommandAttempt;\n readonly #entered = new Set<CommandOccurrence>();\n constructor(commands: Commands) {\n this.commands = commands;\n this.context = commands.context;\n this.#currentAttempt = new CommandAttempt(this.context.transportAttempt);\n this.context.attachRecovery(\n () => this.#replaceRegions(),\n (error) => {\n const producer = this.context.rejectedProducer(error);\n const choice = producer\n ? this.attempt.missingChoices.get(producer)\n : undefined;\n return Boolean(\n choice &&\n error instanceof UniqueConstraintError &&\n this.#matchesSelectedConstraint(choice, error)\n );\n }\n );\n }\n /**\n * The ONE recovery method: both attempt regions replaced synchronously, with\n * no callback and no await between the installations. WHETHER it may run is\n * the operation's question, not this interpreter's — `OperationContext`\n * spends the single allowance ({@link OperationContext.spendRecovery}) and is\n * this method's only caller, so a re-planned operation's new interpreter\n * brings no second allowance with it (Arnaud's D-25).\n */\n #replaceRegions(): TransportAttempt {\n const replacement = new CommandAttempt();\n this.#currentAttempt = replacement;\n return replacement.transport;\n }\n get attempt(): CommandAttempt {\n return this.#currentAttempt;\n }\n identity(fields: Assignments): Input {\n return this.attempt.select(fields, this.context.schema.keys(fields.model));\n }\n #membershipValues(edge: Membership, parent: Assignments): Input {\n return this.attempt.select(parent, membershipFields(edge));\n }\n #linkValues(\n edge: Extract<Membership, { kind: \"junction\" }>,\n source?: Assignments,\n target?: Assignments\n ): Input {\n return junctionPairs(\n edge,\n (owner, field) => this.attempt.read(owner, field),\n source,\n target\n );\n }\n async #requireTransitions(command: RecordCommand): Promise<void> {\n const ctx = this.context;\n const q = ctx.queries;\n const a = ctx.driver.adapter;\n for (const edge of command.transitions) {\n const before = this.#membershipValues(edge, command.located!.fields);\n const after = this.#membershipValues(edge, command.fields);\n for (const pair of edge.pairs) {\n if (after[pair.source] === null)\n throw new NestedWriteError(\n `Cannot update relation key field '${pair.source}' to null while mutating relation '${edge.name}'. A null reference names no row for that relation to point at.`,\n edge.name,\n {\n meta: {\n operation: \"update\",\n field: pair.source,\n relation: edge.name,\n },\n }\n );\n }\n if (\n !edge.reference ||\n edge.reference.onUpdate === \"cascade\" ||\n edge.pairs.some((pair) => before[pair.source] === null)\n )\n continue;\n const changed = a.operators.or(\n ...edge.pairs.map((pair) =>\n a.operators.not(\n a.operators.eq(\n q.fieldValue(command.model, pair.source, before[pair.source]),\n q.updateValue(\n command.model,\n pair.source,\n after[pair.source],\n q.fieldValue(command.model, pair.source, before[pair.source])\n )\n )\n )\n )\n );\n const failure = new NestedWriteError(\n `Cannot update relation '${edge.name}' with onUpdate('${edge.reference.onUpdate ?? \"restrict\"}') while the current relation is occupied.`,\n edge.name,\n {\n meta: ctx.usesBatch\n ? { relation: edge.name }\n : { operation: \"update\", relation: edge.name },\n }\n );\n if (ctx.usesBatch) failure.meta.raceable = true;\n await ctx.requireAbsent(\n q.select(\n edge.target,\n { take: 1 },\n { edge, parent: before },\n { condition: changed }\n ),\n failure\n );\n }\n }\n /**\n * The ONE requirement a concrete reference must meet to become a relation:\n * every component that represents the connection is present and non-NULL.\n *\n * A nullable referenced unique can read NULL on the row a probe FOUND, on a\n * row this operation itself PRODUCED, and on the PARENT whose own value a\n * member's statement spends. Writing that NULL does not connect the\n * relation — it DISCONNECTS the holder the payload asked to connect — and no\n * provider reports it, because NULL in a nullable foreign key is a legal\n * absence.\n *\n * The sentence is the relation's one inherited sentence, with the verb FIXED\n * at `connect` (`write-engine/messages.ts:lookupKeyIsNull`), because what is\n * refused is the CONNECTION and not the verb, the arm or the DIRECTION that\n * spelled it. Nothing else is refused: a nullable referenced unique is still\n * a legal schema, a row holding NULL in one is still updatable, a foreign key\n * is still nullable, and an explicit `disconnect` still writes its own NULL —\n * that one is a literal this row asked for, and carries no relation\n * ({@link FieldValue}).\n */\n private requireRepresentable(\n relation: string,\n referenced: string,\n value: unknown\n ): void {\n if (value !== null) return;\n throw this.#unrepresentable(relation, referenced);\n }\n /**\n * The same requirement's failure, BUILT rather than raised: the fold's own\n * value is a sub-select, so the requirement is also asked of the row that\n * sub-select will read, as a premise of the unit that spends it\n * ({@link folded}). One sentence, one builder, two askers.\n */\n #unrepresentable(relation: string, referenced: string): Error {\n return new NestedWriteError(\n `Cannot connect relation '${relation}': the located target's referenced field '${referenced}' is null.`,\n relation\n );\n }\n /**\n * The values one record's statement STORES — the point where a concrete\n * tuple becomes an explicit relation, and therefore where the requirement\n * above is asked.\n *\n * It is the earliest boundary holding the ACTUAL value of every component,\n * whatever supplied it: a located row's bytes, an arm this operation\n * created, or the parent's own current value ({@link CommandAttempt.read},\n * FC-02A). A value this unit produced into its batch scratch is asked once\n * the boundary has read it back and not before (D-58,\n * `TransportAttempt.carried`), and nothing is admitted, defaulted or\n * transformed a second time to obtain one. Only the components the RESOLVED\n * EDGE named are asked, not every field the row happens to demand.\n */\n private stored(fields: Assignments): Input {\n const values = this.attempt.values(fields);\n for (const [field, value] of fields.contributions())\n if (value.kind === \"field\" && value.relation !== undefined)\n this.requireRepresentable(value.relation, value.field, values[field]);\n return values;\n }\n /**\n * The value a parent-held `connect` writes into its HOLDER's own SET, read\n * WHERE it is spent.\n *\n * That value is the one a consumer's own SET writes, so it is read inside\n * that statement over this arm's own selector\n * ({@link Queries.locatedValue}) and a probe row that changed under us cannot\n * move the written key. `membershipOnly` says this arm's value is not a pure\n * membership and is FALSE for every verb but `connect`, so the verb is asked\n * with it. Every other arm binds what the probe read, unchanged: a junction\n * writes its captured pair, and a `connectOrCreate` FOUND arm spends the\n * bytes its own probe returned — the retired engine folded the `connect`\n * lookup and no other, which is what the scripted transport replies still\n * spell (`tests/raptor3/transport/world.ts`, `coc-found`).\n *\n * This is also the ONE supply {@link CommandExecution.stored} cannot ask\n * about, and the only reason the requirement is stated from two places: once\n * the holder's SET names this value it IS a sub-select, so the literal the\n * probe read exists here and nowhere after. Every other supply — every other\n * verb, both directions, found and produced alike — is the consumer's.\n *\n * The BATCH route folds a second arm, for the same reason and at a different\n * row ({@link locatedAt}): a probe that reads UNLOCKED because its other arm\n * inserts the key it looked for has no lock and — on this route — no\n * confirmation either ({@link confirmFound}), so the bytes it read are the\n * bytes of a row another transaction may since have changed. That arm's value\n * is therefore read where it is spent too, and read at the row this operation\n * LOCATED, never at the selector, which an unlocked probe cannot vouch for:\n * a replacement row that has acquired the selector would answer it.\n */\n private async folded(\n command: Choose,\n enclosing: Command | undefined,\n captured: Input\n ): Promise<Input> {\n const origin = command.lookup.origin;\n if (!origin) return captured;\n const selector =\n origin.operation === \"connect\" && command.lookup.membershipOnly === false\n ? command.lookup.selector\n : await this.locatedAt(command, enclosing, origin.relation);\n if (!selector) return captured;\n const values: Input = { ...captured };\n for (const field of command.fields.demands) {\n this.requireRepresentable(origin.relation, field, captured[field]);\n values[field] = this.context.queries.locatedValue(\n command.model,\n field,\n selector,\n enclosing?.kind === \"record\" ? enclosing.model : undefined\n );\n }\n return values;\n }\n /**\n * Where an UNLOCKED probe's answer is re-read on the batch route: the\n * CAPTURED COMPLETE IDENTITY of the row it found ({@link Queries.includeIdentities}\n * over the located row's own key) — or `undefined` where the holder spends\n * nothing of this row, which is every other placement.\n *\n * The fact that makes this necessary is the route's, not the verb's. The\n * batch route states this consumption's requirements as PREMISES of the\n * atomic unit — the selection's retained requirement ({@link runSelection}),\n * held through the effect because this probe took no lock — and a premise\n * proves that the row is still there, not what its columns now hold. The\n * reference the holder's own statement spends is such a column, so it is read\n * INSIDE that statement, at the identity the premise pins: a key recycled\n * onto another row between the plan-time read and the write moves nothing,\n * because nothing here names the key.\n *\n * What a premise cannot prove of a column, it can prove of its ABSENCE, and\n * the one thing the fold's sub-select cannot report is a NULL: the value is\n * gone from the engine, so {@link requireRepresentable} can only be asked of\n * the capture. The complement is stated beside it — one premise per NULLABLE\n * component, each carrying that component's own sentence — and a component no\n * schema admits a NULL in states nothing at all.\n */\n private async locatedAt(\n command: Choose,\n enclosing: Command | undefined,\n relation: string\n ): Promise<PreparedSelector | undefined> {\n const ctx = this.context;\n const lookup = command.lookup;\n if (!(ctx.usesBatch && lookup.insertsWhenAbsent)) return undefined;\n const spent = this.#spentByHolder(command, enclosing);\n if (spent.length === 0) return undefined;\n for (const field of spent)\n if (physicalField(ctx.schema, lookup.model, field).nullable)\n await ctx.requireAbsent(\n lookup.unrepresentable(field),\n this.#unrepresentable(relation, field)\n );\n return ctx.queries.includeIdentities(lookup.model, [\n this.identity(lookup.fields),\n ]);\n }\n /**\n * The components of a located row the ENCLOSING record's OWN statement\n * spends, named as that row spells them.\n *\n * It is the one reader of the resolved edge that states them\n * ({@link Commands.assignMembership}) read back: a contribution of the\n * holder's write whose producer is this choice's binding and that carries a\n * relation. So it is TRUE for the parent-held direction, where the holder's\n * SET writes the target's referenced value, and FALSE for every other\n * placement — a junction's captured pair is not the holder's own field, and a\n * child-held arm's value is written by the arm, not by the row above it.\n */\n #spentByHolder(command: Choose, enclosing: Command | undefined): string[] {\n if (enclosing?.kind !== \"record\") return [];\n const spent: string[] = [];\n for (const value of enclosing.fields.contributions().values())\n if (\n value.kind === \"field\" &&\n value.producer === command.fields &&\n value.relation !== undefined\n )\n spent.push(value.field);\n return spent;\n }\n /**\n * The PARENT row this created record is a member of, where it has one.\n *\n * A membership names its parent BY VALUE: this row's own column holds what\n * the parent's referenced field held when the plan read it. Where the INSERT\n * commits in a segment of its own, everything that follows trusts a parent\n * nothing re-read — and once another row holds that reference, the\n * correlation answers with IT. So the continuation re-pins the parent the\n * way {@link CommandExecution.captureSeries} pins a captured series': the\n * parent's IDENTITY and the value it holds for the edge, in one premise.\n *\n * The contributions that read the ENCLOSING record's own fields are that\n * membership — `Commands.create` assigns them from the incoming edge — and\n * the placement's origin names the relation and the verb that spelled it.\n */\n #membershipParent(\n command: RecordCommand,\n enclosing: Command | undefined\n ): MembershipParent | undefined {\n const origin = command.origin;\n if (!origin || enclosing?.kind !== \"record\") return undefined;\n const referenced: string[] = [];\n for (const value of command.fields.contributions().values())\n if (value.kind === \"field\" && value.producer === enclosing.fields)\n referenced.push(value.field);\n if (referenced.length === 0) return undefined;\n const parent = enclosing.fields;\n return {\n model: parent.model,\n where: () => ({\n ...this.identity(parent),\n ...this.attempt.select(parent, referenced),\n }),\n relation: origin.relation,\n verb: origin.operation,\n };\n }\n /**\n * Whether the arm that HOLDS a moved value is the arm that RAN.\n *\n * {@link Assignments.hold} is stated at plan time from a choice's FOUND\n * payload, because that write is the one the provider would carry this row\n * along with. A choice that took its MISSING arm created a row only this\n * row's own statement can point it at — nothing cascaded, and re-addressing\n * the observation by the key the new row holds would name no row at all\n * (a live `UPDATE ... RETURNING` that produces nothing, a batch route that\n * commits a fresh target and moves no holder). The attempt already records\n * which arm ran.\n */\n #carried(holder: Assignments): boolean {\n for (const choice of this.attempt.missingChoices.values())\n if (choice.found?.command.fields === holder) return false;\n return true;\n }\n #matchesSelectedConstraint(\n choice: Choose,\n error: UniqueConstraintError\n ): boolean {\n const key = choice.lookup.selector.uniqueKey;\n const selected = choice.lookup.selector.uniqueValues;\n if (!(key && selected)) return false;\n if (\n !key.fields.every((field) => {\n const missing = choice.missing;\n const proposed = missing?.command.fields.known(field);\n return (\n proposed?.kind === \"literal\" &&\n Object.is(proposed.value, selected.get(field))\n );\n })\n )\n return false;\n const table = choice.model[\"~\"].names.sql!;\n const columns = key.fields.map((field) =>\n this.context.queries.columnName(choice.model, field)\n );\n const constraints = getAdapterInternals(\n this.context.driver.adapter\n ).constraints;\n const expected = (\n key.kind === \"primary\"\n ? constraints.primaryKey(table, columns)\n : constraints.unique(table, key.name ?? columns[0]!, columns)\n ).normalizedError;\n const meta = error.meta;\n if (meta.table !== expected.table) return false;\n if (meta.constraint !== expected.constraint) return false;\n const expectedColumns = expected.columns;\n if (meta.columns === undefined || expectedColumns === undefined) {\n return meta.columns === expectedColumns;\n }\n return (\n meta.columns.length === expectedColumns.length &&\n meta.columns.every((column, index) => column === expectedColumns[index])\n );\n }\n async #recover(error: unknown): Promise<boolean> {\n // In place, or not at all: where this operation opened a region, the\n // rejection aborted it and the recovery is the region owner's.\n if (!this.context.replaysInPlace) return false;\n const rejection = this.context.recoveryRejection(error);\n const choice =\n rejection?.kind === \"insert\"\n ? this.attempt.missingChoices.get(rejection.producer)\n : undefined;\n const conditional = this.attempt.conditionalSkips.get(error);\n if (conditional && rejection?.kind === \"assertion\") {\n const replacement = this.context.spendRecovery();\n if (!replacement) return false;\n this.context.restartRejectedInsert(replacement);\n return true;\n }\n if (\n !(\n choice &&\n error instanceof UniqueConstraintError &&\n this.#matchesSelectedConstraint(choice, error)\n )\n )\n return false;\n const replacement = this.context.spendRecovery();\n if (!replacement) return false;\n this.context.restartRejectedInsert(replacement);\n // A lost winner is not permission to attempt the missing INSERT again.\n await this.runSelection(choice.lookup);\n return this.attempt.rows.has(choice.lookup);\n }\n async complete(\n root: CommandOccurrence<RecordCommand | Choose>,\n args: Arguments\n ): Promise<unknown> {\n while (true) {\n try {\n await this.run(root);\n return await this.context.finishOne(\n this.context.queries.select(\n root.command.model,\n {\n select: args.select,\n include: args.include,\n omit: args.omit,\n },\n undefined,\n { identity: this.identity(root.command.fields) }\n )\n );\n } catch (error) {\n if (!(await this.#recover(error))) throw error;\n }\n }\n }\n private async runSelection(\n selection: Selection,\n member?: Member,\n premise?: ObservationPremise\n ): Promise<void> {\n const attempt = this.attempt;\n if (attempt.rows.has(selection)) return;\n const source = selection.source;\n if (\n source.kind === \"producer\" &&\n !this.context.usesBatch &&\n selection.facts.fields.size === 0\n ) {\n const row = attempt.select(source.producer, selection.fields.demands);\n attempt.rows.set(selection, row);\n attempt.bind(selection.fields, row);\n return;\n }\n // An ordered observation (N1) on the batch route reads through the barrier:\n // the queued unit goes with its premises and the read rides the same native\n // batch behind the writes it depends on; a required row is a premise of\n // that batch too, so an absent target aborts it before anything commits.\n const required = selection.required;\n const rows =\n selection.dependent && this.context.usesBatch\n ? await this.context.flush(\n selection.query(),\n member,\n premise ??\n (required && {\n query: selection.query(),\n present: true,\n failure: required,\n })\n )\n : await this.context.read(\n selection.query(),\n true,\n false,\n selection.model\n );\n const found = rows[0];\n if (!found) {\n if (selection.required) throw selection.required();\n const unjudged = selection.unjudged;\n if (unjudged)\n await this.context.requireAbsent(\n selection.outsideVerb(),\n unjudged.failure()\n );\n return;\n }\n attempt.rows.set(selection, found);\n attempt.bind(selection.fields, found);\n // The requirement this premise proves must last through the effect that\n // consumes it, and a probe that read UNLOCKED (`Selection.insertsWhenAbsent`)\n // holds nothing of its own answer — so on the batch route, where no\n // confirmation is taken (`confirmFound`), the premise itself HOLDS the row\n // it found, the way a captured member's does (`holdMember`, D-65). It is\n // addressed by the identity of a row that EXISTS, so it locks no absence\n // and R2c's convergence is untouched; a probe that kept its lock states the\n // premise it always stated.\n if (this.context.usesBatch && selection.retained)\n this.context.requirePresent(\n selection.captured(\n selection,\n selection.membership(),\n undefined,\n selection.insertsWhenAbsent === true\n ),\n selection.retained()\n );\n }\n /**\n * The shared FOUND-consumption rule: an unlocked positive observation is\n * re-taken under lock, over the requirements this operation ALREADY owns,\n * before anything consumes it — and the row that read answers is the\n * authoritative binding every consumer then spends.\n *\n * A probe whose other arm inserts the key it looked for reads without locking\n * ({@link Selection.insertsWhenAbsent}), because a lock cannot protect an\n * absence and asking for one costs the operation its convergence. What that\n * withdrawal also gives up is the POSITIVE answer: the row it found is held\n * for nothing that follows. A read taken AFTER the effect cannot restore it —\n * it proves the row still exists, not that the identity, the membership, the\n * matched condition and the reference the effect spent were still the ones\n * the operation was promised. Three native MySQL schedules measured each of\n * those losses separately (the repair prompt §1): a holder connected to a row\n * that acquired the referenced key after the probe read it, a conditional\n * upsert that wrote after its matched condition changed, and a nested upsert\n * that wrote a record reparented out of the membership it was found in.\n *\n * So the confirmation is taken HERE, between the observation and every arm:\n * one locked read ({@link Selection.confirm}) addressed by the located\n * IDENTITY — never a public selector rerun, which could adopt a replacement\n * record — carrying the requirement the operation owns, whose lock then lasts\n * through the consuming effect under the transaction this operation is\n * already in. Its answer replaces the probe's bytes as this row's binding, so\n * the reference a holder's own INSERT spends is the CURRENT one and never a\n * captured value another row has since acquired; values this operation itself\n * produced are unaffected, because they are read where they are spent\n * ({@link CommandAttempt.read}) and nothing here compares against them.\n *\n * Where the requirement has been lost the operation raises the failure it\n * already owns for that loss — the found membership's, the replacement race\n * of a `connectOrCreate`, the identity sentence of a located target, the\n * conditional premise's own match failure — and nothing reselects, switches\n * an arm or replays.\n *\n * Two routes need no read here. The batch route states the IDENTITY, the MEMBERSHIP and the matched\n * CONDITION as PREMISES of the atomic unit that consumes it — the\n * selection's retained requirement above, the found record's own\n * `requirePresent` ({@link run}) and the condition premises beside this call —\n * which is the same fact proved atomically and aborts before any write —\n * which is the unit's OUTCOME, not the window between a premise and the\n * statement it protects; where a requirement must hold THROUGH its effect\n * the member is held ({@link holdMember}), which is what the retained premise\n * of an unlocked probe now does ({@link runSelection}). And a\n * probe that KEPT its lock is already holding its own answer.\n *\n * What those premises never state is the referenced COLUMN a holder's own\n * statement spends, and a read is not how that route binds it: the value is\n * folded into that statement as a sub-select of the located row's CURRENT\n * value ({@link folded}'s batch arm), so there too the reference is the\n * intended row's own and never a captured key another row has acquired.\n */\n #foundFailure(\n command: Choose,\n requirement: MembershipRequirement | undefined\n ): DeferredFailure {\n const conditional = command.conditions;\n return conditional\n ? () => conditional.matched\n : (requirement?.failure ??\n command.lookup.retained ??\n command.lookup.required ??\n (() => new NotFoundError(command.model[\"~\"].names.ts!, \"update\")));\n }\n /**\n * The narrow FOUND shape whose consuming UPDATE proves its own premise.\n *\n * The selector is exactly the complete row identity: no mutable unique,\n * extended filter, membership, relation read, or matched condition remains\n * to confirm. The found arm has no earlier child effect and writes that same\n * row. Its demanded values are all returned by the UPDATE, so no byte from\n * the unlocked probe survives as a published binding. On a RETURNING\n * provider the statement therefore proves the identity at the point it\n * consumes it; an empty result raises the confirmation's original failure.\n */\n #mutationConfirmationFailure(\n command: Choose,\n requirement: MembershipRequirement | undefined,\n found: CommandOccurrence<RecordCommand> | undefined\n ): DeferredFailure | undefined {\n const update = found?.command;\n const lookup = command.lookup;\n if (\n this.context.usesBatch ||\n !this.context.driver.adapter.capabilities.supportsReturning ||\n requirement ||\n command.conditions ||\n lookup.membership() ||\n !lookup.identityOnly() ||\n !update ||\n update.located !== lookup ||\n update.transitions.length > 0 ||\n found.children.length > 0 ||\n update.fields.writtenFields().length === 0 ||\n update.fields.demands.size === 0 ||\n update.fields.consumes(lookup.fields) ||\n [...lookup.fields.demands].some(\n (field) => !update.fields.demands.has(field)\n ) ||\n [...command.fields.demands].some(\n (field) => !update.fields.demands.has(field)\n )\n )\n return undefined;\n return this.#foundFailure(command, requirement);\n }\n private async confirmFound(\n command: Choose,\n requirement: MembershipRequirement | undefined,\n captured: Input\n ): Promise<Input> {\n const ctx = this.context;\n const lookup = command.lookup;\n if (ctx.usesBatch || !(requirement || lookup.insertsWhenAbsent))\n return captured;\n const membership = requirement?.membership ?? lookup.membership();\n // A MATCHED condition is the narrowest requirement the operation owns here,\n // and its probe's selector is the locator's own narrowed by the condition,\n // so confirming it confirms the located row with it. That is exactly how\n // the batch route states the same pair — condition premises only, with the\n // locator marked as already stated (`attempt.retained`).\n //\n // EVERY matched condition is such a requirement, and they are ONE premise\n // of this consumption, not one premise each: the row is re-taken once,\n // under the CONJUNCTION of the probes that matched it\n // (`Queries.andSelectors`, over the prepared selectors those probes already\n // carry — the locator's own base among them, reused, not prepared again).\n // The alternative, a confirmation per condition, asks the same row the same\n // question twice and pays a round trip for the answer it is already\n // holding under lock. What this one statement then loses is that ONE\n // premise and never a named field, so the failure it raises is the\n // premise's own (`Choose[\"conditions\"].matched`, decided where the premises\n // are built): a conjunction says a MATCHED REQUIREMENT changed and names\n // the conditions as a set, a single condition keeps its exact sentence.\n // Blaming the first of several would be a diagnosis this statement did not\n // make; making it would need the conditions evaluated over the confirmed\n // row rather than in its `WHERE`, which no adapter can project today, or\n // the round trip per condition this one statement removed (repair prompt 2\n // §2).\n const conditions = command.conditions?.probes ?? [];\n const first = conditions[0];\n const failure = this.#foundFailure(command, requirement);\n const selector = first\n ? conditions.length === 1\n ? first.lookup.selector\n : ctx.queries.andSelectors(\n lookup.model,\n conditions.map((condition) => condition.lookup.selector)\n )\n : lookup.selector;\n const rows = await ctx.read(\n lookup.confirm(membership, selector),\n true,\n false,\n lookup.model\n );\n const row = rows[0];\n if (!row) throw failure();\n this.attempt.materialize(lookup.fields, row);\n return row;\n }\n /**\n * This occurrence's execution has begun: {@link run} entered it and its\n * children are the schedule it is dispatching. The dependency pass asks\n * before it moves a child to its execution point (`Commands.depend`): a\n * series expands fresh members while the operation runs, and what separates\n * them from the retained tree around them is exactly this — the fresh\n * member's own occurrences have never been entered, the enclosing record\n * that is running them has.\n */\n started(occurrence: CommandOccurrence): boolean {\n return this.#entered.has(occurrence);\n }\n async run(\n occurrence: CommandOccurrence,\n member: Member = occurrence.command,\n confirmationFailure?: DeferredFailure\n ): Promise<void> {\n const ctx = this.context;\n const attempt = this.attempt;\n const command = occurrence.command;\n this.#entered.add(occurrence);\n // biome-ignore lint/style/useDefaultSwitchClause: the command-kind union is exhaustive; a default would be dead code.\n switch (command.kind) {\n case \"record\": {\n command.fields.activate();\n if (occurrence.refusal) throw occurrence.refusal;\n if (command.located && !attempt.rows.has(command.located))\n await this.runSelection(command.located, member);\n if (\n ctx.usesBatch &&\n command.located &&\n !command.located.retained &&\n !attempt.retained.has(command.located)\n ) {\n const missingRow =\n command.requirement?.failure ?? command.located.required;\n ctx.requirePresent(\n command.located.captured(\n undefined,\n command.requirement?.membership ?? command.located.membership(),\n 1\n ),\n missingRow\n ? missingRow()\n : new NotFoundError(command.model[\"~\"].names.ts!, \"update\")\n );\n }\n await this.#requireTransitions(command);\n for (const child of occurrence.children)\n if (child.placement === \"before\") await this.run(child, member);\n // Every `before` child has run, and one of them may already have moved\n // this row: a correlated arm's target is the row this one points at, so\n // the provider rewrote this row's foreign key when the arm rewrote the\n // key it references ({@link Assignments.hold}). The observation this\n // operation holds of the row is re-addressed from the value the arm\n // published, so the record's own statement, its later children and the\n // terminal read all name the row where the cascade left it — the\n // located key names nothing at all. One of them may equally have run\n // its OTHER arm, and then nothing cascaded ({@link carried}).\n const moved =\n command.located &&\n command.fields.moved((holder) => this.#carried(holder));\n if (moved)\n attempt.materialize(command.located!.fields, attempt.resolve(moved));\n const values = this.stored(command.fields);\n attempt.bind(\n command.fields,\n command.located\n ? await ctx.update(\n command.model,\n // The row as it stands NOW: the same reader that answers the\n // address answers every value the update computes from, so a\n // cascade that moved this row cannot leave the two naming\n // different rows ({@link CommandAttempt.read}, FC-02A). The\n // ORIGINAL observation stays in `attempt.rows` for the\n // consumers that need what was SEEN.\n attempt.select(command.located.fields, [\n ...ctx.schema.keys(command.model),\n ...command.fields.demands,\n ]),\n values,\n member,\n command.operation,\n command.fields.demands,\n confirmationFailure,\n command.located.judgement,\n this.#refusal(command)\n )\n : await ctx.insert(\n command.model,\n values,\n command.fields.demands,\n member,\n command.operation,\n command.fields,\n this.#membershipParent(command, occurrence.parent?.command),\n this.#refusal(command)\n )\n );\n // Every capture still runs before every effect, and the reason is\n // MEASURED, not stylistic: a capture flushes\n // (`OperationContext.captureSeries` → `flush`), and on the batch route a\n // flush COMMITS everything queued before it — so a capture placed after\n // a sibling effect commits that effect, and a planning refusal the\n // capture then raises can no longer undo it.\n // `tests/raptor3/post-prep/g29-dependency-boundaries.test.ts` measures\n // exactly that: with the two passes merged into the body's declared\n // order, the earlier sibling `create` is durable (`committedSegments: 1`)\n // before the member lookup refuses. Sibling ORDER is restored where it\n // was actually inverted — by compiling a set mutation as one statement\n // instead of a capture (`SetMutation`) — not by moving the captures that\n // remain. See `docs/architecture/raptor3-evidence/g4/parity/lane-x-note.md`\n // (U6.2, \"the phase pass stays\").\n for (const child of occurrence.children)\n if (child.placement === \"capture\") await this.run(child, member);\n // A nested `create` list places its entries as consecutive `after`\n // records, and the child-free ones share one INSERT per run.\n const children = occurrence.children;\n for (let index = 0; index < children.length; index++) {\n const child = children[index]!;\n if (child.placement !== \"after\") continue;\n // The maximal run of consecutive `after` records sharing `child`'s\n // INSERT (`child` itself first, when it qualifies at all).\n const run: CommandOccurrence<RecordCommand>[] = [];\n let next = children[index];\n if (isRecordOccurrence(child))\n while (\n next?.placement === \"after\" &&\n this.#sharesInsert(child.command, next)\n ) {\n run.push(next);\n next = children[index + run.length];\n }\n if (run.length < 2) await this.run(child, member);\n else {\n index += run.length - 1;\n if ((await this.#insertTogether(run)) === undefined)\n for (const one of run) await this.run(one, member);\n }\n }\n return;\n }\n case \"lookup\": {\n await this.runSelection(command, member);\n return;\n }\n case \"junction\": {\n if (attempt.junctions.has(command)) return;\n if (command.address && !attempt.rows.has(command.address)) return;\n const captured = await ctx.captureMembership(\n command.edge,\n attempt.resolve(command.values)\n );\n if (captured) attempt.junctions.set(command, captured);\n return;\n }\n case \"absent\": {\n const exclude = command.excluding.map((fields) =>\n ctx.queries.lowerIdentity(command.model, this.identity(fields))\n );\n const restrict = command.restrict;\n const locked = (selector?: PreparedSelector, take?: number) =>\n ctx.queries.select(\n command.model,\n {\n take,\n select: Object.fromEntries(\n storedFields(ctx.schema, command.model).map((field) => [\n field,\n true,\n ])\n ),\n },\n {\n edge: command.membership.edge,\n parent: this.#membershipValues(\n command.membership.edge,\n command.membership.parent\n ),\n },\n {\n forUpdate: !ctx.usesBatch,\n condition: exclude.length\n ? ctx.driver.adapter.operators.not(\n ctx.driver.adapter.operators.or(...exclude)\n )\n : undefined,\n selector,\n }\n );\n // DC14, as `Commands.unreferenced`: candidates no locate holds are\n // locked before the requirement reads.\n if (restrict?.lock && !ctx.usesBatch)\n await ctx.read(locked(restrict.candidates), true);\n await ctx.requireAbsent(\n locked(\n // The parent's identity is known here, where the requirement runs.\n restrict &&\n this.commands.blocked(\n restrict.candidates,\n restrict.except === undefined\n ? undefined\n : {\n slot: restrict.except,\n identity: this.identity(command.membership.parent),\n }\n ),\n 1\n ),\n command.failure()\n );\n return;\n }\n case \"choose\": {\n const supplied = command.lookup.source.kind === \"producer\";\n // A lookup whose selector names a value this operation PRODUCED is\n // answered outside the queue, so the unit that produces it is\n // dispatched first — and the boundary itself carries the value across\n // as a literal (D-58, `OperationContext.submit`), which is what lets\n // the selector name it at all.\n if (ctx.usesBatch && supplied) {\n try {\n await ctx.flush(undefined, member);\n } catch (error) {\n throw ctx.failure(error, \"prefix\", member);\n }\n }\n // A found requirement rides the observation's batch as its premise:\n // no row the selector names may stand outside the membership (N1).\n const requirement = command.foundRequirement;\n const premised =\n requirement !== undefined &&\n ctx.usesBatch &&\n command.lookup.dependent === true;\n try {\n await this.runSelection(\n command.lookup,\n member,\n premised\n ? {\n query: requirement.selection.outsideMembership(\n requirement.membership\n ),\n present: false,\n failure: requirement.failure,\n }\n : undefined\n );\n for (const condition of command.conditions?.probes ?? [])\n await this.runSelection(condition.lookup, member);\n } catch (error) {\n throw supplied ? ctx.failure(error, \"capture\", member) : error;\n }\n const captured = attempt.rows.get(command.lookup);\n const found = this.commands.choiceArm(occurrence, \"found\");\n const missing = this.commands.choiceArm(occurrence, \"missing\");\n if (captured) {\n if (command.conditions?.probes.length && found) {\n found.command.fields.activate();\n if (found.refusal) throw found.refusal;\n const unmatched = command.conditions.probes.find(\n (condition) => !attempt.rows.has(condition.lookup)\n );\n if (unmatched) {\n if (ctx.usesBatch) {\n attempt.conditionalSkips.set(unmatched.skip, command);\n ctx.requirePresent(\n command.lookup.captured(undefined, undefined, 1),\n command.conditions.missingRow\n );\n await ctx.requireAbsent(\n command.lookup.captured(unmatched.lookup, undefined, 1),\n unmatched.skip\n );\n }\n attempt.bind(command.fields, captured);\n return;\n }\n if (ctx.usesBatch) {\n for (const condition of command.conditions.probes)\n ctx.requirePresent(\n command.lookup.captured(condition.lookup, undefined, 1),\n condition.match\n );\n attempt.retained.add(command.lookup);\n }\n }\n const confirmationFailure = this.#mutationConfirmationFailure(\n command,\n requirement,\n found\n );\n const current = confirmationFailure\n ? captured\n : await this.confirmFound(command, requirement, captured);\n if (found) {\n if (ctx.usesBatch && supplied) {\n ctx.prepareMembers(() => [found.command], member);\n await ctx.executeMember(() => this.run(found), found.command);\n } else await this.run(found, member, confirmationFailure);\n if (confirmationFailure)\n attempt.materialize(\n command.lookup.fields,\n attempt.select(\n found.command.fields,\n command.lookup.fields.demands\n )\n );\n attempt.bind(command.fields, {\n ...current,\n ...attempt.select(found.command.fields, command.fields.demands),\n });\n } else\n attempt.bind(\n command.fields,\n await this.folded(command, occurrence.parent?.command, current)\n );\n } else if (missing) {\n attempt.missingChoices.set(missing.command.fields, command);\n await this.run(missing, member);\n attempt.bind(\n command.fields,\n attempt.select(missing.command.fields, command.fields.demands)\n );\n }\n return;\n }\n case \"link\": {\n const original =\n command.captured && attempt.junctions.get(command.captured);\n const address = command.captured;\n const carriedSide =\n address?.edge.uniqueSide === \"source\"\n ? address.edge.sourceSide\n : address?.edge.targetSide;\n const captured =\n original && address && carriedSide\n ? {\n ...original,\n ...Object.fromEntries(\n carriedSide.members.map((pair) => [\n pair.junctionField,\n attempt.read(address.final, pair.referencedField),\n ])\n ),\n }\n : original;\n const matches = (fields: Input) =>\n Object.entries(fields).every(\n ([field, value]) => captured && Object.is(captured[field], value)\n );\n const removed =\n captured &&\n command.removals?.some(\n (removal) =>\n matches(\n this.#linkValues(removal.edge, removal.source, removal.target)\n ) &&\n !removal.keep.some((retained) =>\n matches(this.#linkValues(removal.edge, undefined, retained))\n )\n );\n await ctx.link(\n command.edge,\n attempt.resolve(command.values),\n member,\n removed ? undefined : captured\n );\n return;\n }\n case \"remove\": {\n await ctx.remove(\n command.edge,\n command.source\n ? this.#membershipValues(command.edge, command.source)\n : undefined,\n command.target ? this.identity(command.target) : undefined,\n command.keep.map((target) => this.identity(target)),\n member\n );\n return;\n }\n case \"delete\": {\n await this.runSelection(command.located, member);\n // A selection that is not required and bound no row is an empty\n // slot: a lax `delete: true` deletes nothing (DESIGN §5.3). A\n // required selection threw in `runSelection` before reaching here.\n const row = attempt.rows.get(command.located);\n if (!row) return;\n const model = command.located.model;\n // A tombstone updates the row it located, by identity, and keeps it.\n if (command.values)\n await ctx.update(model, row, command.values, member, \"delete\");\n else await ctx.delete(model, row, member);\n return;\n }\n case \"set\": {\n await ctx.mutateMembers(\n command.edge,\n this.#membershipValues(command.edge, command.parent),\n command.selector,\n command.values,\n member\n );\n return;\n }\n case \"captureSeries\": {\n await this.captureSeries(\n this.commands.seriesCaptureTarget(occurrence),\n member\n );\n return;\n }\n case \"series\": {\n await this.#executeRecords(\n occurrence.children.filter(isRecordOccurrence),\n member\n );\n return;\n }\n case \"selectedSeries\": {\n if (isSeriesOccurrence(occurrence))\n await this.#executeSeries(occurrence);\n return;\n }\n case \"membership\":\n return;\n }\n }\n /**\n * A relation-bearing createMany's result. Its selection is prepared HERE,\n * from the identities the members produced, and not at construction: a\n * selection that refuses does so after the writes it follows, and a series\n * whose every member was skipped publishes `[]` without preparing it. That\n * timing is observable, so it is kept (unlike updateMany's, whose\n * construction already prepared the selection before any write).\n */\n async records(\n records: CommandOccurrence<RecordCommand>[],\n select: Input | undefined,\n member: Member\n ): Promise<unknown> {\n const { count, identities } = await this.#executeRecords(\n records,\n member,\n select !== undefined\n );\n if (!select) return this.context.finishValue({ count });\n if (identities.length === 0) return this.context.finishMany([]);\n return this.context.finishMany(\n this.context.seriesQueries(\n this.context.queries.prepareProjection(records[0]!.command.model, {\n select,\n }),\n identities\n )\n );\n }\n /**\n * Whether `candidate` may share `first`'s INSERT: a create of the same model\n * writing the same columns in the same order, whose output nothing demands\n * and which carries no child, suppression or refusal of its own. Rows that\n * pass reach the provider as one grouped, bind-budgeted INSERT\n * ({@link insertTogether}) in their declared order, so generated keys are\n * allocated as the one-row-at-a-time path allocates them.\n */\n #sharesInsert(\n first: RecordCommand,\n candidate: CommandOccurrence\n ): candidate is CommandOccurrence<RecordCommand> {\n if (!isRecordOccurrence(candidate)) return false;\n const { command, children, refusal } = candidate;\n const columns = first.fields.writtenFields();\n const written = command.fields.writtenFields();\n return (\n command.model === first.model &&\n command.fields.operation === \"create\" &&\n command.fields.demands.size === 0 &&\n written.length === columns.length &&\n written.every((field, index) => field === columns[index]) &&\n !command.suppression &&\n !command.located &&\n children.length === 0 &&\n refusal === undefined\n );\n }\n /**\n * The rows of `records` through the operation's one grouped INSERT owner\n * (`OperationContext.insertMany`), or `undefined` where that owner declines\n * (outside the operation's own region, or on the batch route).\n */\n #insertTogether(\n records: CommandOccurrence<RecordCommand>[]\n ): Promise<number | undefined> {\n const [first] = records;\n return this.context.insertMany(\n first!.command.model,\n () => {\n for (const { command } of records) command.fields.activate();\n return records.map(({ command }) => this.stored(command.fields));\n },\n this.#refusal(first!.command)\n );\n }\n /**\n * What a record whose produced row is refused reports (R4, §5.3): a nested\n * one its relation's `NestedWriteError`, a root one the operation's\n * `ForbiddenError` (`undefined`, the context's default).\n */\n #refusal(command: RecordCommand): PreparedGuardFailure | undefined {\n const origin = command.origin ?? command.located?.origin;\n return origin && nestedRefusal(origin.operation, origin.relation);\n }\n async #executeRecords(\n records: CommandOccurrence<RecordCommand>[],\n member: Member,\n identified = false\n ): Promise<{ readonly count: number; readonly identities: Input[] }> {\n const ctx = this.context;\n const members = ctx.prepareMembers(() => records, member);\n const identities: Input[] = [];\n const first = members[0];\n if (\n !identified &&\n members.length > 1 &&\n first &&\n members.every((record) => this.#sharesInsert(first.command, record))\n ) {\n const count = await this.#insertTogether(members);\n if (count !== undefined) return { count, identities };\n }\n let count = 0;\n for (const record of members) {\n const command = record.command;\n let completed = true;\n if (command.suppression)\n completed = await ctx.executeSkippableMember(\n () => this.run(record),\n command.fields,\n command\n );\n else await ctx.executeMember(() => this.run(record), command);\n if (!completed) {\n await ctx.executeMember(() => this.#adoptSuppressed(record), command);\n continue;\n }\n count++;\n if (identified) identities.push(this.identity(command.fields));\n }\n return { count, identities };\n }\n /**\n * A skipped INSERT is not a skipped MEMBERSHIP.\n *\n * `skipDuplicates` suppressed this member's target ROW, so the membership it\n * declared is written against the row the member NAMES rather than rolled\n * back with the insert — the shipped `joinWhenTargetExists` route\n * (`write-engine/junction-create-many-routing.ts:95-113`,\n * `JunctionStatements.ts:134-155`). \"Own key spelled\" is not that question:\n * a spelled key that names NO row (the insert was refused by a different\n * unique) must write no membership, and a row key the provider generates\n * names the existing row through the one declared unique the payload spells\n * — the shipped `adopt` disposition, which E6.8 calls the `connectOrCreate`\n * adopt (`junction-create-many-routing.ts:117-131`). So the row is LOCATED\n * by what the payload spells, generated keys included, and a member that\n * locates nothing writes nothing.\n *\n * The MEMBERSHIP, and only it: every other effect this member declared\n * belongs to the row that was never created, so a member that declares one\n * strands whole, join included — the shipped router reads `relationBearing`\n * BEFORE the join route (`junction-create-many-routing.ts:76-84`), and in\n * the series it takes instead a skipped root returned before the member's\n * remaining steps ran (`OperationExecutor.ts:894`,\n * `if (execution.skippedRoot) return true`). The separate invariant \"a\n * skipped root must strand nothing\" (`:2389`) is about an effect placed\n * BEFORE that root, and refuses the member outright.\n */\n async #adoptSuppressed(\n record: CommandOccurrence<RecordCommand>\n ): Promise<void> {\n const command = record.command;\n // A duplicate on a singular variant is a no-op, not an ownership transfer.\n if (\n record.children.some(\n ({ command }) =>\n command.kind === \"link\" &&\n command.edge.scope.edge.kind === \"variantJunctionCarrier\" &&\n command.edge.uniqueSide !== undefined\n )\n )\n return;\n for (const child of record.children)\n if (\n child.command.kind !== \"link\" &&\n child.command.kind !== \"remove\" &&\n child.command.kind !== \"junction\"\n )\n return;\n const row = await this.#locateSuppressed(command);\n if (!row) return;\n this.attempt.bind(command.fields, row);\n for (const child of record.children)\n if (child.placement !== \"before\") await this.run(child, command);\n }\n /**\n * The existing row a suppressed member NAMES, read at this member's own\n * position: its complete row key when the payload spells it, else the one\n * declared unique it spells whole. Two spelled uniques name two rows and so\n * name none — the shipped disposition's `spelled.length !== 1` suppression\n * (`junction-create-many-routing.ts:121-124`).\n */\n async #locateSuppressed(command: RecordCommand): Promise<Input | undefined> {\n const ctx = this.context;\n // A NULL is not a spelling: it equals no row, so a key holding one names\n // none (the shipped disposition's own `value !== undefined && value !==\n // null`, `junction-create-many-routing.ts:118-120`).\n const spelled = (fields: readonly string[]): Input | undefined => {\n const values: Input = {};\n for (const field of fields) {\n const known = command.fields.known(field);\n if (\n !command.fields.isRequested(field) ||\n known?.kind !== \"literal\" ||\n known.value === null\n )\n return undefined;\n values[field] = known.value;\n }\n return values;\n };\n let address = spelled(ctx.schema.keys(command.model));\n if (!address) {\n const named = getModelKeyCatalog(command.model)\n .addressableKeys.filter((key) => key.kind !== \"primary\")\n .map((key) => spelled(key.fields))\n .filter((values) => values !== undefined);\n if (named.length !== 1) return undefined;\n address = named[0]!;\n }\n const located = this.commands.lookup(command.model, {\n kind: \"query\",\n selector: ctx.queries.identitySelector(command.model, address),\n });\n await this.runSelection(located, command);\n return this.attempt.rows.get(located);\n }\n async series(\n occurrence: CommandOccurrence<SeriesOccurrence>,\n member?: Member\n ): Promise<number>;\n async series(\n occurrence: CommandOccurrence<SeriesOccurrence>,\n member: Member,\n projection: PreparedProjection\n ): Promise<Input[]>;\n async series(\n occurrence: CommandOccurrence<SeriesOccurrence>,\n member: Member = occurrence.command.series.selection,\n projection?: PreparedProjection\n ): Promise<number | Input[]> {\n const prepared = await this.captureSeries(occurrence, member);\n // Only the admitted updateMany boundary supplies a projection, so\n // captureSeries has constructed record members for this terminal readback.\n const updatedMembers =\n prepared.members as CommandOccurrence<RecordCommand>[];\n const identityFields = projection\n ? updatedMembers.map(({ command }) => command.fields)\n : [];\n const count = await this.#executeSeries(occurrence);\n const identities = identityFields.map((fields) => this.identity(fields));\n if (!projection) {\n await this.context.finish();\n return count;\n }\n if (identities.length === 0) return this.context.finishMany([]);\n return this.context.finishMany(\n this.context.seriesQueries(projection, identities, \"updateMany\")\n );\n }\n /**\n * A captured member set is an assertion about the rows it does NOT contain.\n *\n * Rule 5 forbids caching observed absence, and a plan-time membership read is\n * exactly that: it names the members that were connected and matched the\n * filter when it ran. So the set rides its own batch with the complement it\n * claims — \"connected ∧ filter ∧ key ∉ captured is EMPTY\" — as one raceable\n * `requireAbsent`. A member committed between the read and the batch aborts\n * the atomic unit instead of being silently missed, and the one recovery\n * re-plans from the admitted values against the larger set (Arnaud's D-25).\n *\n * The premise BOUNDS THE WORKLIST, and D-65 says so: the members this series\n * writes are the ones the capture held when this premise answered. One that\n * qualifies later neither enlarges the worklist nor earns a second recovery,\n * and the filter that SELECTED the worklist is not re-asked of each member at\n * its own write — an earlier member may legally change what a later one was\n * selected by. What each member owes AT THE POSITION IT IS CONSUMED is\n * unchanged and still enforced: its own identity, its parent's, and the\n * relation membership {@link captureSeries} and `executeSeries` assert.\n *\n * Only on the batch route: an interactive transaction took `FOR UPDATE` on\n * the same read, so the members it READ cannot change underneath it. That is\n * a row lock and not phantom exclusion — a member connected afterwards is a\n * row no lock covered, and on both routes it is outside the worklist.\n */\n async #requireNoAddedMember(\n series: SeriesOccurrence[\"series\"],\n membership: NonNullable<ReturnType<Selection[\"membership\"]>>,\n rows: readonly Input[]\n ): Promise<void> {\n const ctx = this.context;\n const selection = series.selection;\n const captured = ctx.queries.andSelectors(selection.model, [\n ...(selection.selector ? [selection.selector] : []),\n ctx.queries.excludeIdentities(\n selection.model,\n rows.map((row) => ctx.schema.identity(selection.model, row))\n ),\n ]);\n const failure = membershipRaceFailure(\n series.mutation.kind,\n membership.edge.name,\n \"added\"\n );\n await ctx.requireAbsent(\n ctx.queries.select(\n selection.model,\n { take: 1 },\n {\n edge: membership.edge,\n parent: this.#membershipValues(membership.edge, membership.parent),\n },\n { selector: captured }\n ),\n failure\n );\n }\n private async captureSeries(\n occurrence: CommandOccurrence<SeriesOccurrence>,\n member: Member\n ): Promise<PreparedSeries> {\n const ctx = this.context;\n const attempt = this.attempt;\n const captured = attempt.series.get(occurrence);\n if (captured) return captured;\n const series = occurrence.command.series;\n const selection = series.selection;\n const membership = selection.membership();\n let parentRequirement: { query: Query; failure: Error } | undefined;\n if (membership) {\n const { edge, parent } = membership;\n const failure = new NestedWriteError(\n `Cannot ${series.mutation.kind} relation '${edge.name}': parent record changed across a committed segment.`,\n edge.name\n );\n const parentWhere = () => ({\n ...this.identity(parent),\n ...this.#membershipValues(edge, parent),\n });\n const published = await ctx.flush(\n ctx.queries.select(parent.model, {\n where: parentWhere(),\n select: Object.fromEntries(\n [...parent.demands].map((field) => [field, true])\n ),\n }),\n member\n );\n if (!published[0]) throw ctx.failure(failure, \"result\", member);\n attempt.bind(parent, published[0]);\n parentRequirement = {\n failure,\n query: ctx.queries.select(parent.model, {\n where: parentWhere(),\n select: Object.fromEntries(\n ctx.schema.keys(parent.model).map((field) => [field, true])\n ),\n }),\n };\n }\n // Key order, as every limited write takes its rows (`Queries.keyOrder`).\n const keys = ctx.queries.keyOrder(selection.model);\n const rows = await ctx.read(\n ctx.queries.select(\n selection.model,\n {\n orderBy: Object.fromEntries(keys.map((field) => [field, \"asc\"])),\n take: series.limit,\n },\n membership && {\n edge: membership.edge,\n parent: this.#membershipValues(membership.edge, membership.parent),\n },\n { forUpdate: !ctx.usesBatch, selector: selection.selector }\n ),\n true,\n false,\n selection.model\n );\n if (series.mutation.kind === \"update\") {\n const exclusive = this.#exclusiveMemberMove(\n selection.model,\n series.mutation.raw,\n rows.length\n );\n if (exclusive) throw ctx.failure(exclusive, \"planning\", member);\n }\n if (membership && parentRequirement && ctx.usesBatch) {\n // The complement's own premise, in front of the complement.\n //\n // Membership correlates by VALUE, so once another row takes the captured\n // reference its members answer the same correlation and the complement\n // reads them as additions to a set they were never in. What says \"this\n // parent\" is the premise `executeSeries` already asserts for every\n // member — the same query and the same sentence, asserted here at the\n // position where the captured set is FIXED, because a series that\n // captured no member queues none of the member copies and the complement\n // would otherwise be the only statement of this series that can abort\n // the unit. It is the batch's first statement, so a parent reference\n // reused between the capture and the batch refuses with the sentence the\n // shipped engine raised (`transitions/series-staleness.ts`\n // `g2-series-parent-reference-reused`) instead of the complement's\n // raceable one, which would retry against another parent's members.\n ctx.requirePresent(parentRequirement.query, parentRequirement.failure);\n await this.#requireNoAddedMember(series, membership, rows);\n }\n const members: SelectedSeriesMember[] = ctx.prepareMembers(\n () =>\n rows.map((row): SelectedSeriesMember => {\n const located = this.commands.capture(selection, row);\n attempt.rows.set(located, row);\n attempt.bind(located.fields, row);\n if (series.mutation.kind === \"delete\") {\n // The member's presence, asserted where the set is captured —\n // before any write of the unit — so its loss after the plan-time\n // read rejects at a premise and the operation re-plans once (D-32).\n if (ctx.usesBatch && membership) {\n ctx.requirePresent(\n located.captured(undefined, membership, 1),\n membershipRaceFailure(\n series.mutation.kind,\n membership.edge.name,\n \"removed\"\n )\n );\n attempt.retained.add(located);\n }\n // A tombstone is admitted again for every captured member, from\n // the same generated data and so the same instant.\n const raw = series.mutation.raw;\n return {\n kind: \"delete\",\n located,\n origin: series.mutation.origin,\n ...(raw && {\n values: this.commands.stamp(\n selection.model,\n \"update\",\n this.#memberData(selection, membership, raw)\n ),\n }),\n };\n }\n const child = this.commands.update(\n located,\n this.#memberData(selection, membership, series.mutation.raw),\n series.mutation.raw\n );\n if (membership)\n child.requirement = {\n selection: located,\n membership,\n failure: selection.required!,\n };\n return child;\n }),\n member\n );\n const refusal = this.commands.expandSeries(occurrence, members);\n if (refusal) throw ctx.failure(refusal.error, \"planning\", refusal.member);\n const prepared: PreparedSeries = {\n members: this.commands.seriesMembers(occurrence),\n parentRequirement,\n };\n attempt.series.set(occurrence, prepared);\n return prepared;\n }\n /**\n * One captured member's update data, admitted from the series' raw data as\n * the call was: a nested create in it may leave out what the call's stamps\n * write.\n */\n #memberData(\n selection: Selection,\n membership: BoundMembership | undefined,\n raw: Input\n ): Input {\n const stamps = this.context.scope?.rows.stamps;\n return stamps === undefined\n ? this.#admitMember(selection, membership, raw)\n : parseStamped(stamps, () =>\n this.#admitMember(selection, membership, raw)\n );\n }\n #admitMember(\n selection: Selection,\n membership: BoundMembership | undefined,\n raw: Input\n ): Input {\n const schema = this.context.schema;\n return membership &&\n membership.edge.scope.edge.kind !== \"variantRowCarrier\" &&\n membership.edge.scope.edge.kind !== \"variantJunctionCarrier\"\n ? schema.member(membership.edge.source, membership.edge.name, raw)\n : schema.update(selection.model, raw, true);\n }\n /**\n * One named EXCLUSIVE target membership, applied to many captured rows.\n *\n * A target whose membership is stored once — a junction row unique on the\n * target side, or a reference the TARGET row holds — belongs to exactly one\n * of the rows this series captured, so `connect` / `set` / `connectOrCreate`\n * across more than one of them is not executable by any owner: applied in\n * sequence the last row takes the target from the others, which is the\n * damage measured before this refusal returned ({count: 2}, both rows\n * written, the membership on whichever ran last). These are the retired\n * engine's two registered sentences\n * (`query-engine/relation-key-legality.ts:145`/`:149` at `e8114ed9d^`), kept\n * because D-52 keeps a refusal that names an execution fact — here\n * cardinality — that no owner can execute around.\n *\n * It is stated where the observed COUNT is first known, which is this site:\n * the one place that holds both the captured rows and the mutation they all\n * apply. That is NOT ahead of every write of the unit. A capture flushes,\n * and on the batch route a flush commits everything queued before it, so an\n * enclosing parent's own segment is already durable when this refusal fires\n * — the two routes answer with the same sentence and differ only in what\n * stands committed behind it (D-51's succession of segments, pinned by\n * `tests/raptor3/g4/parity/exclusive-member-cardinality.test.ts`). It reads\n * the payload the caller wrote, which the\n * plan-time analysis (`SelectedSeries.analysis`) already admitted — the\n * per-member admission is NOT re-run here, because a member's admission runs\n * this payload's client-side defaults and every member owns its own\n * (`tests/raptor3/core-structure/member-scope.contract.test.ts`\n * `cs03-peer-scope-root` pins the sequence).\n */\n #exclusiveMemberMove(\n model: AnyModel,\n data: Input,\n count: number\n ): Error | undefined {\n if (count < 2) return undefined;\n for (const name of model[\"~\"].relationNames) {\n const payload = data[name];\n if (payload === undefined) continue;\n const arm =\n model[\"~\"].state.relations[name]![\"~\"].state.target.kind === \"variants\";\n for (const verb of [\"connect\", \"connectOrCreate\", \"set\"] as const) {\n const targets = record(payload)[verb];\n if (targets === undefined) continue;\n for (const target of entries(targets)) {\n const edge = this.context.schema.membership(\n model,\n name,\n arm ? (target.type as string) : undefined\n );\n const stored =\n edge.kind === \"junction\"\n ? edge.uniqueSide === \"target\" &&\n \"that target's member-junction slot can belong to only one of them\"\n : edge.owner === \"target\" &&\n \"that membership is stored on the target row, which can belong to only one of them\";\n if (!stored) continue;\n return new UnsupportedOperationError(\n `updateMany matched ${count} rows, so it cannot apply '${verb}' to relation '${name}': ${stored} — the last row updated would take it from the others. Narrow the filter (or add 'limit: 1') so exactly one row matches, or write this relation in a separate call.`\n );\n }\n }\n }\n return undefined;\n }\n /**\n * The membership a captured member is CONSUMED through, HELD through the\n * write that consumes it.\n *\n * D-65 bounds the worklist at the capture and says what survives that bound:\n * \"what each member owes AT THE POSITION IT IS CONSUMED — its identity, its\n * parent's, and its relation membership — is unchanged and still enforced\".\n * The premises that enforced it only OBSERVED it. A batch is one\n * transaction, not one statement: under READ COMMITTED each statement takes\n * its own snapshot, so a membership change committed after a premise\n * answered is visible to the write behind it, and the review measured\n * exactly that — a member moved to another parent between the unit's last\n * premise and its own ID-addressed DELETE was still deleted for the parent\n * that no longer held it (the repair prompt §2).\n *\n * So the requirement is re-taken HERE, where the member is consumed and\n * beside the parent requirement this site already restates, as a read that\n * HOLDS what it proves for the rest of the transaction — which is where the\n * effect is. It is taken on the row that STORES the membership, because that\n * is the row a race has to change:\n *\n * - a REFERENCE membership is a column of the member's own row, so the held\n * premise over that row proves the membership, holds it, and proves the\n * row is still there in the same statement;\n * - a JUNCTION membership is a row of its own, which no lock on the member\n * reaches. A locking read of the member alone would answer from a\n * cross-table snapshot the substrate is free to re-use after it waits\n * (PostgreSQL re-evaluates a blocked write's qualification against the\n * updated target row, but subqueries over OTHER tables keep the original\n * snapshot), so the junction row is taken under its own lock through the\n * read owner the singular junction capture already uses\n * ({@link Queries.junction}).\n *\n * Nothing reselects, retries or replays: a lost requirement raises the\n * failure that member already owned — the captured series' membership race\n * for a deletion, the located target's own sentence for an update — and the\n * unit aborts where it stands, with whatever earlier segment it acknowledged\n * standing and reported (D-51).\n *\n * The interactive route holds the member ROWS already: its capture reads\n * `FOR UPDATE` ({@link captureSeries}), so a reference membership and the\n * row's presence cannot move underneath it, and only the junction row is\n * left to take.\n */\n private async holdMember(\n member: SelectedSeriesMember,\n located: Selection,\n membership: BoundMembership | undefined\n ): Promise<void> {\n if (!membership) return;\n const ctx = this.context;\n const edge = membership.edge;\n const failure: DeferredFailure =\n member.kind === \"delete\"\n ? () => membershipRaceFailure(\"delete\", edge.name, \"removed\")\n : (member.requirement?.failure ?? located.required!);\n if (ctx.usesBatch) {\n ctx.requirePresent(\n located.captured(undefined, membership, 1, true),\n failure()\n );\n // Stated: the located record's own premise (`run`'s `case \"record\"`) is\n // this same query without the hold, so it does not state it twice.\n this.attempt.retained.add(located);\n }\n if (edge.kind !== \"junction\") return;\n const junction = ctx.queries.junction(\n edge,\n this.#linkValues(edge, membership.parent, located.fields),\n true\n );\n if (ctx.usesBatch) {\n ctx.requirePresent(junction, failure());\n return;\n }\n const rows = await ctx.read(junction, true);\n if (!rows[0]) throw failure();\n }\n async #executeSeries(\n occurrence: CommandOccurrence<SeriesOccurrence>\n ): Promise<number> {\n const ctx = this.context;\n const prepared = this.attempt.series.get(occurrence);\n // The `captureSeries` command `requireSeriesCapture` placed ahead of this\n // series ran in this same attempt (`run`'s `case \"captureSeries\"`), and a\n // recovery replaces the attempt AND the command tree together.\n const { members, parentRequirement } = prepared!;\n const membership = occurrence.command.series.selection.membership();\n for (const child of members) {\n const command = child.command;\n // Every member `captureSeries` built names the row it captured: a\n // `Deletion` carries its `located` by type, and an update member is\n // `Commands.update(located, …)` on that same captured selection.\n const located = command.located!;\n if (ctx.usesBatch) {\n this.attempt.rows.delete(located);\n try {\n await this.runSelection(located);\n } catch (error) {\n throw ctx.failure(error, \"planning\", command);\n }\n }\n await ctx.executeMember(async () => {\n if (ctx.usesBatch && parentRequirement)\n ctx.requirePresent(\n parentRequirement.query,\n parentRequirement.failure\n );\n await this.holdMember(command, located, membership);\n await this.run(child);\n }, command);\n }\n return members.length;\n }\n}\n","import { NestedWriteError } from \"@errors\";\nimport type { ResolvedSlot } from \"@schema/validation/relation-resolution\";\nimport { unreachable } from \"../shared/invariant\";\nimport type { PreparedSelector, SelectorFacts } from \"../shared/query\";\nimport { entries, type Input, record } from \"../shared/schema\";\nimport {\n bindMembership,\n linkJudgement,\n type Membership,\n storedFields,\n} from \"../shared/storage\";\nimport { Assignments, type FieldValue, type Origin } from \"./assignments\";\nimport type {\n AbsenceRequirement,\n Choose,\n CommandOccurrence,\n Commands,\n Deletion,\n JunctionCapture,\n MembershipRequirement,\n RecordCommand,\n Removal,\n SelectedSeries,\n SeriesCapture,\n SeriesOccurrence,\n SetMutation,\n} from \"./commands\";\nimport {\n DELETE_JUDGEMENT,\n MEMBERSHIP_MOVE,\n membershipRaceFailure,\n} from \"./commands\";\nimport {\n type BoundMembership,\n junctionPairs,\n membershipFields,\n nestedTargetAddressesConstraint,\n type Selection,\n type SelectionSource,\n} from \"./selection\";\n\ntype Junction = Extract<Membership, { kind: \"junction\" }>;\ntype Supplier =\n | { readonly kind: \"query\"; readonly selector: PreparedSelector }\n | { readonly kind: \"producer\"; readonly producer: Assignments };\n\nconst mutationOrder = [\n \"disconnect\",\n \"delete\",\n \"create\",\n \"connect\",\n \"connectOrCreate\",\n \"upsert\",\n \"update\",\n \"set\",\n \"updateMany\",\n] as const;\nconst collectionMutationOrder = [\n \"disconnect\",\n \"delete\",\n \"set\",\n \"updateMany\",\n \"deleteMany\",\n \"update\",\n \"upsert\",\n \"connectOrCreate\",\n \"connect\",\n \"create\",\n \"createMany\",\n] as const;\n/**\n * The relation-write vocabulary, DERIVED from the two orders that already own\n * it — the orders are what runs a payload's verbs, so nothing can be a verb\n * here without being one there. Validation's nested-write object schemas\n * (`validation/relations/{create,update,to-one-mutation-schema}.ts` and\n * `relations/polymorphic/{create,update,collection-mutation}.ts`) are strict\n * by `primitives/object.ts`'s default and admit no other key, which is what\n * lets {@link RelationBody.expand} name the payload's keys at this type.\n */\ntype RelationVerb =\n | (typeof mutationOrder)[number]\n | (typeof collectionMutationOrder)[number];\n\n/**\n * The one sentence for a nested target the plan looked for and did not find;\n * `parentScoped` names the search as one through this parent's membership.\n */\nfunction missingTarget(\n verb: string,\n relation: string,\n parentScoped = true\n): NestedWriteError {\n return new NestedWriteError(\n `Cannot ${verb} relation '${relation}': target record was not found${parentScoped ? \" for this parent\" : \"\"}.`,\n relation\n );\n}\n/** Two admitted unique selectors address the same row. */\nfunction sameTarget(\n left: ReadonlyMap<string, unknown>,\n right: ReadonlyMap<string, unknown>\n): boolean {\n return (\n left.size === right.size &&\n [...left].every(\n ([field, value]) => right.has(field) && Object.is(right.get(field), value)\n )\n );\n}\n\n/** One admitted relation body owns its order, parent, slot and supplied continuation. */\nexport class RelationBody {\n #supplier: Supplier | undefined;\n readonly #direct: boolean;\n readonly #hasSupply: boolean;\n readonly #commands: Commands;\n readonly #parent: RecordCommand;\n readonly #slot: ResolvedSlot;\n readonly #admitted: Input;\n readonly #raw: Input;\n constructor(\n commands: Commands,\n parent: RecordCommand,\n slot: ResolvedSlot,\n admitted: Input,\n raw: Input\n ) {\n this.#commands = commands;\n this.#parent = parent;\n this.#slot = slot;\n this.#admitted = admitted;\n this.#raw = raw;\n this.#direct =\n !slot.member &&\n (slot.edge.kind === \"variantRowCarrier\" ||\n slot.edge.kind === \"variantJunctionCarrier\");\n this.#hasSupply = [\"create\", \"connect\", \"connectOrCreate\", \"upsert\"].some(\n (verb) => admitted[verb] !== undefined\n );\n }\n #supply(target: RecordCommand | Choose): void {\n if (this.#direct) return;\n this.#supplier =\n target.kind === \"choose\" && !target.missing\n ? { kind: \"query\", selector: target.lookup.selector }\n : { kind: \"producer\", producer: target.fields };\n }\n /** One nested create of `edge`'s target, under this body's parent. */\n #child(edge: Membership, data: Input, raw: Input): RecordCommand {\n const parent = this.#parent;\n return this.#commands.create(\n edge.target,\n data,\n raw,\n edge.kind === \"reference\" && edge.owner === \"target\"\n ? { edge, source: parent.fields }\n : undefined,\n parent.operation ?? parent.fields.operation,\n parent.fields.deferred\n );\n }\n expand(): void {\n const parent = this.#parent;\n const resolved = this.#slot;\n const name = resolved.slot.field;\n const mutation = this.#admitted;\n const rawMutation = this.#raw;\n const direct = this.#direct;\n const schema = this.#commands.context.schema;\n const order: readonly string[] =\n parent.model[\"~\"].state.relations[name]![\"~\"].state.cardinality === \"many\"\n ? collectionMutationOrder\n : mutationOrder;\n const bound = new Map<string | undefined, Membership>();\n const membership = (variant?: string) => {\n let edge = bound.get(variant);\n if (edge) return edge;\n edge = bindMembership(schema, parent.model, name, variant);\n bound.set(variant, edge);\n if (parent.fields.operation === \"update\" && edge.kind === \"reference\") {\n const keys = schema.keys(parent.model);\n for (const pair of edge.pairs)\n if (edge.owner === \"source\" || !keys.includes(pair.source))\n parent.fields.requireLiteral(pair.source, edge.name);\n }\n return edge;\n };\n // Admission is the boundary: the relation's nested-write schema admits\n // only the keys of {@link RelationVerb}, so the admitted payload's entries\n // are read AT that type here, once, and every consumer below trusts it\n // (ELEGANCE §5).\n const verbs = Object.entries(mutation).sort(\n ([a], [b]) => order.indexOf(a) - order.indexOf(b)\n ) as [RelationVerb, unknown][];\n for (const [verb, payload] of verbs) {\n if (payload === undefined) continue;\n // One origin per verb for what the verb does as a whole (a set's clear,\n // a variant carrier's clear); each payload ENTRY of a verb is its own\n // mutation and gets its own origin (N1): entries run in declaration\n // order, a later entry's read observes an earlier entry's write, and a\n // mutation's own effects — placed behind its read — are told apart from\n // a sibling entry's by that origin.\n const origin = this.#commands.createOrigin(name, verb);\n const entryOrigin = () => this.#commands.createOrigin(name, verb);\n if (!direct) {\n this.#relation(membership(), verb, payload, rawMutation[verb], origin);\n continue;\n }\n if (\n resolved.edge.kind === \"variantRowCarrier\" &&\n verb === \"disconnect\" &&\n typeof payload === \"boolean\"\n ) {\n const clearability = schema.clearability(resolved);\n if (payload && !this.#hasSupply && clearability.kind === \"columns\") {\n const owner = this.#commands.place(\n parent,\n { kind: \"membership\" },\n \"before\"\n );\n const contribution = {\n origin,\n scope: resolved,\n identity: parent.located?.facts,\n };\n for (const field of clearability.fields)\n parent.fields.contribute(\n field,\n { kind: \"literal\", value: null },\n `Cannot disconnect relation '${name}'.`\n );\n this.#commands.publishMembership(owner, parent.fields, contribution);\n }\n continue;\n }\n if (verb === \"set\") {\n const carrier = resolved.edge as Extract<\n typeof resolved.edge,\n { kind: \"variantJunctionCarrier\" }\n >;\n const targets = entries(payload).map((tagged) => {\n const edge = membership(tagged.type as string);\n return {\n edge,\n target: this.#setTargets(edge, [record(tagged.where)], origin)[0]!,\n };\n });\n for (const member of carrier.members)\n this.#clearMembership(membership(member.variant), [], origin);\n for (const { edge, target } of targets) this.association(edge, target);\n continue;\n }\n for (const [index, tagged] of entries(payload).entries()) {\n const origin = entryOrigin();\n const rawTagged = entries(rawMutation[verb])[index]!;\n const edge = membership(tagged.type as string);\n const untag = (value: Input) =>\n verb === \"create\"\n ? value.data\n : verb === \"connect\" || verb === \"delete\" || verb === \"disconnect\"\n ? value.where\n : value;\n this.#relation(edge, verb, untag(tagged), untag(rawTagged), {\n ...origin,\n relation: edge.name,\n });\n }\n }\n }\n #relation(\n edge: Membership,\n verb: RelationVerb,\n payload: unknown,\n rawPayload: unknown,\n origin: Origin\n ): void {\n const parent = this.#parent;\n const hasSupply = this.#hasSupply;\n // Each payload entry is its own mutation (N1): its own origin, in\n // declaration order behind the verb's.\n const entryOrigin = () =>\n this.#commands.createOrigin(\n origin.relation,\n origin.operation,\n origin.slot\n );\n if (\n parent.fields.operation === \"update\" &&\n edge.kind === \"reference\" &&\n edge.owner === \"target\" &&\n edge.pairs.some((pair) => parent.fields.writesField(pair.source)) &&\n !parent.transitions.includes(edge)\n )\n parent.transitions.push(edge);\n switch (verb) {\n case \"disconnect\":\n case \"delete\": {\n if (payload === false) break;\n // DESIGN §5.3's truth table, decided where the payload's form is\n // known: `disconnect: true` and `delete: true` are LAX — an empty slot\n // is a no-op, so the lookup is not required and a consumer that binds\n // no row emits nothing — while an explicit selector is STRICT and a\n // missing target is the correlated refusal.\n const lax = payload === true;\n for (const selector of lax ? [undefined] : entries(payload)) {\n const origin = entryOrigin();\n const unique = nestedTargetAddressesConstraint(edge, verb);\n // Both take related rows: a row the call cannot see is not found,\n // as for any nested lookup. A managed delete target is tombstoned,\n // from the default domain's too, and keeps every link it has.\n const tombstone =\n verb === \"delete\"\n ? this.#commands.tombstone(edge.target)\n : undefined;\n const queries = this.#commands.context.queries;\n const prepared = queries.prepareSelector(\n edge.target,\n selector,\n unique\n );\n const outgoing = this.#commands.lookup(\n edge.target,\n {\n kind: \"query\",\n where: selector,\n unique,\n selector: this.#commands.candidates(\n prepared,\n \"related\",\n tombstone !== undefined,\n verb === \"delete\" ? DELETE_JUDGEMENT : linkJudgement(edge)\n ),\n membership: { edge, parent: parent.located!.fields },\n },\n lax ? undefined : () => missingTarget(verb, edge.name)\n );\n outgoing.origin = origin;\n // A lax delete takes the member the slot holds: one its delete verb\n // does not take is refused, never kept while the call succeeds\n // (plan §5.1). The parent's own key names its member, seen or not;\n // a member's key names it only where the call sees it, so a hidden\n // one is an empty slot, as for a clear. The strict form's sentence:\n // no refusal tells a hidden target from one it may not delete (§5.3).\n // A lax disconnect is the clear's ({@link OperationContext.remove}).\n if (\n lax &&\n verb === \"delete\" &&\n queries.domainOf(edge.target, \"related\", DELETE_JUDGEMENT) !==\n queries.domainOf(edge.target, \"related\")\n )\n outgoing.unjudged = {\n addressed:\n edge.kind === \"reference\" && edge.owner === \"source\"\n ? prepared\n : this.#commands.candidates(\n prepared,\n \"related\",\n tombstone !== undefined\n ),\n failure: () => missingTarget(verb, edge.name),\n };\n this.#membershipSource(edge, parent.located!.fields);\n // Initial absence and loss after observation are distinct facts\n // (ELEGANCE §6, D-32): `required` says what an empty slot means\n // (lax or strict), `retained` what the captured member's loss\n // between the plan-time read and the batch means, asserted where the\n // observation is taken, before any write of the unit. Only the LAX\n // form names no row: its loss is the membership race, and the one\n // recovery re-plans the slot as the race left it. The strict form\n // names a row by its selector; a recovery would re-read that selector\n // and act on whatever row answers it now — the one thing a\n // captured-row loss must not authorise (D-34) — so it keeps the\n // identity sentence `requireLookup` supplies from `required`.\n if (lax)\n outgoing.retained = () =>\n membershipRaceFailure(verb, edge.name, \"removed\");\n const outgoingOccurrence = this.#requireLookup(outgoing);\n const deletion: Deletion = {\n kind: \"delete\",\n located: outgoing,\n origin,\n ...(tombstone && { values: tombstone.admitted }),\n };\n if (tombstone)\n this.#requireUnreferenced(\n edge,\n parent.located!.fields,\n outgoing.selector,\n origin\n );\n if (edge.kind === \"reference\" && edge.owner === \"source\") {\n if (\n !(hasSupply || tombstone) &&\n edge.clearability.kind === \"columns\"\n ) {\n const contribution = {\n origin,\n scope: edge.scope,\n identity: parent.located?.facts,\n };\n for (const field of edge.clearability.fields)\n parent.fields.contribute(\n field,\n { kind: \"literal\", value: null },\n `Cannot disconnect relation '${edge.name}'.`\n );\n this.#commands.publishMembership(\n outgoingOccurrence,\n parent.fields,\n contribution\n );\n }\n if (verb === \"delete\")\n this.#commands.place(parent, deletion, \"after\", origin);\n } else {\n // A lax removal names no target: it clears whatever member the\n // slot holds at execution (at most one on a to-one edge), which is\n // the set-based clear a `Removal` without a target already is.\n const removal: Removal = {\n kind: \"remove\",\n edge,\n source: parent.fields,\n target: lax ? undefined : outgoing.fields,\n keep: [],\n origin,\n };\n // A JUNCTION `delete` removes the LINK row before the target, in\n // this one region: the link references the target, so deleting the\n // target first is a foreign-key violation wherever the constraint\n // is enforced. The order is the shipped engine's own — \"locate the\n // connected child, DELETE its join rows, then the child\"\n // (`write-engine/RelationJunctionPart.ts:911-937` `compileDelete`:\n // `junctionDeleteTargets` then `childDelete`). A `disconnect`\n // places the removal alone, and a reference-held target carries its\n // own foreign key, so it places the deletion alone.\n if (verb === \"delete\" && edge.kind === \"junction\" && !tombstone)\n this.#commands.place(parent, removal, \"after\", origin);\n this.#commands.place(\n parent,\n verb === \"delete\" ? deletion : removal,\n \"after\",\n origin\n );\n }\n }\n break;\n }\n case \"create\":\n for (const [index, child] of entries(payload).entries()) {\n const origin = entryOrigin();\n const target = this.#child(edge, child, entries(rawPayload)[index]!);\n target.origin = origin;\n this.association(edge, target);\n this.#supply(target);\n }\n break;\n case \"createMany\": {\n const body = record(payload);\n if (body.skipDuplicates)\n this.#commands.context.admitsSuppression(\"nested createMany rows\");\n const rawBody = record(rawPayload);\n const rawRows = entries(rawBody.data);\n const records = entries(body.data).map((child, index) => {\n const target = this.#child(edge, child, rawRows[index]!);\n target.origin = origin;\n if (body.skipDuplicates)\n target.suppression = { kind: \"skipDuplicate\" };\n return this.association(edge, target, false, target);\n });\n this.#commands.place(\n parent,\n { kind: \"series\", records },\n \"after\",\n origin\n );\n break;\n }\n case \"connect\":\n case \"connectOrCreate\":\n case \"upsert\":\n case \"update\": {\n // `docs/architecture/retired/write-engine-ATOM.md` §12 \"Same-operation\n // duplicate\": the rows this body's earlier `connectOrCreate` entries\n // PROVABLY create.\n const createdTargets: ReadonlyMap<string, unknown>[] = [];\n const connectedTargets: ReadonlyMap<string, unknown>[] = [];\n for (const [index, supplied] of entries(payload).entries()) {\n const origin = entryOrigin();\n const source = entries(rawPayload)[index]!;\n const conditional: Input =\n verb === \"connect\" ? { where: supplied } : supplied;\n // The child's OWN key update is judged by the same owner that judges\n // the root's, at the position this body already admits it, and R-D2\n // (c) is about the SHAPE, not the site. `connect` and\n // `connectOrCreate` carry no update payload, so they ask nothing.\n //\n // WHEN the answer is stated is the shipped engine's placement, not\n // this body's. A nested `update` is asserted at COMPILE time\n // (`RelationWritePart.ts:856`), so its refusal is raised here, before\n // anything is located. A nested `upsert` is not: the shipped engine\n // builds the same assertion as a closure (`RelationUpsertPart.ts:1006`)\n // and invokes it only inside the FOUND arm (`:468`), so an absent\n // target takes the create arm and the update payload is never judged\n // — the shape `EngineSchema.keyPortabilityRefusal`'s own docblock\n // warns a wider placement breaks, \"an upsert that CREATES a row the\n // arithmetic never touches\". The upsert's refusal is therefore handed\n // to its found arm below, the way the ROOT upsert hands it to its own\n // (`commands.ts:1236-1239`). The carrier differs because the position\n // does: the root assigns `CommandOccurrence.refusal` on an already\n // MATERIALIZED arm, while this body writes a recipe, and a recipe\n // never carries occurrence refusal into materialization (guide,\n // \"Reusing a command or `Selection` never reuses occurrence ancestry,\n // children, refusal, or attempt state\"). The found arm's own deferred\n // `Assignments` is the recipe-borne half of the same channel: it holds\n // the refusal until `activate()` observes the choice\n // (`execution.ts:259`, `:389`), which is the arm-conditional rule the\n // guide already states for every `Choose` arm.\n const childUpdate =\n verb === \"upsert\" ? conditional.update : conditional.data;\n const keyRefusal =\n this.#commands.context.schema.keyPortabilityRefusal(\n edge.target,\n childUpdate\n );\n if (keyRefusal && verb !== \"upsert\") throw keyRefusal;\n const missing =\n conditional.create === undefined\n ? undefined\n : this.#child(\n edge,\n record(conditional.create),\n record(source.create)\n );\n if (missing) missing.origin = origin;\n const correlated =\n (verb === \"update\" || verb === \"upsert\") &&\n parent.fields.operation === \"update\";\n const continuation =\n verb === \"update\" && !edge.many ? this.#supplier : undefined;\n const suppliedSelector =\n continuation?.kind === \"query\" ? continuation : undefined;\n const queries = this.#commands.context.queries;\n const ownSelector = queries.prepareSelector(\n edge.target,\n conditional.where as Input | undefined,\n nestedTargetAddressesConstraint(edge, verb)\n );\n // `docs/architecture/retired/write-engine-ATOM.md` §12:\n // first-create-wins locally. An entry whose target an earlier entry\n // of the SAME operation provably creates ADOPTS that\n // row — the association is the earlier entry's — so it opens no\n // second decision read, no found guard and no missing race pin: its\n // producer is inside this operation. The two facts are the ones\n // `CommandExecution.matchesSelectedConstraint` already reads together.\n const addressed = ownSelector.uniqueValues;\n // A first connect may rewrite an FK that belongs to the target's\n // compound key. Repeating its original selector must not look it up again.\n if (verb === \"connect\") {\n const facts = queries.selectorFacts(ownSelector);\n if (\n facts.exact &&\n Object.keys(record(conditional.where)).every(\n (field) =>\n facts.fields.has(field) ||\n ownSelector.uniqueKey?.name === field\n )\n ) {\n if (\n connectedTargets.some((target) =>\n sameTarget(target, facts.equals)\n )\n )\n continue;\n connectedTargets.push(facts.equals);\n }\n }\n if (verb === \"connectOrCreate\" && addressed) {\n if (\n createdTargets.some((earlier) => sameTarget(earlier, addressed))\n )\n continue;\n if (\n missing &&\n [...addressed].every(([field, value]) => {\n const proposed = missing.fields.known(field);\n return (\n proposed?.kind === \"literal\" &&\n Object.is(proposed.value, value)\n );\n })\n )\n createdTargets.push(addressed);\n }\n // Targets are related rows: a hidden one is not found, so a connect\n // never links it and an upsert never updates it. An update, or an\n // upsert's found arm, writes the target's own data; a connect changes\n // the target's link where the target holds it (R3).\n const rawUpdate = record(\n verb === \"upsert\" ? source.update : (source.data ?? source)\n );\n const judgement =\n verb === \"update\" || verb === \"upsert\"\n ? this.#commands.judge(\n edge.target,\n record(childUpdate),\n rawUpdate,\n verb\n )\n : linkJudgement(edge);\n let selectionSource: SelectionSource = {\n kind: \"query\",\n where: conditional.where as Input | undefined,\n selector: ownSelector,\n purpose: \"related\",\n judgement,\n };\n let facts: SelectorFacts | undefined;\n if (suppliedSelector) {\n const supplierSelector = suppliedSelector.selector;\n const ownFacts = queries.selectorFacts(ownSelector);\n const supplierFacts = queries.selectorFacts(supplierSelector);\n facts = ownFacts.fields.size === 0 ? supplierFacts : ownFacts;\n // The supplier's selector already takes related rows; the\n // update it continues still takes its verb.\n const supplied = queries.andSelectors(edge.target, [\n supplierSelector,\n ownSelector,\n ]);\n selectionSource = {\n kind: \"query\",\n selector: judgement\n ? queries.candidates(supplied, \"related\", undefined, judgement)\n : supplied,\n };\n }\n if (continuation?.kind === \"producer\") {\n selectionSource = {\n kind: \"producer\",\n where: selectionSource.where,\n selector: selectionSource.selector,\n producer: continuation.producer,\n purpose: selectionSource.purpose,\n judgement: selectionSource.judgement,\n };\n continuation.producer.select(\n storedFields(this.#commands.context.schema, edge.target)\n );\n }\n let foundMembership: BoundMembership | undefined;\n // The parent's FINAL membership value, pair by pair: what its own\n // payload NAMES for that column, and otherwise the row it located.\n // \"The parent's FK value is its FINAL value\" is the delegated fold's\n // pinned semantics (M1,\n // `tests/contracts/engine/write/parent-held-delegated-fk-rebind-correlation.test.ts`):\n // a rebind in the parent's own SET moves the member, so a correlated\n // arm locates — and writes — the row the parent ENDS on, never the\n // one it is moving away from. The same value is what that row HOLDS\n // for the edge's referenced field, which is why a correlated arm's\n // own membership contribution RESTATES the parent's assignment\n // instead of adding a second final one.\n let correlation: Record<string, FieldValue> | undefined;\n if (correlated && !continuation) {\n const values =\n edge.kind === \"reference\"\n ? edge.pairs.map((pair) => ({\n ...pair,\n value:\n parent.fields.known(pair.source) ??\n parent.located!.fields.field(pair.source),\n }))\n : [];\n correlation = Object.fromEntries(\n values.map(({ target, value }) => [target, value])\n );\n const membership = {\n edge,\n parent: this.#correlationParent(\n edge,\n verb,\n Object.fromEntries(\n values.map(({ source, value }) => [source, value])\n )\n ),\n };\n this.#membershipSource(edge, membership.parent);\n if (verb === \"upsert\" && conditional.where !== undefined)\n foundMembership = membership;\n else\n selectionSource = {\n kind: \"query\",\n where: selectionSource.where,\n selector: selectionSource.selector,\n membership,\n purpose: selectionSource.purpose,\n judgement: selectionSource.judgement,\n };\n }\n const lookup = this.#commands.lookup(\n edge.target,\n selectionSource,\n verb === \"connect\" || verb === \"update\"\n ? () => missingTarget(verb, edge.name, verb === \"update\")\n : undefined,\n facts\n );\n lookup.origin = origin;\n // The missing arm inserts the key this probe just looked for, so the\n // probe does not lock the absence it may find\n // (`Selection.insertsWhenAbsent`).\n if (missing) lookup.insertsWhenAbsent = true;\n if (verb === \"connectOrCreate\")\n lookup.retained = () =>\n new NestedWriteError(\n \"Record was replaced by another transaction during nested connectOrCreate\",\n edge.name\n );\n lookup.membershipOnly =\n verb === \"connect\" &&\n !(edge.kind === \"reference\" && edge.owner === \"source\");\n // A connect whose located value the PARENT's own SET spends carries\n // that row's presence into the write: the premise is proved inside\n // the atomic unit that carries the write it protects (D-29), so a\n // target that vanishes between the plan-time read and the batch\n // aborts the unit with the arm's own identity sentence instead of\n // reaching the provider as a foreign-key violation on a column the\n // engine chose. Every other connect already states it — a\n // child-held one through the target's own record command, a\n // junction through its captured pair, `connectOrCreate` through the\n // replacement race above — and this selector NAMES a row, so its\n // loss is the non-raceable identity sentence (D-34), which is what\n // `required` already spells.\n if (verb === \"connect\" && !lookup.membershipOnly)\n lookup.retained = lookup.required;\n if (this.#direct && verb === \"connect\") this.#requireLookup(lookup);\n if (\n correlated &&\n !continuation &&\n verb === \"update\" &&\n edge.kind === \"junction\"\n )\n this.#requireLookup(lookup);\n const foundRequirement: MembershipRequirement | undefined =\n foundMembership && {\n selection: lookup,\n membership: foundMembership,\n failure: () => missingTarget(\"upsert\", edge.name),\n };\n const chosen = new Assignments(\n edge.target,\n \"select\",\n {},\n {},\n undefined,\n missing ? [missing.fields] : []\n );\n for (const [field, value] of Object.entries(correlation ?? {}))\n chosen.restate(field, value);\n const target: Choose = {\n kind: \"choose\",\n model: edge.target,\n lookup,\n foundRequirement,\n missing: missing\n ? this.#commands.occurrence(missing, \"after\")\n : undefined,\n fields: chosen,\n found:\n verb === \"upsert\" || verb === \"update\"\n ? this.#commands.occurrence(\n this.#commands.update(\n lookup,\n record(childUpdate),\n rawUpdate,\n true,\n verb === \"upsert\" ? \"upsert\" : \"update\"\n ),\n \"after\"\n )\n : undefined,\n };\n if (target.found) {\n target.found.command.origin = origin;\n target.found.command.requirement = foundRequirement;\n // The upsert's key refusal, on the arm that owns it: the update the\n // found arm would run is the payload being judged, its `Assignments`\n // is deferred, and an untaken arm never activates. `undefined` for a\n // nested `update`, which already refused above.\n if (keyRefusal) target.found.command.fields.reject(keyRefusal);\n }\n this.association(edge, target, correlated);\n this.#supply(target);\n }\n break;\n }\n case \"set\": {\n this.#replaceMembership(edge, entries(payload), origin);\n break;\n }\n case \"updateMany\":\n case \"deleteMany\": {\n const rawMembers = entries(rawPayload);\n parent.fields.select(this.#commands.context.schema.keys(parent.model));\n this.#membershipSource(edge, parent.fields);\n for (const [index, member] of entries(payload).entries()) {\n const origin = entryOrigin();\n const input = record(member);\n // The same owner, at the third nested position that admits an update\n // payload. A `deleteMany` member has no `data`, so it asks nothing.\n const keyRefusal =\n this.#commands.context.schema.keyPortabilityRefusal(\n edge.target,\n input.data\n );\n if (keyRefusal) throw keyRefusal;\n const where =\n verb === \"updateMany\"\n ? input.where === undefined\n ? undefined\n : record(input.where)\n : record(input.where ?? input);\n // Rule 6's first sentence: keep scalar bulk work set-oriented. The\n // provider evaluates the membership and the member filter at this\n // statement's own position, so a row-held membership whose payload\n // names no relation needs no lookup, no series and no capture — the\n // shipped `buildUpdateMany`/`buildDeleteMany` shape\n // (`RelationWritePart.ts:484-504`, `:674-693`). A junction member set\n // must still be materialised through the join table, and a\n // relation-bearing `updateMany` still owns a record per member.\n const context = this.#commands.context;\n // A managed target's members are tombstoned: their candidates are the\n // call's and the default domain's, and they keep every link.\n const tombstone =\n verb === \"deleteMany\"\n ? this.#commands.tombstone(edge.target)\n : undefined;\n const selector = this.#commands.candidates(\n context.queries.prepareSelector(edge.target, where),\n \"related\",\n tombstone !== undefined,\n verb === \"deleteMany\"\n ? DELETE_JUDGEMENT\n : this.#commands.judge(\n edge.target,\n record(input.data),\n record(rawMembers[index]!.data)\n )\n );\n const data = tombstone ? tombstone.admitted : record(input.data);\n if (\n edge.kind === \"reference\" &&\n (verb === \"deleteMany\" ||\n !context.schema.namesRelation(edge.target, data))\n ) {\n const mutation: SetMutation = {\n kind: \"set\",\n edge,\n parent: parent.fields,\n model: edge.target,\n selector,\n ...(verb === \"updateMany\" || tombstone\n ? {\n values: tombstone\n ? data\n : this.#commands.stamp(\n edge.target,\n \"update\",\n data,\n record(rawMembers[index]!.data)\n ),\n }\n : {}),\n operation: verb,\n origin,\n };\n if (tombstone)\n this.#requireUnreferenced(\n edge,\n parent.fields,\n selector,\n origin,\n true\n );\n this.#commands.place(parent, mutation, \"after\", origin);\n continue;\n }\n const selection = this.#commands.lookup(\n edge.target,\n {\n kind: \"query\",\n where,\n selector,\n membership: { edge, parent: parent.fields },\n },\n () =>\n missingTarget(\n verb === \"updateMany\" ? \"update\" : \"delete\",\n edge.name\n )\n );\n selection.origin = origin;\n const mutation: SelectedSeries[\"mutation\"] =\n verb === \"updateMany\"\n ? {\n kind: \"update\",\n raw: record(rawMembers[index]!.data),\n }\n : {\n kind: \"delete\",\n origin,\n ...(tombstone && { raw: tombstone.raw }),\n };\n const analysis: RecordCommand | Deletion =\n mutation.kind === \"update\"\n ? this.#commands.update(selection, data, mutation.raw, true)\n : {\n kind: \"delete\",\n located: selection,\n origin,\n ...(tombstone && { values: tombstone.admitted }),\n };\n if (analysis.kind === \"record\") analysis.origin = origin;\n const series: SelectedSeries = {\n selection,\n analysis,\n mutation,\n };\n if (tombstone)\n this.#requireUnreferenced(edge, parent.fields, selector, origin);\n const target = this.#commands.place(\n parent,\n this.#commands.selectedSeries(series),\n \"after\",\n origin\n );\n this.#requireSeriesCapture(target);\n }\n break;\n }\n default:\n unreachable(verb, \"relation verb\");\n }\n }\n /**\n * A tombstoning nested delete's referential requirement, placed right before\n * its effect: no candidate in this parent's slot is still referenced through\n * a restricting slot. The parent's own link is excepted: the tombstone keeps\n * it, where a hard delete removes it before the row.\n */\n #requireUnreferenced(\n edge: Membership,\n parent: Assignments,\n candidates: PreparedSelector,\n origin: Origin,\n lock?: true\n ): void {\n const commands = this.#commands;\n const schema = commands.context.schema;\n const slots = schema.restrictingSlots(edge.target);\n if (slots.length === 0) return;\n const except = slots.find(\n (slot) =>\n schema.index.get(edge.target)?.get(slot)?.edge === edge.scope.edge &&\n !(edge.target === edge.source && slot === edge.name)\n );\n const requirement: AbsenceRequirement = {\n kind: \"absent\",\n model: edge.target,\n membership: { edge, parent },\n excluding: [],\n failure: commands.restrictFailure(edge.target),\n restrict: { candidates, except, lock },\n };\n commands.place(this.#parent, requirement, \"after\", origin);\n }\n #requireLookup(\n lookup: Selection | JunctionCapture | AbsenceRequirement\n ): CommandOccurrence<Selection | JunctionCapture | AbsenceRequirement> {\n const parent = this.#parent;\n if (lookup.kind === \"lookup\") lookup.retained ??= lookup.required;\n return this.#commands.place(parent, lookup, \"before\");\n }\n #requireSeriesCapture(target: CommandOccurrence<SeriesOccurrence>): void {\n const command: SeriesCapture = {\n kind: \"captureSeries\",\n target,\n };\n this.#commands.place(this.#parent, command, \"capture\");\n }\n #replaceMembership(\n edge: Membership,\n selectors: Input[],\n origin: Origin\n ): void {\n const targets = this.#setTargets(edge, selectors, origin);\n this.#clearMembership(edge, targets, origin);\n for (const target of targets) this.association(edge, target);\n }\n #setTargets(edge: Membership, selectors: Input[], origin: Origin): Choose[] {\n return selectors.map((where): Choose => {\n const lookup = this.#commands.lookup(\n edge.target,\n {\n kind: \"query\",\n where,\n unique: nestedTargetAddressesConstraint(edge, \"set\"),\n purpose: \"related\",\n judgement: linkJudgement(edge),\n },\n () => missingTarget(\"set\", edge.name, false)\n );\n // One origin for the whole set: its lookups, its clear and its\n // associations are one mutation, and a dependent lookup lands ahead of\n // the clear that keeps its row (N1).\n lookup.origin = origin;\n this.#requireLookup(lookup);\n const target: Choose = {\n kind: \"choose\",\n model: edge.target,\n lookup,\n fields: new Assignments(edge.target, \"select\"),\n };\n target.lookup.fields.select(\n this.#commands.context.schema.keys(edge.target)\n );\n return target;\n });\n }\n #clearMembership(edge: Membership, targets: Choose[], origin: Origin): void {\n const parent = this.#parent;\n if (edge.kind === \"reference\") {\n if (edge.clearability.kind === \"none\") {\n const required = [\n ...(edge.discriminator?.side === \"target\"\n ? [edge.discriminator.field]\n : []),\n ...edge.pairs.map((pair) => pair.target),\n ];\n this.#membershipSource(edge, parent.located!.fields);\n const requirement: AbsenceRequirement = {\n kind: \"absent\",\n model: edge.target,\n membership: { edge, parent: parent.located!.fields },\n excluding: targets.map((target) => target.lookup.fields),\n failure: () =>\n new NestedWriteError(\n `Cannot set relation '${edge.name}' because foreign key field(s) ${required.join(\", \")} are required: rows removed from the set cannot be disconnected. Delete them instead.`,\n edge.name\n ),\n };\n this.#commands.place(\n parent,\n requirement,\n \"before\",\n targets.at(-1)?.lookup.origin ?? origin\n );\n } else\n this.#commands.place(\n parent,\n {\n kind: \"remove\",\n edge,\n source: parent.fields,\n keep: targets.map((target) => target.lookup.fields),\n origin,\n },\n \"after\",\n origin\n );\n } else\n this.#commands.place(\n parent,\n { kind: \"remove\", edge, source: parent.fields, keep: [], origin },\n \"after\",\n origin\n );\n }\n private association(\n edge: Membership,\n target: RecordCommand,\n premise?: boolean,\n seriesMember?: RecordCommand\n ): CommandOccurrence<RecordCommand>;\n private association(\n edge: Membership,\n target: Choose,\n premise?: boolean,\n seriesMember?: RecordCommand\n ): CommandOccurrence<Choose>;\n private association(\n edge: Membership,\n target: RecordCommand | Choose,\n premise = false,\n seriesMember?: RecordCommand\n ): CommandOccurrence<RecordCommand | Choose> {\n const source = this.#parent;\n const conditionalParentBinding =\n edge.kind === \"reference\" &&\n edge.owner !== \"source\" &&\n target.kind === \"choose\" &&\n !premise\n ? { edge, target }\n : undefined;\n if (conditionalParentBinding && !conditionalParentBinding.target.found) {\n const { lookup } = conditionalParentBinding.target;\n conditionalParentBinding.target.found = this.#commands.occurrence(\n this.#commands.update(lookup, MEMBERSHIP_MOVE, {}, true),\n \"after\"\n );\n }\n // ONE rule, for every found arm whose probe did not keep its lock. Such an\n // arm's UPDATE can address a row that is no longer there\n // (`Selection.insertsWhenAbsent`), and an UPDATE that asks the provider for\n // nothing back never learns whether it addressed one — so on a provider\n // without RETURNING the loss is invisible. Two arms reach it and both are\n // built here: the binding an inverse-reference `connect`/`connectOrCreate`\n // constructs above, which exists only to write the child's foreign key and\n // therefore demands nothing at all, and a nested to-ONE `upsert`, whose\n // found arm does carry the caller's payload but carries no `where`, so no\n // found membership confirmation is built for it (`Choose.foundRequirement`)\n // and the locking `Selection.confirm` read that states the CORRELATED arm's\n // target proves nothing about this one. Demanding the target's own keys is\n // what makes `OperationContext.update` issue the read that answers \"which\n // row did this UPDATE write?\" — the CURRENT stored-row read where the\n // provider has no RETURNING — and raise `UPDATE did not produce the\n // required record` when there is none. It is the reader of LAST resort: the\n // shared confirmation (`CommandExecution.confirmFound`) holds the row under\n // lock through the effect wherever the provider has one to take, and this\n // is what answers on a provider whose select assembly omits `FOR UPDATE`\n // (SQLite). The arms whose probe still locks are untouched.\n if (\n target.kind === \"choose\" &&\n target.found &&\n target.lookup.insertsWhenAbsent &&\n target.foundRequirement === undefined\n )\n target.found.command.fields.select(\n this.#commands.context.schema.keys(target.model)\n );\n if (target.kind === \"choose\" && target.found)\n target.fields.forward(target.found.command.fields);\n const origin =\n target.kind === \"choose\" ? target.lookup.origin : target.origin;\n const conditionalFound = conditionalParentBinding?.target.found;\n if (conditionalParentBinding && conditionalFound) {\n const { edge: reference, target: conditionalTarget } =\n conditionalParentBinding;\n conditionalFound.command.origin ??= conditionalTarget.lookup.origin;\n for (const pair of reference.pairs)\n conditionalFound.command.fields.absorb(\n pair.target,\n source.fields,\n pair.source,\n `Relation '${reference.name}' owns '${reference.pairs.map((member) => member.target).join(\", \")}'; omit it from nested create and update data.`\n );\n }\n const placement =\n edge.kind === \"reference\" && edge.owner === \"source\" ? \"before\" : \"after\";\n const occurrence = seriesMember\n ? this.#commands.occurrence(target, \"root\")\n : this.#commands.place(source, target, placement, origin);\n if (edge.kind === \"reference\" && edge.owner === \"source\") {\n const contribution = origin\n ? {\n origin,\n scope: edge.scope,\n identity: source.located?.facts,\n }\n : undefined;\n this.#commands.assignMembership(edge, source.fields, target.fields, {\n carried:\n premise && target.kind === \"choose\"\n ? target.found?.command.fields\n : undefined,\n requested:\n !premise ||\n (target.kind === \"choose\" && target.missing !== undefined),\n });\n if (contribution)\n this.#commands.publishMembership(\n occurrence,\n source.fields,\n contribution\n );\n return occurrence;\n }\n if (conditionalParentBinding && conditionalFound) {\n const { edge: reference } = conditionalParentBinding;\n const contribution = origin\n ? {\n origin,\n scope: reference.scope,\n identity: conditionalFound.command.located?.facts,\n }\n : undefined;\n this.#commands.assignMembership(\n reference,\n conditionalFound.command.fields,\n source.fields\n );\n if (contribution)\n this.#commands.publishMembership(\n occurrence,\n conditionalFound.command.fields,\n contribution\n );\n for (const pair of reference.pairs) source.fields.field(pair.source);\n }\n if (edge.kind === \"junction\" && !premise) {\n let captured: JunctionCapture | undefined;\n const address =\n edge.uniqueSide === \"source\"\n ? source.located\n : edge.uniqueSide === \"target\" && target.kind === \"choose\"\n ? target.lookup\n : undefined;\n if (address) {\n const side =\n edge.uniqueSide === \"source\" ? edge.sourceSide : edge.targetSide;\n captured = {\n kind: \"junction\",\n edge,\n address,\n final: edge.uniqueSide === \"source\" ? source.fields : target.fields,\n values: Object.fromEntries(\n side.members.map((pair) => [\n pair.junctionField,\n address.fields.field(pair.referencedField),\n ])\n ),\n };\n if (address !== source.located) this.#requireLookup(address);\n this.#requireLookup(captured);\n } else if (\n seriesMember &&\n edge.uniqueSide === \"target\" &&\n target.kind === \"record\" &&\n edge.targetSide.members.every(\n (pair) =>\n target.fields.known(pair.referencedField)?.kind === \"literal\"\n )\n ) {\n // A singular slot is a TRANSFER, and this member spells the target key\n // itself, so the current owner is addressed directly — the shipped\n // transfer's `values` address\n // (`write-engine/junction-singular-transfer.ts`). It is captured at\n // THIS member's own position, so a later member naming the same target\n // observes the membership this one already moved.\n captured = {\n kind: \"junction\",\n edge,\n final: target.fields,\n values: Object.fromEntries(\n edge.targetSide.members.map((pair) => [\n pair.junctionField,\n target.fields.field(pair.referencedField),\n ])\n ),\n };\n this.#commands.place(seriesMember, captured, \"before\");\n }\n const removals = source.body\n .map((candidate) => candidate.command)\n .filter(\n (command): command is Removal & { edge: Junction } =>\n command.kind === \"remove\" &&\n command.edge.kind === \"junction\" &&\n command.edge.table === edge.table\n );\n for (const removal of removals) {\n this.#linkFields(removal.edge, removal.source, removal.target);\n for (const retained of removal.keep)\n this.#linkFields(removal.edge, undefined, retained);\n }\n this.#commands.place(\n seriesMember ?? source,\n {\n kind: \"link\",\n edge,\n values: this.#linkFields(edge, source.fields, target.fields),\n captured,\n removals,\n origin,\n },\n \"after\",\n origin\n );\n } else if (\n edge.kind === \"junction\" &&\n target.kind === \"choose\" &&\n target.missing\n )\n this.#commands.place(\n target.missing.command,\n {\n kind: \"link\",\n edge,\n values: this.#linkFields(\n edge,\n source.fields,\n target.missing.command.fields\n ),\n origin,\n },\n \"after\",\n origin\n );\n return occurrence;\n }\n /**\n * The parent value a CORRELATED arm locates its target by, at the position\n * the arm's own lookup stands (N1: an observation is valid where it is\n * taken).\n *\n * A CHILD-HELD arm is placed AFTER the parent's write ({@link association}),\n * so the key valid there is the one that write left the row holding — under\n * a key transition the provider has already moved the child's foreign key\n * onto it (`ON UPDATE CASCADE`), and the pre-transition key names no member\n * at all. The parent's own `Assignments` are that answer at every point,\n * which is why a nested `update` placed BEFORE the write reads them too:\n * there they state what the payload names for the column, else the row the\n * parent located. An `upsert` on a PARENT-HELD edge cannot read them — its\n * create arm contributes the CHOSEN row's key into those same assignments\n * (`association` → `Commands.assignMembership`), so correlating on them\n * would make the arm's lookup wait on the value that lookup is what\n * produces, a read that depends on its own write, which no order satisfies\n * (N1). It reads the same two answers as its own view, taken before that\n * contribution exists, and forwards its demands so the located row still\n * projects what the view will read. A JUNCTION's membership is the captured\n * PAIR, which no SET of the parent's own columns moves.\n */\n #correlationParent(\n edge: Membership,\n verb: RelationVerb,\n final: Record<string, FieldValue>\n ): Assignments {\n const parent = this.#parent;\n const located = parent.located!.fields;\n if (edge.kind === \"junction\") return located;\n if (edge.owner !== \"source\" || verb === \"update\") return parent.fields;\n const view = new Assignments(parent.model, \"select\", {}, {}, located, [\n located,\n ]);\n for (const [field, value] of Object.entries(final))\n view.restate(field, value);\n return view;\n }\n #membershipSource(\n edge: Membership,\n source: Assignments\n ): Record<string, FieldValue> {\n return source.select(membershipFields(edge));\n }\n #linkFields(\n edge: Junction,\n source?: Assignments,\n target?: Assignments\n ): Record<string, FieldValue> {\n return junctionPairs(\n edge,\n (owner, field) => owner.field(field),\n source,\n target\n );\n }\n}\n","import {\n NestedWriteError,\n NotFoundError,\n TransactionError,\n UnsupportedOperationError,\n} from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport { createFailureError } from \"../../batch-error-attribution\";\nimport type { PreparedGuardFailure } from \"../../types\";\nimport type { OperationContext } from \"../shared/operation-context\";\nimport {\n InvalidScalarResult,\n type PreparedSelector,\n returningSafeProjection,\n type SelectorFacts,\n} from \"../shared/query\";\nimport {\n type ModelStamps,\n Parameter,\n type RowJudgement,\n type RowPurpose,\n} from \"../shared/row-scope\";\nimport { type Arguments, entries, type Input, record } from \"../shared/schema\";\nimport { type Membership, physicalField } from \"../shared/storage\";\nimport {\n Assignments,\n type FieldValue,\n type MembershipContribution,\n type Origin,\n} from \"./assignments\";\nimport { CommandExecution } from \"./execution\";\nimport { RelationBody } from \"./relation-body\";\nimport {\n type BoundMembership,\n type DeferredFailure,\n membershipFields,\n Selection,\n type SelectionSource,\n} from \"./selection\";\n\nexport { Selection } from \"./selection\";\n\n/** One operation's constructed physical form, and whether it may be one statement. */\nexport interface PhysicalPlan {\n /**\n * May this form reduce to ONE physical statement? It is an ADMISSIBILITY, not\n * a count: a form whose shape rules a single statement out (a locate-then-\n * mutate route, a per-row recoverable skip, a re-read after a non-RETURNING\n * write) answers `false` and opens its envelope immediately. Every other form\n * answers `true` and lets the construction itself state the count, at the one\n * place every provider round trip crosses (`OperationContext.dispatch`): a\n * second statement raises the envelope sentinel before any provider work and\n * the body is constructed again inside the region.\n */\n readonly single: boolean;\n run(): Promise<unknown>;\n}\n\n/** A bulk verb publishes rows only when the caller selected a shape. */\nfunction bulkProjection(\n context: OperationContext,\n model: AnyModel,\n args: Arguments\n) {\n return args.select\n ? context.queries.prepareProjection(model, { select: args.select })\n : undefined;\n}\n\ntype Reference = Extract<Membership, { kind: \"reference\" }>;\ntype Junction = Extract<Membership, { kind: \"junction\" }>;\n\nexport interface RecordCommand {\n kind: \"record\";\n model: AnyModel;\n fields: Assignments;\n body: CommandOccurrence[];\n transitions: Reference[];\n located?: Selection;\n requirement?: MembershipRequirement;\n operation?: string;\n origin?: Origin;\n suppression?: { readonly kind: \"skipDuplicate\" };\n}\nexport interface RecordSeriesCommand {\n readonly kind: \"series\";\n readonly records: CommandOccurrence<RecordCommand>[];\n}\nexport interface MembershipRequirement {\n readonly selection: Selection;\n readonly membership: BoundMembership;\n readonly failure: DeferredFailure;\n}\nexport interface JunctionCapture {\n readonly kind: \"junction\";\n readonly edge: Junction;\n /**\n * The located row this capture waits for. A capture whose junction values are\n * the member's OWN spelled key waits for nothing: it addresses the slot\n * directly, which is the shipped transfer's `values` address\n * (`write-engine/junction-singular-transfer.ts`, `JunctionTransferAddress`).\n */\n readonly address?: Selection;\n readonly values: Record<string, FieldValue>;\n readonly final: Assignments;\n}\nexport interface AbsenceRequirement {\n readonly kind: \"absent\";\n readonly model: AnyModel;\n readonly membership: BoundMembership;\n readonly excluding: Assignments[];\n readonly failure: DeferredFailure;\n /**\n * A tombstoning delete's referential requirement: only its candidates count,\n * and only while a visible member still references one. `except` names the\n * slot through which the parent keeps its own link, which does not block.\n * `lock` marks candidates no earlier locate holds (a set-oriented\n * `deleteMany`): an interactive session locks them first (DC14,\n * {@link Commands.unreferenced}).\n */\n readonly restrict?: {\n readonly candidates: PreparedSelector;\n readonly except?: string;\n readonly lock?: true;\n };\n}\nexport interface Condition {\n readonly lookup: Selection;\n readonly match: Error;\n readonly skip: Error;\n}\nexport interface Choose {\n kind: \"choose\";\n model: AnyModel;\n fields: Assignments;\n lookup: Selection;\n foundRequirement?: MembershipRequirement;\n operation?: string;\n missing?: CommandOccurrence<RecordCommand>;\n found?: CommandOccurrence<RecordCommand>;\n conditions?: {\n probes: Condition[];\n missingRow: Error;\n /**\n * The failure the found arm's ONE confirmation raises when it answers no\n * row (`CommandExecution.confirmFound`). That confirmation proves the\n * CONJUNCTION of the probes that matched, so what it loses is that single\n * premise: where several conditions were conjoined the sentence says a\n * MATCHED REQUIREMENT changed and names them as a SET, because a\n * conjunction has no first term to blame. With ONE condition the premise\n * IS that condition, and so is this ({@link Condition.match}).\n */\n matched: Error;\n };\n}\nexport interface Link {\n kind: \"link\";\n edge: Junction;\n values: Record<string, FieldValue>;\n captured?: JunctionCapture;\n removals?: (Removal & { edge: Junction })[];\n /** The mutation this link is an effect of (its placement's origin, kept). */\n origin?: Origin;\n}\nexport interface Removal {\n kind: \"remove\";\n edge: Membership;\n source?: Assignments;\n target?: Assignments;\n keep: Assignments[];\n /** The mutation this removal is an effect of (its placement's origin, kept). */\n origin?: Origin;\n}\nexport interface Deletion {\n kind: \"delete\";\n located: Selection;\n origin: Origin;\n /**\n * The admitted tombstone of a managed model, as scalar values: the row is\n * updated by its identity with these instead of removed, and keeps every\n * link.\n */\n values?: Input;\n}\n/**\n * One occurrence's tombstone data: as generated, and the scalar values update\n * admission and the call's stamps made of it (`Commands.stamp`), written as\n * they are.\n */\nexport interface TombstoneData {\n readonly raw: Input;\n readonly admitted: Input;\n}\n/**\n * The one sentence for a membership the plan observed and a race changed\n * (Arnaud's D-32): a member added to, or removed from, a captured set after\n * the plan-time read. Raceable — the unit aborts at the premise, which is\n * asserted where the observation was taken, before any write of the unit,\n * and the operation re-plans once from the admitted values against the set\n * the race produced.\n */\nexport function membershipRaceFailure(\n verb: string,\n edge: string,\n change: \"added\" | \"removed\"\n): NestedWriteError {\n const failure = new NestedWriteError(\n `Cannot ${verb} relation '${edge}': a member was ${change} after the plan-time read; retry to converge.`,\n edge\n );\n failure.meta.raceable = true;\n return failure;\n}\n/**\n * The one sentence for a nested read that depends on an earlier write of the\n * same nested write: `what` names that write, and `meta` follows the\n * operation key in the order each site states it.\n */\nfunction dependsOn(\n operation: string,\n relation: string,\n what: string,\n meta: Record<string, unknown>\n): NestedWriteError {\n return new NestedWriteError(\n `Nested operation '${operation}' on relation '${relation}' depends on an earlier ${what} in the same nested write. Split these operations into separate queries.`,\n relation,\n { meta: { operation, ...meta } }\n );\n}\n/**\n * A nested set mutation: the ONE correlated statement a nested\n * `updateMany`/`deleteMany` needs when its physical form expresses the whole\n * operation. The membership and the member filter are both predicates the\n * provider evaluates at this statement's own position in the body, so there is\n * no planning read to go stale, nothing to capture, and nothing for the\n * dependency analyser to refuse. It is a WRITE like any other, with the\n * unknown row-set footprint the shipped `appendTarget(\"updateMany\", unknown)`\n * registered, so a LATER read on the same model is still analysed against it.\n */\nexport interface SetMutation {\n readonly kind: \"set\";\n readonly edge: Membership;\n readonly parent: Assignments;\n readonly model: AnyModel;\n readonly selector: PreparedSelector;\n /** The admitted scalar assignments; absent names a `deleteMany`. */\n readonly values?: Input;\n readonly operation: \"updateMany\" | \"deleteMany\";\n readonly origin: Origin;\n}\nexport interface SelectedSeries {\n readonly selection: Selection;\n readonly analysis: RecordCommand | Deletion;\n readonly limit?: number;\n /**\n * A delete series carries the ORIGIN of the mutation that spelled it: the\n * member `captureSeries` builds for each captured row is a {@link Deletion},\n * whose origin is required, and the type says here what the one construction\n * site (`RelationBody`'s `deleteMany` arm) already supplies.\n */\n readonly mutation:\n | { readonly kind: \"update\"; readonly raw: Input }\n | {\n readonly kind: \"delete\";\n readonly origin: Origin;\n /** A managed target's generated data, re-admitted for every captured member. */\n readonly raw?: Input;\n };\n}\nexport type SelectedSeriesMember = RecordCommand | Deletion;\nexport interface SeriesOccurrence {\n readonly kind: \"selectedSeries\";\n readonly series: SelectedSeries;\n readonly template: CommandOccurrence<RecordCommand | Deletion>;\n}\nexport interface SeriesCapture {\n readonly kind: \"captureSeries\";\n readonly target: CommandOccurrence<SeriesOccurrence>;\n}\nexport interface MembershipMutation {\n readonly kind: \"membership\";\n}\nexport type Placement = \"root\" | \"before\" | \"capture\" | \"after\";\n\n/** A delete's candidates take their model's delete predicate (R3). */\nexport const DELETE_JUDGEMENT: RowJudgement = Object.freeze({\n verb: \"delete\",\n writes: Object.freeze([]),\n});\nexport interface CommandOccurrence<C extends Command = Command> {\n readonly kind: \"occurrence\";\n readonly command: C;\n /** Mutable for one reason: a dependent read moves to its execution point (N1). */\n placement: Placement;\n children: CommandOccurrence[];\n role?: \"found\" | \"missing\" | \"template\" | \"member\";\n captureTarget?: CommandOccurrence<SeriesOccurrence>;\n parent?: CommandOccurrence;\n dependencyRead?: DependencyRead;\n refusal?: Error;\n}\nexport interface MembershipPublication {\n readonly carrier: Assignments;\n readonly identity?: SelectorFacts;\n readonly contribution: MembershipContribution;\n}\nexport interface DependencyRead {\n readonly occurrence: CommandOccurrence;\n readonly lookup: Selection;\n readonly owner: CommandOccurrence<RecordCommand>;\n readonly membership?: BoundMembership;\n readonly target: boolean;\n}\ninterface DependencyWrite {\n readonly occurrence: CommandOccurrence;\n readonly command?: RecordCommand | Deletion | Link | Removal | SetMutation;\n readonly membership?: MembershipPublication;\n}\ninterface BranchPath {\n readonly parent?: BranchPath;\n readonly choice: CommandOccurrence;\n readonly arm: \"found\" | \"missing\";\n}\ninterface ReadVisit {\n readonly read: DependencyRead;\n readonly branch?: BranchPath;\n}\ninterface WriteVisit {\n readonly write: DependencyWrite;\n readonly branch?: BranchPath;\n}\ninterface SeriesRefusal {\n readonly error: Error;\n readonly member: SelectedSeriesMember;\n}\nexport type Command = (\n | RecordCommand\n | Selection\n | JunctionCapture\n | AbsenceRequirement\n | Choose\n | Link\n | Removal\n | Deletion\n | SetMutation\n | RecordSeriesCommand\n | SeriesCapture\n | SeriesOccurrence\n | MembershipMutation\n) & { membershipPublications?: MembershipPublication[] };\n\nexport function isRecordOccurrence(\n occurrence: CommandOccurrence\n): occurrence is CommandOccurrence<RecordCommand> {\n return occurrence.command.kind === \"record\";\n}\nexport function isSeriesOccurrence(\n occurrence: CommandOccurrence\n): occurrence is CommandOccurrence<SeriesOccurrence> {\n return occurrence.command.kind === \"selectedSeries\";\n}\n\n/**\n * The data of an update that only moves a membership (a `connect` or `set`\n * writing the row's foreign key). It refreshes generated update timestamps;\n * extension data defaults still belong to explicit create/update payloads.\n */\nexport const MEMBERSHIP_MOVE: Input = Object.freeze({});\n\n/** Construction owns branch order; every storage consumer names exact produced fields. */\nexport class Commands {\n #nextMutation = 0;\n readonly execution: CommandExecution;\n readonly context: OperationContext;\n constructor(context: OperationContext) {\n this.context = context;\n this.execution = new CommandExecution(this);\n }\n\n create(\n model: AnyModel,\n admitted: Input,\n raw: Input = admitted,\n incoming?: { edge: Reference; source: Assignments },\n operation = \"create\",\n deferred = false\n ): RecordCommand {\n const command: RecordCommand = {\n kind: \"record\",\n model,\n operation,\n body: [],\n transitions: [],\n fields: new Assignments(\n model,\n \"create\",\n this.stamp(model, \"create\", admitted, raw),\n raw,\n undefined,\n [],\n deferred\n ),\n };\n if (incoming)\n this.assignMembership(incoming.edge, command.fields, incoming.source);\n this.#relations(command, admitted, raw);\n return command;\n }\n update(\n located: Selection,\n admitted: Input,\n raw: Input,\n deferred = false,\n operation: \"update\" | \"upsert\" = \"update\"\n ): RecordCommand {\n const model = located.model;\n const command: RecordCommand = {\n kind: \"record\",\n model,\n located,\n body: [],\n transitions: [],\n fields: new Assignments(\n model,\n \"update\",\n admitted === MEMBERSHIP_MOVE\n ? this.context.schema.scalars(\n model,\n this.context.schema.update(model, {}, true)\n )\n : operation === \"upsert\" && Object.keys(raw).length === 0\n ? {}\n : this.stamp(model, \"update\", admitted, raw),\n raw,\n located.fields,\n undefined,\n deferred\n ),\n };\n for (const field of this.context.schema.keys(model))\n located.fields.field(field);\n this.#relations(command, admitted, raw);\n return command;\n }\n #relations(parent: RecordCommand, admitted: Input, raw: Input): void {\n for (const name of parent.model[\"~\"].relationNames) {\n if (admitted[name] === undefined) continue;\n new RelationBody(\n this,\n parent,\n this.context.schema.index.get(parent.model)!.get(name)!,\n record(admitted[name]),\n record(raw[name])\n ).expand();\n }\n }\n /**\n * What THIS occurrence of a delete of `model` writes instead of removing the\n * row: the declared constant data and the call's one instant, admitted once\n * through the model's update-data schema, which adds `updatedAt` and the set\n * envelopes, with the call's update stamp: a tombstone is an update.\n * `undefined` where the delete is physical: the model has no declaration,\n * or the call's controls chose to delete physically.\n */\n tombstone(model: AnyModel): TombstoneData | undefined {\n const scope = this.context.scope;\n const tombstone = scope?.rows.tombstones?.get(model[\"~\"].names.ts!);\n if (!(scope && tombstone)) return undefined;\n const raw =\n tombstone.at === undefined\n ? tombstone.assign\n : { ...tombstone.assign, [tombstone.at]: scope.instant() };\n return {\n raw,\n admitted: this.stamp(\n model,\n \"update\",\n this.context.schema.update(model, raw, true)\n ),\n };\n }\n /**\n * One occurrence's scalar values (`schema.scalars` of its admitted data)\n * with what the call's extensions write on every `kind` of `model`, put\n * under the occurrence's own. The caller's data (`raw`) wins a field it\n * writes, by name or through the relation whose foreign key on `model` holds\n * it (owner ruling, 2026-10-02): the extension writes nothing there, and that\n * relation decides the key. Only the fields kept are admitted, once per\n * occurrence per attempt, a create's through each field's create schema and\n * an update's through the model's update-data schema, as a tombstone is: a value the\n * caller replaced is never seen by the field's schema. A tombstone has no\n * caller data, so all of it is written.\n */\n stamp(\n model: AnyModel,\n kind: keyof ModelStamps,\n admitted: Input,\n raw: Input = {}\n ): Input {\n const name = model[\"~\"].names.ts!;\n const stamp = this.context.scope?.rows.stamps?.get(name)?.[kind];\n if (stamp === undefined)\n return this.context.schema.scalars(model, admitted);\n const written = new Set<string>();\n for (const [relation, { edge }] of this.context.schema.index.get(model)!) {\n if (raw[relation] === undefined || edge.kind !== \"foreignKey\") continue;\n if (edge.owner.source !== model || edge.owner.field !== relation)\n continue;\n for (const { foreignField } of edge.reference.members)\n written.add(foreignField);\n }\n const kept: Input = {};\n for (const [field, value] of Object.entries(stamp))\n if (raw[field] === undefined && !written.has(field))\n // `{ now: true }` writes the call's one instant (R7).\n kept[field] =\n value instanceof Parameter ? this.context.scope!.instant() : value;\n // A create's stamps are admitted as a create admits them: a field only a\n // create takes (an insert-only timestamp) is no update field.\n const values =\n kind === \"create\"\n ? this.context.schema.createValues(model, kept)\n : this.context.schema.update(model, kept, true);\n return this.context.schema.scalars(model, { ...admitted, ...values });\n }\n /**\n * What an update occurrence of `model` is judged at (R3): the fields the\n * caller's data writes on this row (`raw`, as the chain's request transforms\n * leave it, before any stamp or generated value), none where it emits an\n * UPDATE of stamps and generated values only. `undefined` where it emits no\n * UPDATE, an upsert's empty arm or a row only addressed to reach its\n * children, so it is only read; and where the call's domain judges `model`\n * by no verb. A scalar is written by name; a relation whose key this row\n * holds, with its key fields, by every verb but `update`; a join by every\n * verb but `update` and `updateMany`, since each changes this row's link\n * rows. A relation whose key the other row holds writes nothing here: its\n * rows are judged themselves.\n */\n judge(\n model: AnyModel,\n admitted: Input,\n raw: Input,\n operation: \"update\" | \"upsert\" = \"update\"\n ): RowJudgement | undefined {\n const name = model[\"~\"].names.ts!;\n const rows = this.context.scope?.rows;\n if (!rows?.domain.verbs?.has(name)) return undefined;\n const writes: string[] = [];\n const slots = this.context.schema.index.get(model)!;\n for (const [field, value] of Object.entries(raw)) {\n if (value === undefined) continue;\n const edge = slots.get(field)?.edge;\n if (edge === undefined) {\n writes.push(field);\n continue;\n }\n const verbs = Object.keys(record(value));\n if (edge.kind === \"junction\" || edge.kind === \"variantJunctionCarrier\") {\n if (verbs.some((verb) => verb !== \"update\" && verb !== \"updateMany\"))\n writes.push(field);\n } else if (verbs.some((verb) => verb !== \"update\")) {\n const holder = edge.kind === \"foreignKey\" ? edge.owner : edge.carrier;\n if (holder.source !== model || holder.field !== field) continue;\n writes.push(field);\n if (edge.kind === \"foreignKey\")\n for (const { foreignField } of edge.reference.members)\n writes.push(foreignField);\n }\n }\n if (writes.length > 0) {\n const tombstone = rows.tombstones?.get(name);\n const marks =\n tombstone !== undefined &&\n writes.some(\n (field) =>\n field === tombstone.at || Object.hasOwn(tombstone.assign, field)\n );\n return marks\n ? { verb: \"update\", writes, marks: true }\n : { verb: \"update\", writes };\n }\n const stamped =\n Object.keys(rows.stamps?.get(name)?.update ?? {}).length > 0 ||\n model[\"~\"].scalarFieldNames.some(\n (field) => admitted[field] !== undefined\n );\n return stamped && (operation === \"update\" || Object.keys(raw).length > 0)\n ? { verb: \"update\", writes }\n : undefined;\n }\n /**\n * A write's candidates: the caller's selector AND the call's domain for\n * `purpose` under the write's `judgement`, AND, for a tombstone, the model's\n * default domain — once when the call's controls select the default. The\n * selector's unique key is kept.\n */\n candidates(\n selector: PreparedSelector,\n purpose: RowPurpose,\n tombstone: boolean,\n judgement?: RowJudgement\n ): PreparedSelector {\n const scope = this.context.scope;\n const queries = this.context.queries;\n const candidates = queries.candidates(\n selector,\n purpose,\n undefined,\n judgement\n );\n return tombstone && scope && scope.defaults !== scope.domain\n ? queries.candidates(candidates, purpose, scope.defaults)\n : candidates;\n }\n /**\n * The candidates a tombstoning delete may not take: those a member in its\n * model's default domain still references through a slot whose foreign key\n * restricts deletes, as the database refuses a hard delete of them.\n * `undefined` when no slot restricts.\n */\n blocked(\n candidates: PreparedSelector,\n except?: { readonly slot: string; readonly identity: Input }\n ): PreparedSelector | undefined {\n const model = candidates.model;\n const slots = this.context.schema.restrictingSlots(model);\n if (slots.length === 0) return undefined;\n const queries = this.context.queries;\n return queries.andSelectors(model, [\n candidates,\n queries.referenced(model, slots, this.context.scope?.defaults, except),\n ]);\n }\n /**\n * The refusal a restricting foreign key gives a hard delete, stated by core\n * under the context's attribution, as the database's own error carries it:\n * declared for a packaged premise, and built by the same construction.\n */\n restriction(model: AnyModel): PreparedGuardFailure {\n return {\n kind: \"foreignKey\",\n message: `Cannot delete '${model[\"~\"].names.ts!}' record: a related record still references it through one of its relations whose foreign key restricts deletes: ${this.context.schema\n .restrictingSlots(model)\n .map((slot) => `'${slot}'`)\n .join(\", \")}.`,\n raceable: false,\n };\n }\n restrictFailure(model: AnyModel): DeferredFailure {\n const failure = this.restriction(model);\n return () =>\n createFailureError(failure, model[\"~\"].names.ts!, this.context.operation);\n }\n createOrigin(relation: string, operation: string, slot = relation): Origin {\n return { relation, operation, slot, order: this.#nextMutation++ };\n }\n occurrence<C extends Command>(\n command: C,\n placement: Placement = \"root\"\n ): CommandOccurrence<C> {\n const occurrence: CommandOccurrence<C> = {\n kind: \"occurrence\",\n command,\n placement,\n children: [],\n };\n return occurrence;\n }\n place<C extends Command>(\n parent: RecordCommand,\n command: C,\n placement: Exclude<Placement, \"root\">,\n origin = this.#origin(command)\n ): CommandOccurrence<C> {\n const occurrence = this.occurrence(command, placement);\n const semanticOrder = origin?.order ?? -1;\n const placementOrder = (value: Placement) =>\n value === \"before\" ? 0 : value === \"capture\" ? 1 : 2;\n const following = parent.body.findIndex((candidate) => {\n const candidateOrder = this.#origin(candidate.command)?.order ?? -1;\n return (\n candidateOrder > semanticOrder ||\n (candidateOrder === semanticOrder &&\n placementOrder(candidate.placement) > placementOrder(placement))\n );\n });\n parent.body.splice(\n following < 0 ? parent.body.length : following,\n 0,\n occurrence\n );\n return occurrence;\n }\n #recipeChildren(command: Command): readonly CommandOccurrence[] {\n if (command.kind === \"record\") return command.body;\n if (command.kind === \"choose\")\n return [command.found, command.missing].filter(\n (arm): arm is CommandOccurrence<RecordCommand> => arm !== undefined\n );\n if (command.kind === \"series\") return command.records;\n if (command.kind === \"selectedSeries\") return [command.template];\n return [];\n }\n #materializePlacement(occurrence: CommandOccurrence): void {\n const role = (\n parent: Command,\n child: CommandOccurrence\n ): CommandOccurrence[\"role\"] => {\n if (parent.kind === \"choose\")\n return child === parent.found ? \"found\" : \"missing\";\n if (parent.kind === \"selectedSeries\") return \"template\";\n return undefined;\n };\n const sources = this.#recipeChildren(occurrence.command);\n const replacements = new Map<CommandOccurrence, CommandOccurrence>();\n occurrence.children = sources.map((source) => {\n const replacement = this.occurrence(source.command, source.placement);\n replacement.role = role(occurrence.command, source);\n replacements.set(source, replacement);\n return replacement;\n });\n for (const [source, replacement] of replacements) {\n if (source.command.kind === \"captureSeries\") {\n const resolved = replacements.get(source.command.target);\n // Established upstream: `requireSeriesCapture` places a capture in the\n // SAME body as the series it names, so the target is one of this\n // parent's recipe children and has a replacement here; and a\n // replacement carries its source's COMMAND, so it keeps the kind\n // `SeriesCapture.target` already states.\n replacement.captureTarget =\n resolved as CommandOccurrence<SeriesOccurrence>;\n }\n }\n for (const child of occurrence.children) this.#materializePlacement(child);\n }\n #origin(command: Command): Origin | undefined {\n if (command.kind === \"choose\") return command.lookup.origin;\n if (command.kind === \"captureSeries\")\n return command.target.command.series.selection.origin;\n if (command.kind === \"selectedSeries\")\n return command.series.selection.origin;\n if (command.kind === \"junction\") return command.address?.origin;\n if (\n command.kind === \"record\" ||\n command.kind === \"delete\" ||\n command.kind === \"set\" ||\n command.kind === \"lookup\" ||\n command.kind === \"link\" ||\n command.kind === \"remove\"\n )\n return command.origin;\n return undefined;\n }\n /**\n * Where a membership's value is BOUND into the row that carries it, as the\n * two things that row can do with it.\n *\n * It REQUESTS the value when its own statement must point it at the target:\n * a fresh or rebound row, and a correlated choice's missing arm, which\n * creates a row only that statement can point this one at.\n *\n * It HOLDS the value when it rides on `carried`, the arm's own write: a\n * CORRELATED arm's target is the row this row's membership names, so a\n * write of the referenced key moves this row with it (`ON UPDATE CASCADE`)\n * before this row's own statement runs ({@link Assignments.hold}). A\n * SUPPLIER earlier in the same body — `connect` and its kin run before\n * `update` and `upsert` — names a different row, and then it is this row's\n * own statement that moves it and the key it was located by that addresses\n * it.\n */\n assignMembership(\n edge: Reference,\n destination: Assignments,\n producer: Assignments,\n binding: {\n readonly carried?: Assignments;\n readonly requested?: boolean;\n } = {}\n ): void {\n for (const pair of edge.pairs) {\n const field = edge.owner === \"source\" ? pair.source : pair.target;\n const referenced = edge.owner === \"source\" ? pair.target : pair.source;\n // What the consumer needs is that the producer's create SUPPLIES this\n // referenced field, not that its value is a construction-time literal.\n // A sibling `connect` on the producer supplies it from the row it\n // locates, and `known` is undefined there BY CONTRACT — the located\n // bytes are what the column holds, never the selector's literal, which\n // a case-insensitive collation can differ from — so a knowability test\n // spelled as `known` refuses a shape whose value is fixed before the\n // consumer's INSERT: the consumer reads it from the producer at its own\n // execution point, behind the lookup and behind the producer's write.\n // An explicit NULL supplies nothing, and a field the payload never\n // writes is the shape the sentence names.\n const known = producer.known(referenced);\n if (\n producer.operation === \"create\" &&\n (!producer.writesField(referenced) ||\n (known?.kind === \"literal\" && known.value === null))\n ) {\n const scalar = physicalField(\n this.context.schema,\n producer.model,\n referenced\n ).scalar[\"~\"].state;\n if (!scalar.autoGenerate)\n destination.reject(\n new UnsupportedOperationError(\n `Cannot create relation '${edge.name}': referenced field '${referenced}' must be supplied by the parent record or generated by the database.`\n )\n );\n }\n // The one place the resolved edge is read, so the one place that can\n // say what this written component has to be able to REPRESENT: the\n // relation travels with the value, and the requirement is asked where\n // the value is known ({@link CommandExecution.stored}).\n const value: FieldValue = {\n ...producer.field(referenced),\n relation: edge.name,\n };\n if (\n binding.carried?.writesField(referenced) &&\n !destination.writesField(field)\n )\n destination.hold(field, value, binding.carried);\n if (binding.requested !== false)\n destination.contribute(\n field,\n value,\n `${destination.operation} assigns conflicting values to column '${this.context.queries.columnName(destination.model, field)}' through relation '${edge.name}'.`\n );\n }\n if (edge.discriminator && binding.requested !== false)\n destination.contribute(\n edge.discriminator.field,\n { kind: \"literal\", value: edge.discriminator.value },\n `Conflicting stored discriminator for relation '${edge.name}'.`\n );\n }\n publishMembership(\n owner: CommandOccurrence,\n carrier: Assignments,\n contribution: MembershipContribution\n ): void {\n (owner.command.membershipPublications ??= []).push({\n carrier,\n identity: contribution.identity,\n contribution,\n });\n }\n analyze<C extends RecordCommand | SeriesOccurrence | Choose>(\n command: C\n ): CommandOccurrence<C> {\n const occurrence = this.occurrence(command);\n this.#materializePlacement(occurrence);\n this.#bindTree(occurrence);\n this.#analyzeOccurrence(occurrence);\n return occurrence;\n }\n analyzeSeries(series: SelectedSeries): CommandOccurrence<SeriesOccurrence> {\n return this.analyze(this.selectedSeries(series));\n }\n selectedSeries(series: SelectedSeries): SeriesOccurrence {\n return {\n kind: \"selectedSeries\",\n series,\n template: this.occurrence(series.analysis),\n };\n }\n membershipPublications(\n occurrence: CommandOccurrence\n ): readonly MembershipPublication[] {\n return occurrence.command.membershipPublications ?? [];\n }\n choiceArm(\n occurrence: CommandOccurrence,\n arm: \"found\" | \"missing\"\n ): CommandOccurrence<RecordCommand> | undefined {\n if (occurrence.command.kind !== \"choose\") return undefined;\n const child = occurrence.children.find(\n (candidate) => candidate.role === arm\n );\n return child && isRecordOccurrence(child) ? child : undefined;\n }\n seriesMembers(\n occurrence: CommandOccurrence<SeriesOccurrence>\n ): CommandOccurrence<RecordCommand | Deletion>[] {\n return occurrence.children.filter(\n (child): child is CommandOccurrence<RecordCommand | Deletion> =>\n child.role === \"member\" &&\n (child.command.kind === \"record\" || child.command.kind === \"delete\")\n );\n }\n seriesCaptureTarget(\n occurrence: CommandOccurrence\n ): CommandOccurrence<SeriesOccurrence> {\n // Two facts an earlier owner established: the kind, by the one caller's\n // `case \"captureSeries\"` arm (`CommandExecution.run`), and the target, by\n // `materializePlacement`, which resolves every capture's target before\n // `analyze`/`analyzeSeries` returns the tree this reads.\n return occurrence.captureTarget!;\n }\n #readMembership(write: DependencyWrite, read: DependencyRead): void {\n const { lookup, owner } = read;\n const membership = read.membership ?? lookup.membership();\n if (!(lookup.origin && membership)) return;\n // A membership is read through fields — the member side's foreign key,\n // the parent side's referenced key — and a record write of either, on the\n // member model or by the parent itself (a key transition, a self-held\n // foreign key), changes what the read observes: an ordered observation\n // (N1). The selector overlap `readTarget` computes does not see these\n // fields, because a membership is not part of the selector. A CREATE whose\n // known literal for a member-side field cannot be this parent's key —\n // another parent's key, or null — makes no member of this parent and is\n // disjoint; an UPDATE of a member-side key may take a member OUT of the\n // membership, so it is observed whatever it writes.\n const command = write.command;\n if (\n command?.kind === \"record\" &&\n (command.fields.operation === \"create\" ||\n command.fields.writtenFields().length > 0)\n ) {\n const edge = membership.edge;\n const parentKey = (field: string): unknown => {\n const stated = membership.parent.known(field);\n if (stated?.kind === \"literal\") return stated.value;\n return membership.parent === owner.command.fields\n ? owner.command.located?.facts.equals.get(field)\n : undefined;\n };\n const literal = (field: string) =>\n this.#literalOf(command, field, write.occurrence);\n let touchesMember = false;\n let disjoint = false;\n if (edge.kind === \"reference\" && edge.owner === \"target\") {\n for (const pair of edge.pairs) {\n if (!command.fields.writesField(pair.target)) continue;\n touchesMember = true;\n if (command.fields.operation !== \"create\") continue;\n const value = literal(pair.target);\n const key = parentKey(pair.source);\n if (\n value !== undefined &&\n (value.value === null ||\n (key !== undefined && !Object.is(value.value, key)))\n )\n disjoint = true;\n }\n const discriminator = edge.discriminator;\n if (\n discriminator?.side === \"target\" &&\n command.fields.writesField(discriminator.field)\n ) {\n touchesMember = true;\n if (command.fields.operation === \"create\") {\n const value = literal(discriminator.field);\n if (value !== undefined && value.value !== discriminator.value)\n disjoint = true;\n }\n }\n }\n const written =\n (command.model === edge.target && touchesMember && !disjoint) ||\n (command.fields === membership.parent &&\n membershipFields(edge).some((field) =>\n command.fields.writesField(field)\n ));\n if (written) {\n const origin = lookup.origin;\n const earlier = command.origin?.operation ?? command.fields.operation;\n this.#depend(write, read, () =>\n dependsOn(\n origin.operation,\n origin.relation,\n `'${earlier}' membership write`,\n {\n conflictsWith: earlier,\n dependency: \"membership\",\n overlap: \"unknown\",\n }\n )\n );\n return;\n }\n }\n if (membership.edge.kind === \"junction\") {\n // A junction membership changes under any link, removal or member set\n // of the same junction table, whichever side or parent wrote it (a\n // self-referential inverse is the same rows): the read is an ordered\n // observation of it (N1). The overlap is not computed finer than the\n // table — an observation costs a placement, not a refusal.\n const command = write.command;\n const table = membership.edge.table;\n const touches =\n (command?.kind === \"link\" ||\n command?.kind === \"remove\" ||\n command?.kind === \"set\") &&\n command.edge.kind === \"junction\" &&\n command.edge.table === table;\n if (!touches) return;\n const origin = lookup.origin;\n this.#depend(write, read, () =>\n dependsOn(origin.operation, origin.relation, \"membership write\", {\n dependency: \"membership\",\n overlap: \"unknown\",\n })\n );\n return;\n }\n const edge = membership.edge;\n const carrier = edge.owner === \"source\" ? edge.source : edge.target;\n const observed =\n edge.owner === \"source\" ? owner.command.located?.facts : lookup.facts;\n const publication = write.membership;\n if (!publication) return;\n const relation = lookup.origin.slot ?? lookup.origin.relation;\n const operation = lookup.origin.operation;\n const dependency = (earlier: string) =>\n dependsOn(operation, relation, `'${earlier}' membership write`, {\n conflictsWith: earlier,\n relation,\n });\n // The same read, and the other side of it: a membership read THROUGH a\n // field an earlier arm already MOVED on this parent — the arm's target\n // update carried this row's own foreign key with it, so the key the read\n // was planned with names no member at all ({@link Assignments.hold}). The\n // record-write case above says this for a parent that WRITES the field\n // itself; a correlated arm's parent does not write it, the provider does.\n if (\n publication.carrier === membership.parent &&\n membershipFields(edge).some((field) =>\n publication.carrier.movesField(field)\n )\n ) {\n this.#depend(write, read, () =>\n dependency(publication.contribution.origin.operation)\n );\n return;\n }\n if (publication.carrier.model !== carrier) return;\n const contribution = publication.contribution;\n const ownerDiffers = write.occurrence.command !== lookup;\n if (!ownerDiffers) return;\n const sameEdge = contribution.scope.edge === edge.scope.edge;\n if (!sameEdge) return;\n const sameMember =\n contribution.scope.member === undefined ||\n contribution.scope.member === edge.scope.member;\n if (!sameMember) return;\n const identity = publication.identity;\n let disjoint = false;\n if (observed && identity)\n for (const [key, value] of observed.equals) {\n const conflicts =\n !publication.carrier.writesField(key) &&\n identity.equals.has(key) &&\n !Object.is(identity.equals.get(key), value);\n if (conflicts) {\n disjoint = true;\n break;\n }\n }\n if (disjoint) return;\n this.#depend(write, read, () => dependency(contribution.origin.operation));\n }\n #readTarget(write: DependencyWrite, read: DependencyRead): void {\n const { lookup } = read;\n if (\n !lookup.origin ||\n lookup.membershipOnly ||\n lookup.source.kind === \"producer\"\n )\n return;\n const scopes = [\n {\n model: lookup.model,\n path: [],\n fields: lookup.facts.fields,\n equals: lookup.facts.equals,\n exact: lookup.facts.exact,\n },\n ...lookup.facts.reads,\n ];\n const mutation = write.command;\n if (!mutation) return;\n for (const scope of scopes) {\n if (mutation.kind === \"link\" || mutation.kind === \"remove\") {\n const observed = scope.path.at(-1);\n const sameEdge =\n observed !== undefined &&\n observed.scope.edge === mutation.edge.scope.edge;\n if (!sameEdge) continue;\n const origin = lookup.origin;\n this.#depend(write, read, () =>\n dependsOn(origin.operation, origin.relation, \"membership write\", {\n conflictsWith: mutation.kind === \"link\" ? \"connect\" : \"disconnect\",\n dependency: \"membership\",\n overlap: \"unknown\",\n })\n );\n return;\n }\n const model =\n mutation.kind === \"delete\" ? mutation.located.model : mutation.model;\n if (model !== scope.model) continue;\n // A set mutation names no row it wrote — the shipped footprint is\n // `unknownConstraint` (`OwnWriteSteps.ts:186-191`) — so it has no located\n // row to prove a later read of the same model disjoint from it.\n const located = mutation.kind === \"set\" ? undefined : mutation.located;\n if (\n mutation.kind === \"record\" &&\n mutation.fields.operation !== \"create\" &&\n !mutation.located?.membership()?.edge.many\n ) {\n let hasWrittenOverlap = false;\n for (const field of mutation.fields.writtenFields()) {\n hasWrittenOverlap = scope.fields.has(field);\n if (hasWrittenOverlap) break;\n }\n if (!hasWrittenOverlap) continue;\n }\n let matched = 0;\n let disjoint = false;\n for (const [field, expected] of scope.equals) {\n const value =\n mutation.kind === \"record\" && mutation.fields.operation === \"create\"\n ? mutation.fields.known(field)\n : undefined;\n const selected =\n located?.facts.exact &&\n !(mutation.kind === \"record\" && mutation.fields.writesField(field))\n ? located\n : undefined;\n const known =\n value?.kind === \"literal\"\n ? value.value\n : selected?.facts.equals.get(field);\n const hasKnown =\n value?.kind === \"literal\" || selected?.facts.equals.has(field);\n if (!(hasKnown && scope.exact)) continue;\n const equal = Object.is(known, expected);\n if (!equal) {\n disjoint = true;\n break;\n }\n matched++;\n }\n if (disjoint) continue;\n const origin = lookup.origin;\n const operation =\n mutation.kind === \"set\"\n ? mutation.operation\n : (mutation.origin?.operation ??\n (mutation.kind === \"delete\"\n ? \"delete\"\n : mutation.fields.operation));\n this.#depend(write, read, () =>\n dependsOn(\n origin.operation,\n origin.relation,\n `'${operation}' target write`,\n {\n conflictsWith: operation,\n dependency: \"targetExistence\",\n overlap:\n scope.exact && matched > 0 && matched === scope.fields.size\n ? \"equal\"\n : \"unknown\",\n }\n )\n );\n return;\n }\n }\n /**\n * A read whose answer an earlier write of this operation can change is an\n * ORDERED OBSERVATION (N1, the nesting plan §1): it is taken at its execution\n * point, after that write. The dependency pass keeps computing the overlap\n * fact and spends it on placement, not on a refusal.\n *\n * The write's and the read's execution points are the two children of their\n * nearest common ancestor on each path (the ancestor's OWN write when the\n * write is the ancestor's, or a membership the ancestor's fields carry), in\n * the run order of {@link CommandExecution.run}: the `before` children, the\n * ancestor's write, the captures, the `after` children, each in body order.\n * A read that already follows its write is only marked {@link Selection.dependent}\n * (the batch route reads it through the barrier). A read that would run first\n * — a `before` lookup, a capture, a parent-held choice whose subtree reads\n * what the parent's own write changes — moves to the `after` phase, to its\n * consumer's execution point: behind the write, ahead of its own mutation's\n * first effect. The one shape no order satisfies is a read the ancestor's\n * own write CONSUMES (a parent-held target's key), which keeps the inherited\n * refusal — the sentence names exactly that: an earlier write the read cannot\n * follow. The other limit is the ancestor's own EXECUTION POSITION: a\n * placement IS a position in `ancestor.children`, so it may change only\n * while that ancestor has not begun dispatching them\n * ({@link CommandExecution.started}). A series expands its members from the\n * admitted payload WHILE the operation runs (`expandSeries`), and each\n * member is a FRESH subtree whose ancestor has not started: its observations\n * are placed like any other (FC-01 — the operation-global \"once members are\n * expanded nothing moves\" veto refused under `updateMany` what `update`\n * executes). The limit covers the pairs an expansion makes against the\n * tree AROUND the series: the per-member analysis walks past the series to\n * the enclosing record's own write and to the siblings ahead of it, and the\n * second pass pairs a member's writes with the reads FOLLOWING the series —\n * in either the consumer may sit in a phase the enclosing record has\n * already run. In the shipped shapes that pair was already judged\n * against the template's identical write at `analyze` time, so the reader\n * moved before anything ran and this limit is not reached; it holds the\n * line if a member ever carries a write the template does not, because\n * re-placing a child of a record that is dispatching its children would\n * reorder a schedule that is already being consumed.\n */\n #depend(\n write: DependencyWrite,\n read: DependencyRead,\n refusal: () => NestedWriteError\n ): void {\n const owner = read.owner;\n // A mutation's own effects are placed behind its read by construction: a\n // junction delete's link removal, a set's clear. They are not what the\n // read depends on.\n const writeOrigin = write.command\n ? this.#origin(write.command)\n : write.membership?.contribution.origin;\n if (\n writeOrigin !== undefined &&\n writeOrigin.order === read.lookup.origin?.order\n )\n return;\n const readPath = new Map<\n CommandOccurrence,\n CommandOccurrence | undefined\n >();\n for (\n let node: CommandOccurrence | undefined = this.#reader(read),\n child: CommandOccurrence | undefined;\n node;\n child = node, node = node.parent\n )\n readPath.set(node, child);\n // A membership contribution executes with the record whose own write\n // carries it, wherever its publisher stands (a parent-held choice\n // publishes the parent's key for the parent's UPDATE).\n let writeAt = write.occurrence;\n if (write.membership)\n for (\n let node: CommandOccurrence | undefined = write.occurrence;\n node;\n node = node.parent\n )\n if (\n isRecordOccurrence(node) &&\n node.command.fields === write.membership.carrier\n ) {\n writeAt = node;\n break;\n }\n // `bindTree` hangs every occurrence from the operation's one root, which\n // `reader` put on the read's path, so the walk meets the path at the root\n // at the latest (N4: an invariant of the tree, not a refusal).\n let ancestor: CommandOccurrence = writeAt;\n let producer: CommandOccurrence | undefined;\n while (!readPath.has(ancestor)) {\n producer = ancestor;\n ancestor = ancestor.parent!;\n }\n // The pairing walk (`visitPrecedingWrites`) hands `depend` only a write\n // that PRECEDES the read — an ancestor's own write, or one in a sibling\n // ahead of the read's occurrence — never one inside the read's own\n // occurrence, and the early lookup or capture `reader` may stand on is a\n // leaf; so the meeting point is a proper ancestor of the reader and the\n // path records the child it came through.\n const consumer = readPath.get(ancestor)!;\n const follows = producer\n ? this.#runsBefore(producer, consumer, ancestor)\n : consumer.placement !== \"before\";\n if (!follows) {\n const consumed =\n isRecordOccurrence(ancestor) &&\n (ancestor.command.fields.consumes(read.lookup.fields) ||\n (consumer.command.kind === \"choose\" &&\n ancestor.command.fields.consumes(consumer.command.fields)));\n if (consumed || this.execution.started(ancestor)) {\n owner.refusal ??= refusal();\n return;\n }\n // At its consumer's execution point: behind the write (behind the\n // ancestor's own write when that is the write), ahead of the first\n // `after` effect of its own or a later mutation — every effect carries\n // its mutation's origin, so the reader lands behind the whole mutation\n // of the write it depends on and ahead of the first effect that may\n // consume it.\n const children = ancestor.children;\n children.splice(children.indexOf(consumer), 1);\n consumer.placement = \"after\";\n const own = this.#origin(consumer.command)?.order;\n const producerIndex = producer ? children.indexOf(producer) : -1;\n const landing = children.findIndex((candidate, index) => {\n if (index <= producerIndex || candidate.placement !== \"after\")\n return false;\n const order = this.#origin(candidate.command)?.order;\n return own !== undefined && order !== undefined && order >= own;\n });\n children.splice(\n landing < 0\n ? producer\n ? producerIndex + 1\n : children.length\n : landing,\n 0,\n consumer\n );\n }\n read.lookup.dependent = true;\n }\n /**\n * The literal a record write states for `field`, following a value taken\n * from another record's field (a nested create's foreign key from its\n * parent) to that record's known or located identity in the tree.\n */\n #literalOf(\n command: RecordCommand,\n field: string,\n occurrence: CommandOccurrence\n ): { readonly value: unknown } | undefined {\n const stated = command.fields.known(field);\n if (stated?.kind === \"literal\") return { value: stated.value };\n const assignment = command.fields.stated(field);\n if (assignment?.kind !== \"field\") return undefined;\n for (\n let node: CommandOccurrence | undefined = occurrence;\n node;\n node = node.parent\n ) {\n if (\n !isRecordOccurrence(node) ||\n node.command.fields !== assignment.producer\n )\n continue;\n const known = node.command.fields.known(assignment.field);\n if (known?.kind === \"literal\") return { value: known.value };\n const located = node.command.located?.facts;\n if (located?.exact && located.equals.has(assignment.field))\n return { value: located.equals.get(assignment.field) };\n return undefined;\n }\n return undefined;\n }\n /** The occurrence that RUNS a dependency read: its early lookup or capture when one is placed, else the read's own. */\n #reader(read: DependencyRead): CommandOccurrence {\n const owner = read.owner;\n const early = owner.children.find(\n (child) =>\n child.command === read.lookup || child.captureTarget === read.occurrence\n );\n return early ?? read.occurrence;\n }\n #runsBefore(\n first: CommandOccurrence,\n second: CommandOccurrence,\n parent: CommandOccurrence\n ): boolean {\n const phase = (occurrence: CommandOccurrence) =>\n occurrence.placement === \"before\"\n ? 0\n : occurrence.placement === \"capture\"\n ? 1\n : 2;\n return (\n phase(first) < phase(second) ||\n (phase(first) === phase(second) &&\n parent.children.indexOf(first) < parent.children.indexOf(second))\n );\n }\n #bindTree(occurrence: CommandOccurrence, parent?: CommandOccurrence): void {\n occurrence.parent = parent;\n occurrence.dependencyRead ??= this.#dependencyRead(occurrence);\n for (const child of occurrence.children) this.#bindTree(child, occurrence);\n }\n #dependencyRead(occurrence: CommandOccurrence): DependencyRead | undefined {\n const command = occurrence.command;\n const owner = isSeriesOccurrence(occurrence)\n ? this.#seriesOwner(occurrence)\n : this.#recordOwner(occurrence);\n if (!owner) return undefined;\n if (command.kind === \"choose\")\n return {\n occurrence,\n lookup: command.lookup,\n owner,\n membership: command.foundRequirement?.membership,\n target: true,\n };\n if (command.kind === \"delete\")\n return {\n occurrence,\n lookup: command.located,\n owner,\n target: true,\n };\n if (command.kind === \"selectedSeries\")\n return {\n occurrence,\n lookup: command.series.selection,\n owner,\n target: true,\n };\n return undefined;\n }\n #recordOwner(\n occurrence: CommandOccurrence\n ): CommandOccurrence<RecordCommand> | undefined {\n let candidate = occurrence.parent;\n while (candidate) {\n if (isRecordOccurrence(candidate)) return candidate;\n candidate = candidate.parent;\n }\n return undefined;\n }\n #seriesOwner(\n occurrence: CommandOccurrence<SeriesOccurrence>\n ): CommandOccurrence<RecordCommand> | undefined {\n const owner = this.#recordOwner(occurrence);\n if (owner) return owner;\n const template = occurrence.children.find(\n (child) => child.role === \"template\"\n );\n return template && isRecordOccurrence(template) ? template : undefined;\n }\n #compatible(left?: BranchPath, right?: BranchPath): boolean {\n for (let a = left; a; a = a.parent)\n for (let b = right; b; b = b.parent)\n if (a.choice === b.choice && a.arm !== b.arm) return false;\n return true;\n }\n #visitDirectWrites(\n occurrence: CommandOccurrence,\n visit: (write: WriteVisit) => void,\n branch?: BranchPath\n ): void {\n const command = occurrence.command;\n if (\n (command.kind === \"record\" &&\n (command.fields.operation === \"create\" ||\n command.fields.writtenFields().length)) ||\n command.kind === \"delete\" ||\n command.kind === \"set\" ||\n command.kind === \"link\" ||\n command.kind === \"remove\"\n ) {\n const write = { occurrence, command };\n visit({ write, branch });\n }\n for (const membership of this.membershipPublications(occurrence)) {\n const write = { occurrence, membership };\n visit({ write, branch });\n }\n }\n #childBranch(\n parent: CommandOccurrence,\n child: CommandOccurrence,\n branch: BranchPath | undefined\n ): BranchPath | undefined {\n return parent.command.kind === \"choose\"\n ? {\n parent: branch,\n choice: parent,\n arm: child.role === \"found\" ? \"found\" : \"missing\",\n }\n : branch;\n }\n #visitWrites(\n occurrence: CommandOccurrence,\n visit: (write: WriteVisit) => void,\n branch: BranchPath | undefined\n ): void {\n this.#visitDirectWrites(occurrence, visit, branch);\n for (const child of occurrence.children)\n this.#visitWrites(\n child,\n visit,\n this.#childBranch(occurrence, child, branch)\n );\n }\n #visitReads(\n occurrence: CommandOccurrence,\n visit: (read: ReadVisit) => \"stop\" | void,\n branch: BranchPath | undefined\n ): boolean {\n const read = occurrence.dependencyRead;\n if (read) {\n const readVisit = { read, branch };\n if (visit(readVisit) === \"stop\") return true;\n }\n for (const child of occurrence.children)\n if (\n this.#visitReads(\n child,\n visit,\n this.#childBranch(occurrence, child, branch)\n )\n )\n return true;\n return false;\n }\n #visitPrecedingWrites(\n target: CommandOccurrence,\n visit: (write: WriteVisit) => void,\n branch: BranchPath | undefined\n ): void {\n const parent = target.parent;\n if (!parent) return;\n const parentBranch =\n parent.command.kind === \"choose\" ? branch?.parent : branch;\n this.#visitPrecedingWrites(parent, visit, parentBranch);\n this.#visitDirectWrites(parent, visit, parentBranch);\n if (parent.command.kind === \"choose\") return;\n if (this.#isSeriesMember(parent, target)) return;\n // `bindTree` sets `parent` while walking that parent's own `children`, so\n // a target with a parent is one of them and the loop returns at it.\n for (const sibling of parent.children) {\n if (sibling === target) return;\n this.#visitWrites(sibling, visit, parentBranch);\n }\n }\n #analyzeRead(occurrence: CommandOccurrence): void {\n const read = occurrence.dependencyRead;\n if (!read) return;\n const branch = this.#branchOf(occurrence);\n const readVisit = { read, branch };\n let publishedParent: CommandOccurrence<RecordCommand> | undefined;\n for (\n let child: CommandOccurrence | undefined = occurrence;\n child?.parent;\n child = child.parent\n ) {\n const parent = child.parent;\n if (!isSeriesOccurrence(parent) || child.role !== \"member\") continue;\n if (parent.command.series.selection.membership())\n publishedParent = this.#seriesOwner(parent);\n break;\n }\n this.#visitPrecedingWrites(\n occurrence,\n (write) => {\n if (write.write.occurrence === publishedParent) return;\n this.#checkPair(write, readVisit);\n },\n branch\n );\n }\n #checkPair(write: WriteVisit, read: ReadVisit): void {\n if (!this.#compatible(write.branch, read.branch)) return;\n this.#readMembership(write.write, read.read);\n if (read.read.target) this.#readTarget(write.write, read.read);\n }\n #activeRefusal(read: ReadVisit): Error | undefined {\n for (let branch = read.branch; branch; branch = branch.parent) {\n if (branch.arm === \"missing\") return undefined;\n const choice = branch.choice.command;\n if (\n choice.kind !== \"choose\" ||\n !this.execution.attempt.rows.has(choice.lookup)\n )\n return undefined;\n }\n return read.read.owner.refusal;\n }\n #analyzeOccurrence(occurrence: CommandOccurrence): void {\n this.#analyzeRead(occurrence);\n const command = occurrence.command;\n if (command.kind === \"record\") {\n // A snapshot: `depend` moves a dependent child within this array while\n // the walk is on it, and a sibling that shifts into the vacated slot\n // must still be analysed (N1).\n this.#analyzeChildren(occurrence);\n for (const child of occurrence.children) {\n const childCommand = child.command;\n if (childCommand.kind === \"record\")\n occurrence.refusal ??= child.refusal;\n else if (childCommand.kind === \"choose\") {\n const found = this.choiceArm(child, \"found\");\n const missing = this.choiceArm(child, \"missing\");\n if (found && !missing) occurrence.refusal ??= found.refusal;\n } else if (childCommand.kind === \"series\")\n for (const record of child.children)\n occurrence.refusal ??= record.refusal;\n else if (childCommand.kind === \"selectedSeries\") {\n const template = child.children.find(\n (candidate) => candidate.role === \"template\"\n );\n if (template && isRecordOccurrence(template))\n occurrence.refusal ??= template.refusal;\n }\n }\n return;\n }\n if (command.kind === \"choose\" || command.kind === \"series\") {\n this.#analyzeChildren(occurrence);\n return;\n }\n if (command.kind === \"selectedSeries\") {\n const template = occurrence.children.find(\n (child) => child.role === \"template\"\n );\n if (template) this.#analyzeOccurrence(template);\n }\n }\n /** Recurse over a stable sibling snapshot while dependency moves may occur. */\n #analyzeChildren(occurrence: CommandOccurrence): void {\n for (const child of [...occurrence.children])\n this.#analyzeOccurrence(child);\n }\n #branchOf(occurrence: CommandOccurrence): BranchPath | undefined {\n const parent = occurrence.parent;\n if (!parent) return undefined;\n return this.#childBranch(parent, occurrence, this.#branchOf(parent));\n }\n #isSeriesMember(\n parent: CommandOccurrence,\n child: CommandOccurrence\n ): boolean {\n return (\n parent.command.kind === \"series\" ||\n (isSeriesOccurrence(parent) && child.role === \"member\")\n );\n }\n #visitFollowingReads(\n target: CommandOccurrence,\n visit: (read: ReadVisit) => \"stop\" | void,\n startBranch: BranchPath | undefined\n ): boolean {\n let current = target;\n let branch = startBranch;\n while (current.parent) {\n const parent = current.parent;\n const parentBranch =\n parent.command.kind === \"choose\" ? branch?.parent : branch;\n let follows = false;\n if (!this.#isSeriesMember(parent, current)) {\n for (const sibling of parent.children) {\n if (follows) {\n const stopped = this.#visitReads(\n sibling,\n visit,\n this.#childBranch(parent, sibling, parentBranch)\n );\n if (stopped) return true;\n } else if (sibling === current) follows = true;\n }\n }\n current = parent;\n branch = parentBranch;\n }\n return false;\n }\n expandSeries(\n occurrence: CommandOccurrence<SeriesOccurrence>,\n members: readonly SelectedSeriesMember[]\n ): SeriesRefusal | undefined {\n // Expanded once per occurrence: `captureSeries` returns early once the\n // attempt holds this capture, and a recovery re-plans onto a NEW command\n // tree (`commands/index.ts`), never re-entering this occurrence.\n occurrence.children = members.map((member) => {\n const child = this.occurrence(member);\n child.role = \"member\";\n this.#materializePlacement(child);\n return child;\n });\n const memberOccurrences = this.seriesMembers(occurrence);\n const seriesBranch = this.#branchOf(occurrence);\n for (const member of memberOccurrences) this.#bindTree(member, occurrence);\n for (const member of memberOccurrences) {\n this.#analyzeOccurrence(member);\n }\n for (const [index, occurrenceMember] of memberOccurrences.entries()) {\n const member = members[index];\n if (!member) continue;\n if (occurrenceMember.command.kind === \"record\") {\n const refusal = occurrenceMember.refusal;\n if (refusal) return { error: refusal, member };\n }\n let refusal: Error | undefined;\n this.#visitWrites(\n occurrenceMember,\n (write) => {\n if (\n this.#visitFollowingReads(\n occurrence,\n (read) => {\n this.#checkPair(write, read);\n refusal ??= this.#activeRefusal(read);\n return refusal ? \"stop\" : undefined;\n },\n seriesBranch\n )\n )\n return;\n },\n seriesBranch\n );\n if (refusal) return { error: refusal, member };\n }\n return undefined;\n }\n lookup(\n model: AnyModel,\n source: SelectionSource,\n required?: DeferredFailure,\n facts?: SelectorFacts\n ): Selection {\n return new Selection(this.execution, model, source, required, facts);\n }\n capture(selection: Selection, row: Input): Selection {\n return this.lookup(\n selection.model,\n {\n kind: \"query\",\n selector: this.context.queries.identitySelector(\n selection.model,\n this.context.schema.identity(selection.model, row)\n ),\n // The captured row was judged where it was selected; the row its\n // write produces is judged at the same verb (R4).\n ...(selection.judgement && { judgement: selection.judgement }),\n },\n selection.required\n );\n }\n /**\n * A root `create`/`update` that writes no relation and publishes no relation\n * is the set-oriented mutation owner plus ONE cardinality decision — the same\n * statement, the same prepared projection and the same decoder a bulk verb\n * uses, so no second single-row physical path exists. It is also the shipped\n * fold gate (`UpdateOperation` `canFold`, `DeleteOperation.ts:206-212`): a\n * relation projection must read other rows, which no RETURNING can carry, and\n * a provider without RETURNING keeps the located/mutated/re-read route.\n */\n /**\n * A root `update` that writes no relation and publishes no relation is the\n * set-oriented mutation owner plus ONE cardinality decision — the same\n * statement, the same prepared projection and the same decoder a bulk verb\n * uses, so no second single-row physical path exists. It is also the shipped\n * fold gate (`UpdateOperation` `canFold`): a relation projection must read\n * other rows, which no RETURNING can carry, and a provider without RETURNING\n * keeps the located/mutated/re-read route.\n *\n * Root `create` folds under the same three conditions, through the set-oriented\n * INSERT owner ({@link rootCreate}).\n */\n private rootUpdate(\n model: AnyModel,\n args: Arguments,\n raw: Arguments\n ): (() => Promise<unknown>) | undefined {\n const ctx = this.context;\n if (ctx.schema.namesRelation(model, args.data)) return undefined;\n if (!ctx.driver.adapter.capabilities.supportsReturning) return undefined;\n const projection = ctx.queries.prepareProjection(model, args);\n if (!returningSafeProjection(projection)) return undefined;\n const values = this.stamp(model, \"update\", args.data, raw.data);\n // Nothing to assign emits no UPDATE: the row is only read, on the\n // located route.\n if (Object.keys(values).length === 0) return undefined;\n const selector = ctx.queries.candidates(\n ctx.queries.prepareSelector(model, args.where, true),\n \"root\",\n undefined,\n this.judge(model, args.data, raw.data)\n );\n return () =>\n ctx.updateMany(\n model,\n selector,\n values,\n undefined,\n projection,\n () => new NotFoundError(model[\"~\"].names.ts!, \"update\")\n );\n }\n /**\n * A tombstoning root delete's plan: `effect` behind its referential premise,\n * stated first — no candidate is still referenced through a restricting\n * slot. A model without such a slot runs `effect` alone, under the limit.\n *\n * A `limit` makes the premise and the effect name ONE window, the first\n * `limit` candidates in key order, so a reference outside it does not refuse\n * the delete and one inside it does: the refusal the database gives a hard\n * delete of those same rows, which every limited write takes in that order\n * too (`Queries.lowerMutationLimit`). An interactive session\n * READS the window — the lock below, limited — and both statements take\n * exactly the rows it locked, by key. Where the keys pass half the driver's\n * bind budget (counted before compiling: SQLite's 999 at the chunked-delete\n * idiom's 1000), or either statement, compiled with them, would pass the\n * budget (a caller's own long `in` list), the window is the candidates up to\n * its last key instead ({@link Queries.through},\n * one bound value per key column) and the effect keeps the limit, so a row\n * that becomes a candidate below that key after the lock still cannot make\n * the count exceed it. A batch states the window in SQL in both\n * statements ({@link Queries.window}), whose total order gives the one atomic\n * unit one answer. `effectBinds(rows)` counts what the effect binds beyond\n * its selector: its assignments, and the captured keys of a result re-read\n * by key. The compiled statements are the meter.\n *\n * An interactive session locks the candidates before it asks (DC14): the\n * premise is then a later statement, so it sees a child a concurrent writer\n * committed while holding a candidate, and a writer that reaches a\n * candidate afterwards waits for the tombstone and no longer finds it live.\n * Measured on PostgreSQL: without the lock both interleavings of a\n * create-with-connect leave a live child under a tombstone. Without a limit\n * no key is needed, so the lock is answered as one count\n * ({@link Queries.lockAll}), and skipped where the provider has no row lock.\n */\n #unreferenced(\n candidates: PreparedSelector,\n limit: number | undefined,\n single: boolean,\n effectBinds: (rows: number) => number,\n effect: (window: PreparedSelector, limit?: number) => Promise<unknown>\n ): PhysicalPlan {\n const blocked = this.blocked(candidates);\n if (!blocked) return { single, run: () => effect(candidates, limit) };\n const ctx = this.context;\n const queries = ctx.queries;\n const model = candidates.model;\n const failure = this.restriction(model);\n return {\n single: false,\n run: async () => {\n const locked = (selector: PreparedSelector, take?: number) =>\n queries.select(\n model,\n {\n take,\n select: Object.fromEntries(\n ctx.schema.keys(model).map((field) => [field, true])\n ),\n },\n undefined,\n { selector, forUpdate: !ctx.usesBatch }\n );\n // The rows the call takes, stated once: the premise asks about them\n // and the effect writes them. A limit names a window of the\n // candidates, the first `limit` in key order (`Queries.select`).\n let taken = candidates;\n let effectLimit: number | undefined;\n // A batch's window is SQL beside the candidates: the write re-checks\n // both on a row a concurrent writer changed (READ COMMITTED), so the\n // window alone would take a row that no longer matches.\n if (limit !== undefined && ctx.usesBatch)\n taken = queries.andSelectors(model, [\n candidates,\n queries.window(candidates, limit),\n ]);\n else if (limit !== undefined) {\n // The effect takes exactly the rows the lock took, still under the\n // candidates' own predicates: a lock holds the row, not the related\n // rows a filter or a row domain reads.\n const rows = await ctx.read(locked(candidates, limit), true);\n // Counted before anything is compiled: the keys alone may not pass\n // half the budget (the premise and the effect each bind them), and\n // a set of key equalities nests one level per key, so this also\n // keeps it within a compiler's expression depth (SQLite's 1000).\n const budget = ctx.driver.maxBindParametersPerStatement;\n const keyed =\n budget === undefined ||\n rows.length * ctx.schema.keys(model).length <= budget / 2;\n const exact = keyed\n ? queries.andSelectors(model, [\n candidates,\n queries.includeIdentities(\n model,\n rows.map((row) => ctx.schema.identity(model, row))\n ),\n ])\n : undefined;\n // Then the compiled statements, with all they bind beside the keys.\n const fits =\n exact !== undefined &&\n (budget === undefined ||\n (locked(this.blocked(exact)!, 1).sql.values.length <= budget &&\n (queries.lowerSelector(exact, \"budget\")?.values.length ?? 0) +\n effectBinds(rows.length) <=\n budget));\n if (exact && (fits || rows.length === 0)) taken = exact;\n else {\n // Too long to bind as keys: the candidates up to the last locked\n // key, and the effect keeps the limit, so a row that becomes a\n // candidate below that key after the lock still cannot make the\n // count exceed it.\n taken = queries.andSelectors(model, [\n candidates,\n queries.through(model, ctx.schema.identity(model, rows.at(-1)!)),\n ]);\n effectLimit = limit;\n }\n } else if (\n !ctx.usesBatch &&\n ctx.driver.adapter.capabilities.supportsRowLocks\n )\n await ctx.read(queries.lockAll(candidates), true);\n const query = locked(this.blocked(taken)!, 1);\n // A packaged array member states it inside the array's atomic unit.\n if (ctx.preparesBatch)\n ctx.packageGuard(model, query.sql, \"notExists\", failure);\n else await ctx.requireAbsent(query, this.restrictFailure(model)());\n return effect(taken, effectLimit);\n },\n };\n }\n /**\n * A root `create` that writes no relation and publishes no relation is the\n * set-oriented INSERT owner plus ONE cardinality decision, exactly as\n * {@link rootUpdate} is for `update`: one `INSERT … RETURNING <projection>`,\n * the same prepared projection and the same decoder a bulk create uses. It is\n * the shipped classification too — `canExecuteDirectly` runs this shape\n * through `runStatementAtomic` with no transaction, measured.\n *\n * The gate is the fold's own reachability: a relation in `data` needs the\n * record route's dependency machinery, a projection that reads other rows has\n * no RETURNING spelling, and a provider without RETURNING must re-read.\n */\n /**\n * The array route's upsert. That route prepares a package and issues no\n * read of its own, so the conditional form (a locate, two arms and their\n * premises, then a terminal read) cannot be built there at all. The shipped\n * engine served it with its two top-level upsert paths, restated here at\n * this owner (D-46): (1) \"an eligible `ON CONFLICT` fold has no planning\n * read\" — one targeted conflict statement, under the shipped fold's\n * conjuncts (`write-engine/UpsertOperation.ts` `buildOnConflictFold`): a\n * targeted-upsert adapter, no conditional filter, a `where` naming one\n * constraint and nothing else, the create spelling every column of that\n * constraint with the primitive value the `where` names, an update of values\n * and counters (engine-08);\n * (2) otherwise the probe-first path — the locate read runs at preparation\n * ({@link OperationContext.read}) and the selected scalar arm rides the\n * owner's batch as ONE statement with RETURNING, the existing owners of a\n * folded root write (`createMany`, `updateMany` with its packaged presence\n * premise). Both need scalar arms, a non-empty update naming no key of the\n * model and a RETURNING-safe projection on a RETURNING adapter; everything\n * else keeps the conditional form and, on this route, its existing answer.\n * The targeted fold serves the live route too. Stamped writes retain their\n * existing route, keeping stamp admission with the selected arm.\n */\n #rootUpsert(\n model: AnyModel,\n args: Arguments,\n raw: Arguments\n ): PhysicalPlan | undefined {\n const ctx = this.context;\n const capabilities = ctx.driver.adapter.capabilities;\n if (!ctx.preparesBatch && ctx.scope?.rows.stamps !== undefined)\n return undefined;\n if (args.targetWhere || args.setWhere) return undefined;\n if (!capabilities.supportsReturning) return undefined;\n if (\n ctx.schema.namesRelation(model, args.create!) ||\n ctx.schema.namesRelation(model, args.update!)\n )\n return undefined;\n const updates =\n Object.keys(record(raw.update)).length === 0\n ? {}\n : this.stamp(model, \"update\", args.update!, raw.update);\n const fields = Object.keys(updates);\n if (fields.length === 0) return undefined;\n if (ctx.schema.keys(model).some((key) => updates[key] !== undefined))\n return undefined;\n const projection = ctx.queries.prepareProjection(model, args);\n if (!returningSafeProjection(projection)) return undefined;\n const values = this.stamp(model, \"create\", args.create!, raw.create);\n const missing = () =>\n ctx.createMany(model, [values], projection, false, () => {\n throw new InvalidScalarResult(\n \"record\",\n \"INSERT did not produce the required record\"\n );\n });\n const judgement = this.judge(\n model,\n args.update!,\n record(raw.update),\n \"upsert\"\n );\n const lookup = this.lookup(model, {\n kind: \"query\",\n where: args.where,\n unique: true,\n purpose: \"root\",\n judgement,\n });\n // The arm this probe chooses INSERTS the key it just looked for, so the\n // probe does not lock the absence it may find (`Selection.insertsWhenAbsent`).\n lookup.insertsWhenAbsent = true;\n const key = lookup.selector.uniqueKey;\n // The targeted fold evaluates no selector: under a domain its conflict\n // could be a hidden row, which it would update. A counter folds too\n // (engine-08): `upsertOne` names each value over the conflicting row.\n const spelled =\n capabilities.supportsTargetedUpsert &&\n lookup.selector.scoped === undefined &&\n key !== undefined &&\n lookup.selector.uniqueValues !== undefined &&\n key.fields.every((field) => {\n const value = values[field];\n return (\n (value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")) &&\n Object.is(value, lookup.selector.uniqueValues!.get(field))\n );\n }) &&\n fields.every((field) =>\n ctx.queries.namesUpdate(model, field, updates[field])\n );\n if (spelled)\n return {\n single: true,\n run: () =>\n ctx.upsertOne(model, values, updates, key!.fields, projection, () => {\n throw new TypeError(\n \"INSERT … ON CONFLICT did not produce the required record\"\n );\n }),\n };\n if (!ctx.preparesBatch) return undefined;\n // The locate read precedes the arm, so this form is never one statement.\n return {\n single: false,\n run: async () => {\n const rows = await ctx.planningLocate(lookup.query(), model);\n const captured = rows[0];\n if (!captured) return missing();\n // The row the unlocked probe found is updated only while it is still\n // a candidate: one hidden since then is the other's race, not found.\n const selector = ctx.queries.candidates(\n ctx.queries.prepareSelector(\n model,\n ctx.schema.identity(model, captured),\n true\n ),\n \"root\",\n undefined,\n judgement\n );\n return ctx.updateMany(\n model,\n selector,\n updates,\n undefined,\n projection,\n () => new NotFoundError(model[\"~\"].names.ts!, \"upsert\")\n );\n },\n };\n }\n private rootCreate(\n model: AnyModel,\n args: Arguments,\n raw: Arguments\n ): (() => Promise<unknown>) | undefined {\n const ctx = this.context;\n if (ctx.schema.namesRelation(model, args.data)) return undefined;\n if (!ctx.driver.adapter.capabilities.supportsReturning) return undefined;\n const projection = ctx.queries.prepareProjection(model, args);\n if (!returningSafeProjection(projection)) return undefined;\n const values = this.stamp(model, \"create\", args.data, raw.data);\n return () =>\n ctx.createMany(model, [values], projection, false, () => {\n throw new InvalidScalarResult(\n \"record\",\n \"INSERT did not produce the required record\"\n );\n });\n }\n /**\n * Construct this operation's physical form and answer whether that form MAY\n * be one statement ({@link PhysicalPlan.single}). Construction reaches no\n * provider, so the envelope owner can ask before it decides\n * (`OperationContext.run`). The envelope RULE itself lives in one place, the\n * context: a form admitted here is only confirmed single by reaching its\n * terminal statement having issued no other.\n */\n plan(model: AnyModel, args: Arguments, raw: Arguments): PhysicalPlan {\n const ctx = this.context;\n const adapter = ctx.driver.adapter;\n const returning = adapter.capabilities.supportsReturning;\n if (ctx.operation === \"createMany\") {\n const rows = entries(args.data);\n const rawRows = entries(raw.data);\n const relationBearing = rows.some((row) =>\n model[\"~\"].relationNames.some((name) => row[name] !== undefined)\n );\n if (relationBearing) {\n if (args.skipDuplicates)\n ctx.admitsSuppression(\"rows involving nested writes\");\n const records = rows.map((row, index) => {\n const record = this.create(model, row, rawRows[index]!);\n if (args.skipDuplicates)\n record.suppression = { kind: \"skipDuplicate\" };\n return record;\n });\n const occurrences = records.map((record) => {\n for (const field of ctx.schema.keys(model))\n record.fields.field(field);\n return this.analyze(record);\n });\n const series: RecordSeriesCommand = {\n kind: \"series\",\n records: occurrences,\n };\n return {\n single: false,\n run: () => this.execution.records(occurrences, args.select, series),\n };\n }\n const projection = bulkProjection(ctx, model, args);\n const values = rows.map((row, index) =>\n this.stamp(model, \"create\", row, rawRows[index])\n );\n const recoverableSkip =\n args.skipDuplicates === true &&\n adapter.mutations.skipDuplicatesStrategy === \"recoverableUniqueError\";\n if (recoverableSkip) ctx.admitsSuppression(\"duplicate rows\");\n // `single` is the envelope owner's OPTIMISTIC question — \"may this form\n // reduce to one statement?\" — never a per-verb count. A relation-free\n // `createMany` writes one grouped, bind-budgeted INSERT per column set, so\n // the answer is a row-count-independent fact: a recoverable skip is\n // per-row by construction, and a projection without RETURNING re-reads.\n // How many statements the construction actually produces is the\n // construction's own answer, enforced at `OperationContext.dispatch`.\n return {\n single:\n values.length === 0 ||\n (!recoverableSkip && (!projection || returning)),\n run: () =>\n ctx.createMany(model, values, projection, args.skipDuplicates),\n };\n }\n // Root delete and deleteMany are the selected-row removal owner plus ONE\n // cardinality: `delete` locates by the extended-unique selector and owns\n // the missing-row identity, `deleteMany` takes a limit. A managed model's\n // rows are tombstoned by the same plan: the set UPDATE owner in place of\n // the set DELETE owner, behind the referential premise.\n if (ctx.operation === \"delete\" || ctx.operation === \"deleteMany\") {\n const one = ctx.operation === \"delete\";\n const projection = one\n ? ctx.queries.prepareProjection(model, args)\n : bulkProjection(ctx, model, args);\n if (args.limit === 0)\n return {\n single: true,\n run: async () => ctx.emptyBulkResult(projection),\n };\n const tombstone = this.tombstone(model);\n const selector = this.candidates(\n ctx.queries.prepareSelector(model, args.where, one),\n \"root\",\n tombstone !== undefined,\n DELETE_JUDGEMENT\n );\n const missing = one\n ? () => new NotFoundError(model[\"~\"].names.ts!, \"delete\")\n : undefined;\n const single =\n !projection || (returning && returningSafeProjection(projection));\n if (!tombstone)\n return {\n single,\n run: () =>\n ctx.deleteMany(model, selector, args.limit, projection, missing),\n };\n const values = tombstone.admitted;\n return this.#unreferenced(\n selector,\n args.limit,\n single,\n (rows) => {\n // A result without RETURNING is re-read by key, and its write binds\n // the captured keys beside the selector.\n let bound =\n projection && !(returning && returningSafeProjection(projection))\n ? rows * ctx.schema.keys(model).length\n : 0;\n for (const [field, value] of Object.entries(values))\n bound += ctx.queries.updateAssignment(model, field, value).values\n .length;\n return bound;\n },\n (window, limit) =>\n ctx.updateMany(model, window, values, limit, projection, missing)\n );\n }\n if (ctx.operation === \"upsert\") {\n const folded = this.#rootUpsert(model, args, raw);\n if (folded) return folded;\n const missing = this.create(model, args.create!, raw.create!);\n missing.operation = \"upsert\";\n const lookup = this.lookup(model, {\n kind: \"query\",\n where: args.where,\n unique: true,\n purpose: \"root\",\n judgement: this.judge(model, args.update!, raw.update!, \"upsert\"),\n });\n // As above: the missing arm below inserts this very key\n // (`Selection.insertsWhenAbsent`).\n lookup.insertsWhenAbsent = true;\n const queries = this.context.queries;\n const probes: Condition[] = [];\n const conditioned: string[] = [];\n // One builder for every premise sentence this operation owns; the subject\n // is the premise that no longer holds.\n const premiseChanged = (subject: string) =>\n new TransactionError(\n `The upsert ${subject} changed before the atomic batch.`,\n { meta: { model: model[\"~\"].names.ts!, operation: \"upsert\" } }\n );\n for (const field of [\"targetWhere\", \"setWhere\"] as const) {\n const where = args[field];\n if (!where) continue;\n const conditionSelector = queries.prepareSelector(model, where);\n const skip = premiseChanged(`${field} skip premise`);\n skip.meta.raceable = true;\n const probe = this.lookup(model, {\n kind: \"query\",\n selector: queries.andSelectors(model, [\n lookup.selector,\n conditionSelector,\n ]),\n });\n // This probe runs before either arm is chosen and its selector is the\n // locator's own, narrowed by the condition — so it names the key the\n // missing arm inserts, and a miss here must not lock that absence\n // either (`Selection.insertsWhenAbsent`). `targetWhere` / `setWhere`\n // are public arguments and `rootUpsert` declines them, so on MySQL\n // this is the only spelling of the shape that reaches the provider.\n probe.insertsWhenAbsent = true;\n conditioned.push(field);\n probes.push({\n lookup: probe,\n match: premiseChanged(`${field} match premise`),\n skip,\n });\n }\n const [firstProbe] = probes;\n const found = this.occurrence(\n this.update(lookup, args.update!, raw.update!, true, \"upsert\")\n );\n // The shipped engine's THIRD key owner, raised where it raises it: at\n // analysis, before either arm exists, so a missing row is refused too and\n // nothing is written (`EngineSchema.keyTransitionRefusal`). Both facts it\n // needs are read off structures that already exist — the update arm's own\n // recorded key transitions, and the locator's DISCRIMINATOR pins — so the\n // refusal restates neither the relation walk nor the selector.\n const transition = ctx.schema.keyTransitionRefusal(\n model,\n args.update!,\n lookup.selector.facts.keys,\n found.command.transitions\n );\n if (transition) throw transition;\n const choice: Choose = {\n kind: \"choose\",\n model,\n lookup,\n operation: \"upsert\",\n missing: this.occurrence(missing),\n // A conditions record exists where a condition does. Its `matched`\n // failure is decided HERE, where the premises are built, so the one\n // place that raises it states no diagnosis of its own (repair prompt 2\n // §2).\n conditions: firstProbe && {\n probes,\n missingRow: new NotFoundError(model[\"~\"].names.ts!, \"upsert\"),\n matched:\n probes.length === 1\n ? firstProbe.match\n : premiseChanged(`matched premise (${conditioned.join(\", \")})`),\n },\n fields: new Assignments(model, \"select\", {}, {}, undefined, [\n missing.fields,\n ]),\n found,\n };\n found.command.operation = \"upsert\";\n choice.fields.forward(found.command.fields);\n for (const field of ctx.schema.keys(model)) choice.fields.field(field);\n const occurrence = this.analyze(choice);\n // The row key's portability contract, carried where the shipped engine\n // carries it for an upsert: on the FOUND arm (`UpsertOperation.compileFoundArm`\n // runs `updateLegality` only once that arm is selected, so a create still\n // writes its row) and only when the update payload names relations\n // (`updateHasRelations ? … : undefined`). It outranks a nested-write\n // refusal on the same arm, as the shipped legality order does.\n const foundArm = this.choiceArm(occurrence, \"found\");\n if (foundArm && ctx.schema.namesRelation(model, args.update!))\n foundArm.refusal =\n ctx.schema.keyPortabilityRefusal(model, args.update) ??\n foundArm.refusal;\n return {\n single: false,\n run: () => this.execution.complete(occurrence, args),\n };\n }\n if (ctx.operation === \"create\" || ctx.operation === \"update\") {\n const folded =\n ctx.operation === \"update\"\n ? this.rootUpdate(model, args, raw)\n : this.rootCreate(model, args, raw);\n if (folded) return { single: true, run: folded };\n const root =\n ctx.operation === \"create\"\n ? this.create(model, args.data, raw.data)\n : this.update(\n this.lookup(\n model,\n {\n kind: \"query\",\n where: args.where!,\n unique: true,\n purpose: \"root\",\n judgement: this.judge(model, args.data, raw.data),\n },\n () => new NotFoundError(model[\"~\"].names.ts!, \"update\")\n ),\n args.data,\n raw.data\n );\n for (const field of ctx.schema.keys(model)) root.fields.field(field);\n const occurrence = this.analyze(root);\n return {\n single: false,\n run: () => this.execution.complete(occurrence, args),\n };\n }\n const updateData = args.data;\n const relationBearing = ctx.schema.namesRelation(model, updateData);\n const projection = bulkProjection(ctx, model, args);\n if (args.limit === 0)\n return { single: true, run: async () => ctx.emptyBulkResult(projection) };\n const judgement = this.judge(model, updateData, raw.data);\n const values = relationBearing\n ? undefined\n : this.stamp(model, \"update\", updateData, raw.data);\n // Nothing to assign emits no UPDATE: the rows are only read, as a series.\n if (values !== undefined && Object.keys(values).length > 0) {\n const selector = ctx.queries.candidates(\n ctx.queries.prepareSelector(model, args.where),\n \"root\",\n undefined,\n judgement\n );\n return {\n single: !projection || returning,\n run: () =>\n ctx.updateMany(model, selector, values, args.limit, projection),\n };\n }\n const selection = this.lookup(\n model,\n { kind: \"query\", where: args.where, purpose: \"root\", judgement },\n () => new NotFoundError(model[\"~\"].names.ts!, \"update\")\n );\n const analysis = this.update(selection, updateData, raw.data, true);\n const series: SelectedSeries = {\n selection,\n analysis,\n limit: args.limit,\n mutation: { kind: \"update\", raw: raw.data },\n };\n const occurrence = this.analyzeSeries(series);\n return {\n single: false,\n run: async () => {\n if (projection)\n return this.execution.series(\n occurrence,\n series.selection,\n projection\n );\n return { count: await this.execution.series(occurrence) };\n },\n };\n }\n}\n","import type { Operations } from \"@client/types\";\nimport type { QueryExecutionContext } from \"@drivers/types\";\nimport { NotFoundError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport { baseOperation } from \"../../routed-operations\";\nimport type { PreparedBatchOperation } from \"../../types\";\nimport {\n type ExecutionBinding,\n OperationContext,\n} from \"../shared/operation-context\";\nimport { admitProjected } from \"../shared/projected\";\nimport type { Leaf, ProjectionShape, Read } from \"../shared/query\";\nimport { PreparedDomain, Queries } from \"../shared/query\";\nimport {\n type CallRows,\n type CallScope,\n parseStamped,\n type RowDomain,\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 { Commands, type PhysicalPlan } from \"./commands\";\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 cache\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/**\n * One admitted operation, before any execution.\n *\n * The client lifecycle is admission-first by construction — a cache 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 /** The ONE admission of this input. */\n readonly args: Arguments;\n /** Present for read verbs: the one prepared read's published facts. */\n readonly read?: PreparedRead;\n execute(\n binding?: ExecutionBinding,\n attribution?: QueryExecutionContext\n ): 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\nclass PreparedCommand implements PreparedOperation {\n readonly #config: EngineConfig;\n readonly #schema: EngineSchema;\n readonly #queries: Queries;\n readonly #operation: Operation;\n readonly #model: EngineConfig[\"schema\"][string];\n readonly #modelName: string;\n readonly #rawArgs: unknown;\n readonly #missing: (() => NotFoundError) | undefined;\n readonly #scope: CallScope | undefined;\n #admitted: Arguments | undefined;\n #prepared: Read | undefined;\n #facts: PreparedRead | undefined;\n\n constructor(\n config: EngineConfig,\n schema: EngineSchema,\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 const defaults = rows && preparedDomain(queries, rows.defaults);\n this.#scope = rows && {\n rows,\n domain: preparedDomain(queries, rows.domain, defaults),\n defaults: defaults!,\n instant: () => (instant ??= new Date()),\n };\n this.#config = config;\n this.#schema = schema;\n this.#queries = queries;\n this.#operation = baseOperation(requested);\n this.#model = config.schema[modelName]!;\n this.#modelName = modelName;\n this.#rawArgs = rawArgs;\n this.#missing =\n requested === this.#operation\n ? undefined\n : () =>\n new NotFoundError(\n this.#model[\"~\"].names.ts ?? \"unknown\",\n requested\n );\n }\n\n get args(): Arguments {\n return (this.#admitted ??= this.#admit());\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 #admit(): Arguments {\n const stamps = this.#scope?.rows.stamps;\n const domain = this.#scope?.domain;\n const admit = domain?.projects\n ? () =>\n admitProjected(\n domain,\n this.#schema,\n this.#model,\n this.#operation,\n this.#rawArgs,\n (raw) => this.#schema.admit(this.#model, this.#operation, raw)\n )\n : () => this.#schema.admit(this.#model, this.#operation, this.#rawArgs);\n return 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 if (!value) return undefined;\n return (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 ): OperationContext {\n return new OperationContext(\n this.#schema,\n this.#config.driver,\n this.#modelName,\n this.#operation,\n binding,\n preparing,\n attribution,\n this.#scope\n );\n }\n\n #plan(context: OperationContext): PhysicalPlan {\n return new Commands(context).plan(\n this.#model,\n this.args,\n this.#rawArgs as Arguments\n );\n }\n\n #body(context: OperationContext) {\n const value = this.#read();\n if (value) return context.run(() => context.publish(value, this.#missing));\n // The physical form is constructed BEFORE the envelope decision and runs\n // once, whichever envelope the rule chooses.\n let planned: PhysicalPlan | undefined = this.#plan(context);\n const single = planned.single;\n // Each ATTEMPT runs its own occurrence tree. The envelope restart and the\n // recovery both re-enter this body, and a recovery re-plans from the same\n // ADMITTED arguments — never re-validated, never re-transformed (rule 10,\n // Arnaud's D-25) — because the tree that ran carries the members it\n // captured and a series occurrence is expanded exactly once. The first\n // attempt consumes the plan built above, which is also the plan that\n // answered the envelope question, so nothing is constructed twice to\n // START an operation.\n return context.run(() => {\n const plan = planned ?? this.#plan(context);\n planned = undefined;\n return plan.run();\n }, single);\n }\n\n execute(\n binding?: ExecutionBinding,\n attribution?: QueryExecutionContext\n ): Promise<unknown> {\n try {\n return this.#body(this.#context(false, attribution, binding));\n } catch (error) {\n return Promise.reject(error);\n }\n }\n\n prepareSingle(\n attribution?: QueryExecutionContext\n ): PreparedBatchOperation<unknown> | undefined {\n // Preparing admits the input whatever the verb compiles to: an\n // operation that publishes no single query still answers for the\n // payload it was handed, exactly as `prepareBatch` does.\n this.args;\n const context = this.#context(true, attribution);\n const value = this.#read();\n if (value) {\n context.publishPrepared(value, this.#missing);\n return context.preparedBatch();\n }\n // D-20: a WRITE whose plan is one statement publishes the same package\n // (`prepareBatch` would publish it too), so the array owner parses it\n // through its own `parseResult` seam and interceptor onion instead of\n // through the batch. It is not a second preparation: this is the\n // preparation, and `Commands.plan` states the ONE-statement\n // admissibility itself. Preparation reaches no driver and queues\n // synchronously, so the package is in hand when this returns; anything\n // it would refuse — a capability gate, the dynamic-planning sentinel —\n // is refused again, and reported, by the arm that actually runs the\n // operation, which is the only arm a caller takes once no single\n // package is published.\n const plan = this.#plan(context);\n if (!plan.single) return undefined;\n plan.run().catch(() => undefined);\n return context.preparedBatch();\n }\n\n async prepareBatch(\n attribution?: QueryExecutionContext\n ): Promise<PreparedBatchOperation<unknown> | undefined> {\n const context = this.#context(true, attribution);\n try {\n await this.#body(context);\n } catch (error) {\n if (context.isIncompletePreparation(error)) return undefined;\n throw error;\n }\n return context.preparedBatch();\n }\n}\n\n/**\n * Prepared queries per driver result parser. Weak: a schema and adapter can\n * outlive every client, and a transient driver's parser (with whatever it\n * captures) must be released with it. A driver without a parser has one slot.\n */\ninterface QueriesByResult {\n readonly parsers: WeakMap<object, Queries>;\n none?: Queries;\n}\n\n/**\n * Engines over the same resolved registry share one schema view and, per\n * adapter and result parser, one query owner: both derive only from those\n * inputs, so a client created per request reuses the warm per-model views\n * instead of rebuilding them.\n */\nconst sharedEngines = new WeakMap<\n object,\n {\n schema: EngineSchema;\n queries: WeakMap<object, QueriesByResult>;\n }\n>();\n\n/**\n * Each row domain a call selects, prepared once per query owner. A prepared\n * domain derives only from the domain, that owner (its adapter and result\n * parser) and its defaults, so clients sharing the owner share it too; a\n * client without `rows` never reaches the map. The domain alone keys it: a\n * chain's binding builds each domain with its one default domain.\n */\nconst preparedDomains = new WeakMap<\n Queries,\n WeakMap<RowDomain, PreparedDomain>\n>();\n\nfunction preparedDomain(\n queries: Queries,\n rows: RowDomain,\n defaults?: PreparedDomain\n): PreparedDomain {\n const byDomain = memo(preparedDomains, queries, () => new WeakMap());\n return memo(\n byDomain,\n rows,\n () => new PreparedDomain(rows, queries, defaults)\n );\n}\n\nfunction sharedQueries(config: EngineConfig): Queries {\n const { adapter, result } = config.driver;\n const key = config.resolved?.registry;\n let shared = key && sharedEngines.get(key);\n if (!shared) {\n shared = {\n schema: new EngineSchema(config.schema, config.resolved),\n queries: new WeakMap(),\n };\n if (key) sharedEngines.set(key, shared);\n }\n let byResult = shared.queries.get(adapter);\n if (!byResult)\n shared.queries.set(adapter, (byResult = { parsers: new WeakMap() }));\n if (!result) {\n return (byResult.none ??= new Queries(shared.schema, adapter, result));\n }\n let queries = byResult.parsers.get(result);\n if (!queries) {\n queries = new Queries(shared.schema, adapter, result);\n byResult.parsers.set(result, queries);\n }\n return queries;\n}\n\nexport function createCommandEngine(config: EngineConfig) {\n // One query owner for the prepared read. The adapter is pinned by identity\n // across transaction scoping (`TransactionBoundDriver` copies\n // `baseDriver.adapter`), so the statement and shape prepared here are valid for\n // every binding of this driver's lineage.\n const queries = sharedQueries(config);\n const { schema } = queries;\n const prepare = (\n modelName: string,\n requested: Operations,\n rawArgs: unknown,\n rows?: CallRows\n ): PreparedOperation =>\n new PreparedCommand(\n config,\n schema,\n queries,\n modelName,\n requested,\n rawArgs,\n rows\n );\n return { prepare };\n}\n","/**\n * Raptor 3 — private client route (G4-03).\n *\n * The one place that adapts the EXISTING client protocol to the candidate's\n * private prepared-operation boundary. It owns exactly one decision: which\n * driver an existing owner supplied for this run, and therefore which of the\n * two transaction grants the candidate receives. It owns no lifecycle —\n * request transforms, default omit, the extension chain, interceptors, the\n * official cache, raw SQL, transactions, arrays, observers and introspection\n * stay with their current owners, and this route is reached only through the\n * ordinary `PendingOperation` those owners already drive.\n *\n * It is NOT public: nothing here is exported from the package entry. Since the\n * C-01 cutover `VibORM`'s constructor builds it for every client, so it is the\n * ONE operation owner rather than a selectable alternative.\n */\n\nimport { officialCacheRuntime } from \"@cache/capability\";\nimport type { Operations } from \"@client/types\";\nimport type { AnyDriver, QueryExecutionContext } from \"@drivers/exports\";\nimport { UnsupportedOperationError } from \"@errors\";\nimport type { Schema } from \"@schema/hydration\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { Sql } from \"@sql\";\nimport type { CacheResultCodec } from \"../../cache-flow\";\nimport type { PreparedBatchOperation } from \"../../types\";\nimport { createCommandEngine, type PreparedOperation } from \"../commands\";\nimport type { WriteOutcomeSeam } from \"../shared/operation-context\";\nimport type { CallRows } from \"../shared/row-scope\";\nimport type { ResolvedSchemaViews } from \"../shared/schema\";\n\n/** What the existing pending-operation lifecycle knows when it executes. */\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/** One client operation's facts, answered by the candidate. */\nexport interface RoutedCandidateOperation {\n /**\n * The payload this operation runs: the candidate's ONE admission of the\n * client-prepared input (post request transform, post default omit). The\n * same object the statements are built from, so the interceptor's `input`\n * and the cache key describe the query that actually runs.\n */\n readonly preparedArgs: Record<string, unknown>;\n /**\n * The ONE statement this operation compiles to, or `undefined` when it does\n * not compile to exactly one. A prepared read owns one and publishes it; a\n * write's fold is only reachable through the asynchronous\n * {@link RoutedCandidateOperation.prepareBatch}, which publishes a package of\n * driver-prepared queries rather than an `Sql`.\n */\n buildStatement(): Sql | undefined;\n cacheResultCodec(): CacheResultCodec;\n /**\n * The prepared package when this operation prepares to it synchronously —\n * a read, whose preparation reaches no driver. It is the SAME package\n * {@link RoutedCandidateOperation.prepareBatch} publishes, so the one query\n * an array member dispatches and the parser that reads its result come from\n * one preparation.\n */\n prepareSingle(\n context: QueryExecutionContext\n ): PreparedBatchOperation<unknown> | undefined;\n prepareBatch(\n context: QueryExecutionContext\n ): Promise<PreparedBatchOperation<unknown> | undefined>;\n execute<T>(execution: RoutedOperationExecution): Promise<T>;\n}\n\n/** The client-scoped route a query engine consults instead of its executor. */\nexport interface ClientOperationRoute {\n operation(\n model: AnyModel,\n requestedOperation: string,\n args: Record<string, unknown>,\n rows?: CallRows\n ): RoutedCandidateOperation;\n}\n\n/** This operation's write-outcome seam, and whether it has already spoken. */\ninterface RouteWriteOutcome {\n published: boolean;\n readonly seam: WriteOutcomeSeam;\n}\n\n/**\n * Hand the candidate the client's own cache-invalidation rail.\n *\n * The durable phase of a write is a TRANSPORT fact — a segment acknowledged, or\n * a dispatch whose rollback the driver cannot prove — so the transport states\n * it, at the point it learns it, through this seam. The route reads no such\n * fact back out of a published error: `recordSeriesProgress` reports a record\n * series and nothing else (`g4/regression/note.md` \"Seam round\").\n */\nfunction routeWriteOutcome(\n execution: RoutedOperationExecution\n): RouteWriteOutcome | undefined {\n const { committedWriteSegment, writeMayBeVisible } = execution;\n if (!(committedWriteSegment || writeMayBeVisible)) return undefined;\n const outcome: RouteWriteOutcome = {\n published: false,\n seam: {\n committedSegment: async () => {\n outcome.published = true;\n if (committedWriteSegment) await committedWriteSegment();\n },\n mayBeVisible: async () => {\n outcome.published = true;\n if (writeMayBeVisible) await writeMayBeVisible();\n },\n },\n };\n return outcome;\n}\n\nclass RoutedOperation implements RoutedCandidateOperation {\n readonly #factoryDriver: AnyDriver;\n readonly #modelName: string;\n readonly #requestedOperation: string;\n readonly #prepared: PreparedOperation;\n #codec: CacheResultCodec | undefined;\n\n constructor(\n factoryDriver: AnyDriver,\n modelName: string,\n requestedOperation: string,\n prepared: PreparedOperation\n ) {\n this.#factoryDriver = factoryDriver;\n this.#modelName = modelName;\n this.#requestedOperation = requestedOperation;\n this.#prepared = prepared;\n }\n\n get preparedArgs(): Record<string, unknown> {\n return this.#prepared.args;\n }\n\n buildStatement(): Sql | undefined {\n return this.#prepared.read?.statement;\n }\n\n cacheResultCodec(): CacheResultCodec {\n // KEPT as a capability boundary (N4, plan §4). It alone owns \"the\n // cache layer asked this engine to encode a verb this engine\n // publishes no prepared read for\" — a boundary between two\n // independently-maintained vocabularies in two layers:\n // `CACHEABLE_OPERATIONS` (`query-engine/cache-flow.ts`, nine names,\n // including both `…OrThrow` variants) and the engine's own\n // `READ_OPERATIONS` (`shared/schema.ts`, seven), reconciled today\n // only by the `…OrThrow` normalization `baseOperation`\n // (`query-engine/routed-operations.ts`) states. No type\n // ties them and no single upstream owner establishes the fact, so an\n // assertion here would establish a missing fact rather than state an\n // established one (ELEGANCE §5). The class stays public\n // (`UnsupportedOperationError`) because this seam\n // (`RoutedCandidateOperation`) is consumed outside raptor3.\n const read = this.#prepared.read;\n if (!read)\n throw new UnsupportedOperationError(\n `Cannot cache '${this.#requestedOperation}' on model '${this.#modelName}': the operation has no readable result.`,\n {\n meta: {\n model: this.#modelName,\n operation: this.#requestedOperation,\n },\n }\n );\n return (this.#codec ??= officialCacheRuntime().cacheCodec(\n read,\n this.#requestedOperation\n ));\n }\n\n prepareSingle(\n context: QueryExecutionContext\n ): PreparedBatchOperation<unknown> | undefined {\n return this.#prepared.prepareSingle(context);\n }\n\n prepareBatch(\n context: QueryExecutionContext\n ): Promise<PreparedBatchOperation<unknown> | undefined> {\n return this.#prepared.prepareBatch(context);\n }\n\n // Not `async`: the candidate's promise is handed back as it is. An async\n // function adopts a returned promise a microtask later, so a refusal thrown\n // before any I/O (V8003) sat rejected with no handler in between, which\n // workerd under nodejs_compat reports as an unhandled rejection.\n execute<T>(execution: RoutedOperationExecution): Promise<T> {\n try {\n const outcome = execution.isWrite\n ? routeWriteOutcome(execution)\n : undefined;\n if (outcome)\n return runWriteCandidate<T>(\n this.#prepared,\n execution,\n this.#factoryDriver,\n outcome\n );\n return runCandidate(\n this.#prepared,\n execution,\n this.#factoryDriver,\n undefined\n ) as Promise<T>;\n } catch (error) {\n return Promise.reject(error);\n }\n }\n}\n\n/**\n * Create the candidate route for one client lineage. The candidate engine is\n * factory-bound to that client's root driver, so any other driver reaching an\n * operation is a scope an existing owner opened — which is exactly the binding\n * decision below.\n *\n * `resolved` is the client's own already-composed topology index and schema\n * registry, handed over by identity: the candidate hydrates, validates and\n * registers nothing a second time (note.md B-3).\n */\nexport function createCandidateRoute(\n schema: Schema,\n factoryDriver: AnyDriver,\n resolved?: ResolvedSchemaViews\n): ClientOperationRoute {\n const engine = createCommandEngine({\n schema,\n driver: factoryDriver,\n resolved,\n });\n return {\n operation(\n model: AnyModel,\n requestedOperation: string,\n args: Record<string, unknown>,\n rows?: CallRows\n ): RoutedCandidateOperation {\n const modelName = model[\"~\"].names.ts ?? \"unknown\";\n const operation = requestedOperation as Operations;\n // One prepared handle per client operation. Admission and the prepared\n // read stay lazy inside it (LX-01); every consumer below reads the same\n // construction, so nothing is admitted or projected twice.\n return new RoutedOperation(\n factoryDriver,\n modelName,\n requestedOperation,\n engine.prepare(modelName, operation, args, rows)\n );\n },\n };\n}\n\nasync function runWriteCandidate<T>(\n prepared: PreparedOperation,\n execution: RoutedOperationExecution,\n factoryDriver: AnyDriver,\n outcome: RouteWriteOutcome\n): Promise<T> {\n const value = await runCandidate(\n prepared,\n execution,\n factoryDriver,\n outcome.seam\n );\n // A transport that never separated commit from success — every direct\n // statement and every borrowed scope — leaves the operation's own success as\n // the only durable fact there is. That is the arm the shipped write-outcome\n // rail keeps for itself, on the same condition (`extensions/query.ts:286-293`,\n // `publishedDirectUnits === 0`).\n if (!outcome.published && execution.committedWriteSegment)\n await execution.committedWriteSegment();\n return value as T;\n}\n\n/**\n * Run one operation on the driver its owner selected.\n *\n * - root: no binding; the candidate owns its standalone envelope.\n * - an existing array owner's sequential fallback (`driverOverride`): the exact\n * borrowed driver and NO grant — the array owner's transaction is the unit,\n * exactly as the shipped `runLinearOn` path leaves it, so the candidate opens\n * no scope and a failing statement poisons the array's scope.\n * - inside `$transaction(callback)` (the engine is bound to a transaction\n * driver): the caller opened no scope for this operation, so the route\n * TRANSFERS the right to open one. The candidate then applies the same\n * envelope rule it applies everywhere — a statement-atomic write runs\n * directly on the caller's transaction driver (poisoning it on failure,\n * exactly as the shipped `runStatementAtomic` path does), a multi-statement\n * one opens exactly one nested region and rolls back only its own work. The\n * second grant is member isolation inside whichever of those two scopes is\n * current.\n *\n * The route decides WHICH SITUATION it is in and states it; it never decides\n * whether an envelope is needed. `writeOutcome` is not a fourth situation: it\n * is the client's cache-invalidation rail, carried to the transport that is\n * the only thing able to say when a write became durable.\n */\nfunction runCandidate(\n prepared: PreparedOperation,\n execution: RoutedOperationExecution,\n factoryDriver: AnyDriver,\n writeOutcome: WriteOutcomeSeam | undefined\n): Promise<unknown> {\n const { context, driverOverride, engineDriver } = execution;\n if (driverOverride) {\n return prepared.execute(\n { driver: driverOverride, kind: \"borrowed-transaction\", writeOutcome },\n context\n );\n }\n if (engineDriver === factoryDriver)\n return prepared.execute(\n writeOutcome ? { kind: \"standalone\", writeOutcome } : undefined,\n context\n );\n return prepared.execute(\n {\n driver: engineDriver,\n kind: \"borrowed-transaction\",\n memberRollback: (execute, scoped) =>\n engineDriver.withTransaction(execute, undefined, scoped),\n operationRegion: (execute, scoped) =>\n engineDriver.withTransaction(execute, undefined, scoped),\n writeOutcome,\n },\n context\n );\n}\n","import type {\n QueryInterceptorExecutionControl,\n TransactionWriteOutcomes,\n WriteOutcome,\n WriteOutcomeNotifications,\n} from \"./query\";\n\nexport interface ArrayDeferred<Value> {\n readonly promise: Promise<Value>;\n reject(reason: unknown): void;\n resolve(value: Value): void;\n}\n\n/** Extension-only state shared by native and fallback array coordination. */\nexport interface ArrayAdmissionSlot {\n admitted: boolean;\n admissionFailures?: unknown[];\n readonly child: ArrayDeferred<unknown>;\n certainty?: WriteOutcome[\"certainty\"];\n notifications?: WriteOutcomeNotifications;\n observation?: ArrayDeferred<unknown>;\n query?: Promise<unknown>;\n}\n\ntype StartArrayQuery<Slot extends ArrayAdmissionSlot> = (\n slot: Slot,\n child: (notifications?: WriteOutcomeNotifications) => Promise<unknown>,\n control: QueryInterceptorExecutionControl\n) => Promise<unknown>;\n\n/** Create one privately observed result rail for array admission. */\nexport function createArrayDeferred<Value>(): ArrayDeferred<Value> {\n let settled = false;\n // Promise executors run synchronously; TypeScript does not model that guarantee.\n let rejectPromise!: (reason?: unknown) => void;\n let resolvePromise!: (value: Value | PromiseLike<Value>) => void;\n const promise = new Promise<Value>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n promise.catch(() => undefined);\n return {\n promise,\n reject(reason) {\n if (settled) return;\n settled = true;\n rejectPromise(reason);\n },\n resolve(value) {\n if (settled) return;\n settled = true;\n resolvePromise(value);\n },\n };\n}\n\n/**\n * Start every query onion and release the array only after every member has\n * reached its authoritative child. Failures are returned in stable order so\n * the client keeps ownership of its public transaction error composition.\n */\nexport async function admitArrayQueries<Slot extends ArrayAdmissionSlot>(\n slots: readonly Slot[],\n outcomes: TransactionWriteOutcomes,\n start: StartArrayQuery<Slot>\n): Promise<readonly unknown[] | undefined> {\n let firstFailure: unknown;\n let hasFailure = false;\n let remaining = slots.length;\n const signal = createArrayDeferred<void>();\n if (remaining === 0) signal.resolve();\n\n for (const slot of slots) {\n const reportAdmissionFailure = (failure: unknown): void => {\n const failures = slot.admissionFailures;\n if (failures === undefined) {\n slot.admissionFailures = [failure];\n } else if (!failures.includes(failure)) {\n failures.push(failure);\n }\n if (hasFailure) return;\n hasFailure = true;\n firstFailure = failure;\n signal.reject(failure);\n };\n let query: Promise<unknown>;\n try {\n query = start(\n slot,\n (notifications) => {\n slot.notifications = notifications;\n if (!slot.admitted) {\n slot.admitted = true;\n remaining -= 1;\n if (remaining === 0) signal.resolve();\n }\n return slot.child.promise;\n },\n {\n reportAdmissionFailure,\n readCommitCertainty: () => slot.certainty,\n }\n );\n } catch (error) {\n reportAdmissionFailure(error);\n query = Promise.reject(error);\n }\n slot.query = query;\n if (slot.observation !== undefined) {\n query\n .then(slot.observation.resolve, slot.observation.reject)\n .catch(() => undefined);\n }\n query.catch(reportAdmissionFailure);\n }\n\n try {\n await signal.promise;\n await Promise.resolve();\n if (hasFailure) throw firstFailure;\n return undefined;\n } catch (fallback) {\n outcomes.discardAll();\n for (const slot of slots) slot.child.reject(fallback);\n await Promise.allSettled(slots.map(readArrayQuery));\n const reported: unknown[] = [];\n for (const slot of slots) {\n for (const failure of slot.admissionFailures ?? []) {\n if (!reported.includes(failure)) reported.push(failure);\n }\n }\n return reported;\n }\n}\n\n/** Read the public query onion, or its authoritative child before attachment. */\nexport function readArrayQuery(slot: ArrayAdmissionSlot): Promise<unknown> {\n return slot.query ?? slot.child.promise;\n}\n","import { attachCommitCertainty } from \"@drivers/driver-error-context\";\nimport { isVibORMError } from \"@errors\";\nimport type { WriteOutcome } from \"@extensions/query\";\n\nexport function markArrayCommitCertainty(\n error: unknown,\n certainty: WriteOutcome[\"certainty\"]\n): unknown {\n if (isVibORMError(error)) return attachCommitCertainty(error, certainty);\n if (!(error instanceof AggregateError)) return error;\n const marked = error.errors.map((failure) =>\n markArrayCommitCertainty(failure, certainty)\n );\n const cause =\n error.cause === error.errors[0]\n ? marked[0]\n : markArrayCommitCertainty(error.cause, certainty);\n return new AggregateError(marked, error.message, { cause });\n}\n\nexport function combineArrayFailures(\n primary: unknown,\n suppressed: readonly unknown[]\n): unknown {\n const distinct = suppressed.filter((failure) => failure !== primary);\n if (distinct.length === 0) return primary;\n return new AggregateError(\n [primary, ...distinct],\n \"Array transaction and operation post-work both failed.\",\n { cause: primary }\n );\n}\n","import type {\n AnyDriver,\n BatchQuery,\n QueryExecutionContext,\n QueryResult,\n} from \"@drivers/exports\";\nimport { assertNormalizedBatchResults } from \"@drivers/normalized-result\";\nimport type {\n BatchTransactionOptions,\n TransactionOptions,\n} from \"@drivers/shared/transaction-options\";\nimport { TransactionError } from \"@errors\";\nimport { attributeOperationBatchError } from \"@query-engine/batch-error-attribution\";\nimport type {\n TransactionOperationCapability,\n TransactionOperationOwner,\n} from \"@query-engine/transaction-operation\";\nimport type { PreparedBatchGuard } from \"@query-engine/types\";\n\nexport interface NativeBatchMember {\n readonly operation: TransactionOperationCapability;\n readonly owner: TransactionOperationOwner<TransactionOperationCapability>;\n}\n\nexport interface PreparedNativeBatch {\n readonly queries: BatchQuery[];\n readonly guards: PreparedBatchGuard[];\n readonly parsers: ((\n batchResults: QueryResult<unknown>[]\n ) => Promise<unknown>)[];\n}\n\n/** Prepare members in order into one native batch with per-member parsers. */\nexport async function prepareNativeBatch(\n members: readonly NativeBatchMember[],\n driver: AnyDriver\n): Promise<PreparedNativeBatch> {\n const queries: BatchQuery[] = [];\n const guards: PreparedBatchGuard[] = [];\n const parsers: PreparedNativeBatch[\"parsers\"] = [];\n for (const { operation, owner } of members) {\n const preparation = await owner.observeBatchPhase(\n operation,\n driver,\n async () => {\n const prepared = owner.prepare(operation, driver);\n if (prepared) return { kind: \"single\" as const, prepared };\n return {\n kind: \"batch\" as const,\n preparedBatch: await owner.prepareBatch(operation),\n };\n }\n );\n const start = queries.length;\n if (preparation.kind === \"single\") {\n queries.push(preparation.prepared);\n parsers.push((batchResults) =>\n owner.observeBatchPhase(operation, driver, () => {\n const result = batchResults[start];\n if (!result) throw missingOperationResult(driver, operation, owner);\n return owner.parseResult(operation, result);\n })\n );\n continue;\n }\n const { preparedBatch } = preparation;\n if (!preparedBatch) throw unbatchableArrayError(driver);\n const length = preparedBatch.queries.length;\n for (const query of preparedBatch.queries) queries.push(query);\n for (const guard of preparedBatch.guards ?? []) {\n guards.push({ ...guard, queryIndex: start + guard.queryIndex });\n }\n parsers.push((batchResults) =>\n owner.observeBatchPhase(operation, driver, () =>\n preparedBatch.parseResult(batchResults.slice(start, start + length))\n )\n );\n }\n return { queries, guards, parsers };\n}\n\nexport async function executeNativeBatch(\n driver: AnyDriver,\n queries: BatchQuery[],\n guards: PreparedBatchGuard[],\n options: TransactionOptions | BatchTransactionOptions | undefined,\n context: QueryExecutionContext,\n committed?: () => Promise<void>\n): Promise<QueryResult<unknown>[]> {\n if (queries.length === 0) return [];\n try {\n return await driver._executeBatch(\n queries,\n options as BatchTransactionOptions | undefined,\n context,\n committed\n );\n } catch (error) {\n throw await attributeOperationBatchError(error, guards, driver, queries);\n }\n}\n\nexport function assertNativeBatchResults(\n driver: AnyDriver,\n results: QueryResult<unknown>[],\n queryCount: number\n): void {\n assertNormalizedBatchResults(results, queryCount, {\n provider: driver.driverName,\n operation: \"$transaction([...])\",\n });\n}\n\nexport function assertAtomicArraySupport(driver: AnyDriver): void {\n if (driver.supportsTransactions || driver.supportsBatch) return;\n throw new TransactionError(\n `Driver \"${driver.driverName}\" supports neither transactions nor atomic batch execution.`,\n {\n meta: {\n driver: driver.driverName,\n method: \"$transaction([...])\",\n },\n }\n );\n}\n\nexport function unbatchableArrayError(driver: AnyDriver): TransactionError {\n return new TransactionError(\n `Driver \"${driver.driverName}\" does not support callback transactions and this transaction contains operations that cannot be batched atomically.`,\n {\n meta: {\n driver: driver.driverName,\n method: \"$transaction([...])\",\n },\n }\n );\n}\n\nexport function missingOperationResult(\n driver: AnyDriver,\n operation: TransactionOperationCapability,\n owner: TransactionOperationOwner<TransactionOperationCapability>\n): TransactionError {\n const operationName = owner.operation(operation);\n return new TransactionError(\n `Driver \"${driver.driverName}\" omitted the result for operation \"${operationName}\".`,\n {\n meta: {\n driver: driver.driverName,\n operation: operationName,\n },\n }\n );\n}\n","import { bindExecutionTransactionPhases } from \"@drivers/execution-context\";\nimport type {\n AnyDriver,\n QueryExecutionContext,\n QueryResult,\n} from \"@drivers/exports\";\nimport type {\n BatchTransactionOptions,\n TransactionOptions,\n} from \"@drivers/shared/transaction-options\";\nimport { InvalidTransactionInputError } from \"@errors\";\nimport { prewarmProtectedObservers } from \"@extensions/observation\";\nimport type { QueryEngine } from \"@query-engine/query-engine\";\nimport {\n type TransactionOperationCapability,\n transactionOperationOwner,\n} from \"@query-engine/transaction-operation\";\nimport {\n assertAtomicArraySupport,\n assertNativeBatchResults,\n executeNativeBatch,\n type NativeBatchMember,\n type PreparedNativeBatch,\n prepareNativeBatch,\n} from \"./array-transaction-native-batch\";\n\n/** The allocation-compatible array path used when no query handler compiled. */\nexport async function executeLegacyArrayTransaction(\n operations: TransactionOperationCapability[],\n engine: QueryEngine,\n options: TransactionOptions | BatchTransactionOptions | undefined,\n context: QueryExecutionContext,\n observeArrayLifecycle = false,\n reportCertainty?: (certainty: \"committed\" | \"may-have-committed\") => void\n): Promise<unknown[]> {\n const driver = engine.driver;\n const results: unknown[] = operations;\n if (!driver.supportsTransactions && driver.supportsBatch) {\n if (observeArrayLifecycle) {\n const observerReadiness = prewarmProtectedObservers(\n engine.extensionChain?.observe\n );\n if (observerReadiness !== undefined) await observerReadiness;\n return executeObservedNativeArray(\n operations,\n driver,\n options,\n context,\n reportCertainty\n );\n }\n for (const operation of operations) {\n transactionOperationOwner(operation).reserveWith(operation, driver);\n }\n const { queries, guards, parsers } = await prepareNativeBatch(\n batchMembers(operations),\n driver\n );\n const batchResults = await executeNativeBatch(\n driver,\n queries,\n guards,\n options,\n context\n );\n assertNativeBatchResults(driver, batchResults, queries.length);\n for (let index = 0; index < parsers.length; index += 1) {\n results[index] = await parsers[index]!(batchResults);\n }\n return results;\n }\n\n assertAtomicArraySupport(driver);\n if (observeArrayLifecycle) {\n return executeObservedFallbackArray(\n operations,\n engine,\n options,\n context,\n reportCertainty\n );\n }\n return driver.withTransaction(\n runInOrder(operations, results),\n options as TransactionOptions | undefined,\n context\n );\n}\n\nfunction batchMembers(\n operations: readonly TransactionOperationCapability[]\n): NativeBatchMember[] {\n return operations.map((operation) => ({\n operation,\n owner: transactionOperationOwner(operation),\n }));\n}\n\nfunction runInOrder(\n operations: readonly TransactionOperationCapability[],\n results: unknown[]\n): (transactionDriver: AnyDriver) => Promise<unknown[]> {\n return async (transactionDriver) => {\n for (let index = 0; index < operations.length; index += 1) {\n const operation = operations[index]!;\n results[index] = await transactionOperationOwner(operation).executeWith(\n operation,\n transactionDriver\n );\n }\n return results;\n };\n}\n\ninterface ObservedNativeMember {\n readonly application: Promise<unknown>;\n readonly rejectChild: (reason?: unknown) => void;\n readonly resolveChild: (value: unknown) => void;\n settled: boolean;\n certainty?: \"committed\" | \"may-have-committed\";\n}\n\nasync function executeObservedNativeArray(\n operations: TransactionOperationCapability[],\n driver: AnyDriver,\n options: TransactionOptions | BatchTransactionOptions | undefined,\n context: QueryExecutionContext,\n reportCertainty:\n | ((certainty: \"committed\" | \"may-have-committed\") => void)\n | undefined\n): Promise<unknown[]> {\n const results: unknown[] = operations;\n const observations: ObservedNativeMember[] = [];\n try {\n for (const operation of operations) {\n observations.push(startNativeObservation(operation));\n }\n } catch (error) {\n rejectObservedMembers(observations, error);\n throw error;\n }\n let batch: PreparedNativeBatch;\n try {\n for (const operation of operations) {\n transactionOperationOwner(operation).reserveWith(operation, driver);\n }\n batch = await prepareNativeBatch(batchMembers(operations), driver);\n } catch (error) {\n rejectObservedMembers(observations, error);\n throw error;\n }\n const { queries, guards, parsers } = batch;\n\n let batchResults: QueryResult<unknown>[];\n try {\n batchResults = await executeNativeBatch(\n driver,\n queries,\n guards,\n options,\n context\n );\n } catch (error) {\n setObservedCertainty(observations, \"may-have-committed\");\n reportCertainty?.(\"may-have-committed\");\n rejectObservedMembers(observations, error);\n throw error;\n }\n\n setObservedCertainty(observations, \"committed\");\n reportCertainty?.(\"committed\");\n try {\n assertNativeBatchResults(driver, batchResults, queries.length);\n for (let index = 0; index < parsers.length; index += 1) {\n const value = await parsers[index]!(batchResults);\n const observation = observations[index]!;\n resolveObservedMember(observation, value);\n results[index] = await observation.application;\n }\n return results;\n } catch (error) {\n rejectObservedMembers(observations, error);\n throw error;\n }\n}\n\nasync function executeObservedFallbackArray(\n operations: TransactionOperationCapability[],\n engine: QueryEngine,\n options: TransactionOptions | BatchTransactionOptions | undefined,\n context: QueryExecutionContext,\n reportCertainty:\n | ((certainty: \"committed\" | \"may-have-committed\") => void)\n | undefined\n): Promise<unknown[]> {\n const results: unknown[] = operations;\n const transactionState: { phase: \"pending\" | \"ready\" | \"committed\" } = {\n phase: \"pending\",\n };\n const isNested = engine.transactionWriteOutcomes !== undefined;\n const transactionContext = isNested\n ? context\n : bindExecutionTransactionPhases(context, {\n readyToCommit: () => {\n transactionState.phase = \"ready\";\n },\n committed: () => {\n transactionState.phase = \"committed\";\n },\n });\n try {\n const transactionResults = await engine.driver.withTransaction(\n runInOrder(operations, results),\n options as TransactionOptions | undefined,\n transactionContext\n );\n if (!isNested) reportCertainty?.(\"committed\");\n return transactionResults;\n } catch (error) {\n if (!isNested && transactionState.phase === \"committed\") {\n reportCertainty?.(\"committed\");\n } else if (!isNested && transactionState.phase === \"ready\") {\n reportCertainty?.(\"may-have-committed\");\n }\n throw error;\n }\n}\n\nfunction startNativeObservation(\n operation: TransactionOperationCapability\n): ObservedNativeMember {\n const owner = transactionOperationOwner(operation);\n if (!owner.hasObservation(operation))\n throw new InvalidTransactionInputError();\n let rejectChild: (reason?: unknown) => void = () => undefined;\n let resolveChild: (value: unknown) => void = () => undefined;\n const child = new Promise<unknown>((resolve, reject) => {\n resolveChild = resolve;\n rejectChild = reject;\n });\n let member: ObservedNativeMember;\n const application = owner.observe(\n operation,\n () => child,\n () =>\n member.certainty === undefined\n ? undefined\n : { commitCertainty: member.certainty }\n );\n member = {\n application,\n rejectChild,\n resolveChild,\n settled: false,\n };\n member.application.catch(() => undefined);\n return member;\n}\n\nfunction rejectObservedMember(\n member: ObservedNativeMember,\n failure: unknown\n): void {\n if (member.settled) return;\n member.settled = true;\n member.rejectChild(failure);\n}\n\nfunction resolveObservedMember(\n member: ObservedNativeMember,\n value: unknown\n): void {\n if (member.settled) return;\n member.settled = true;\n member.resolveChild(value);\n}\n\nfunction rejectObservedMembers(\n observations: readonly ObservedNativeMember[],\n failure: unknown\n): void {\n for (const observation of observations) {\n rejectObservedMember(observation, failure);\n }\n}\n\nfunction setObservedCertainty(\n observations: readonly ObservedNativeMember[],\n certainty: \"committed\" | \"may-have-committed\"\n): void {\n for (const observation of observations) observation.certainty = certainty;\n}\n","import type {\n AnyDriver,\n QueryExecutionContext,\n QueryResult,\n} from \"@drivers/exports\";\nimport type {\n BatchTransactionOptions,\n TransactionOptions,\n} from \"@drivers/shared/transaction-options\";\nimport {\n type ArrayAdmissionSlot,\n readArrayQuery,\n} from \"@extensions/array-admission\";\nimport type { TransactionWriteOutcomes, WriteOutcome } from \"@extensions/query\";\nimport {\n decomposeQueryCoordinationFailure,\n decomposeWriteOutcomePublicationFailure,\n} from \"@extensions/query\";\nimport type {\n TransactionOperationCapability,\n TransactionOperationOwner,\n} from \"@query-engine/transaction-operation\";\nimport {\n combineArrayFailures,\n markArrayCommitCertainty,\n} from \"./array-transaction-failures\";\nimport {\n assertNativeBatchResults,\n executeNativeBatch,\n type PreparedNativeBatch,\n prepareNativeBatch,\n} from \"./array-transaction-native-batch\";\n\nexport interface NativeArraySlot extends ArrayAdmissionSlot {\n readonly operation: TransactionOperationCapability;\n readonly owner: TransactionOperationOwner<TransactionOperationCapability>;\n}\n\nexport async function executeInterceptedNativeArray(\n slots: readonly NativeArraySlot[],\n outcomes: TransactionWriteOutcomes,\n driver: AnyDriver,\n options: TransactionOptions | BatchTransactionOptions | undefined,\n context: QueryExecutionContext,\n reportCertainty?: (certainty: WriteOutcome[\"certainty\"]) => void\n): Promise<unknown[]> {\n let batch: PreparedNativeBatch;\n try {\n batch = await prepareNativeBatch(slots, driver);\n } catch (error) {\n outcomes.discardAll();\n throw await rejectAndCombine(slots, error);\n }\n const { queries, guards, parsers } = batch;\n\n let committed = false;\n const commitFailures: unknown[] = [];\n const confirmCommit = async (): Promise<void> => {\n if (committed) return;\n committed = true;\n reportCertainty?.(\"committed\");\n for (const slot of slots) slot.certainty = \"committed\";\n commitFailures.push(\n ...(await publishNativeOutcome(slots, outcomes, \"committed\"))\n );\n };\n\n let batchResults: QueryResult<unknown>[];\n try {\n batchResults = await executeNativeBatch(\n driver,\n queries,\n guards,\n options,\n context,\n driver.supportsOrderedCommittedSegments ? confirmCommit : undefined\n );\n } catch (error) {\n if (committed) {\n throw await closeCommittedFailure(slots, error, commitFailures);\n }\n reportCertainty?.(\"may-have-committed\");\n throw await closeDispatchedFailure(slots, outcomes, error);\n }\n await confirmCommit();\n try {\n assertNativeBatchResults(driver, batchResults, queries.length);\n } catch (error) {\n throw await closeCommittedFailure(slots, error, commitFailures);\n }\n\n const results: unknown[] = new Array(slots.length);\n for (let index = 0; index < slots.length; index += 1) {\n const slot = slots[index]!;\n try {\n slot.child.resolve(await parsers[index]!(batchResults));\n } catch (error) {\n slot.child.reject(markArrayCommitCertainty(error, \"committed\"));\n }\n }\n const queryOutcomes = await Promise.allSettled(slots.map(readArrayQuery));\n const queryFailures: unknown[] = [];\n for (let index = 0; index < queryOutcomes.length; index += 1) {\n const outcome = queryOutcomes[index]!;\n if (outcome.status === \"fulfilled\") results[index] = outcome.value;\n else {\n for (const failure of queryFailureParts(outcome.reason)) {\n queryFailures.push(failure);\n }\n }\n }\n const failures = [\n ...queryFailures,\n ...commitFailures.map((failure) =>\n markArrayCommitCertainty(failure, \"committed\")\n ),\n ];\n if (failures.length > 0) {\n throw combineArrayFailures(failures[0], failures.slice(1));\n }\n return results;\n}\n\nasync function closeDispatchedFailure(\n slots: readonly NativeArraySlot[],\n outcomes: TransactionWriteOutcomes,\n failure: unknown\n): Promise<unknown> {\n const primary = markArrayCommitCertainty(failure, \"may-have-committed\");\n for (const slot of slots) slot.certainty = \"may-have-committed\";\n const commitFailures = await publishNativeOutcome(\n slots,\n outcomes,\n \"may-have-committed\"\n );\n return rejectAndCombine(slots, primary, commitFailures);\n}\n\nasync function closeCommittedFailure(\n slots: readonly NativeArraySlot[],\n failure: unknown,\n commitFailures: readonly unknown[]\n): Promise<unknown> {\n for (const slot of slots) slot.certainty = \"committed\";\n return rejectAndCombine(\n slots,\n markArrayCommitCertainty(failure, \"committed\"),\n commitFailures\n );\n}\n\n/** Reject every child with the primary failure and fold in what settled. */\nasync function rejectAndCombine(\n slots: readonly NativeArraySlot[],\n primary: unknown,\n extra: readonly unknown[] = []\n): Promise<unknown> {\n for (const slot of slots) slot.child.reject(primary);\n const suppressed: unknown[] = [];\n for (const outcome of await Promise.allSettled(slots.map(readArrayQuery))) {\n if (outcome.status === \"rejected\") {\n suppressed.push(...queryFailureParts(outcome.reason));\n }\n }\n return combineArrayFailures(primary, [...suppressed, ...extra]);\n}\n\nasync function publishNativeOutcome(\n slots: readonly NativeArraySlot[],\n outcomes: TransactionWriteOutcomes,\n certainty: WriteOutcome[\"certainty\"]\n): Promise<unknown[]> {\n const failures: unknown[] = [];\n for (const slot of slots) {\n if (!slot.owner.isWrite(slot.operation)) {\n continue;\n }\n try {\n if (certainty === \"committed\") {\n await slot.notifications?.committed();\n } else {\n await slot.notifications?.mayHaveCommitted();\n }\n } catch (error) {\n failures.push(error);\n }\n }\n try {\n await outcomes.publish(certainty);\n } catch (error) {\n for (const failure of decomposeWriteOutcomePublicationFailure(error)) {\n failures.push(failure);\n }\n }\n return failures;\n}\n\nfunction queryFailureParts(failure: unknown): readonly unknown[] {\n const coordination = decomposeQueryCoordinationFailure(failure);\n if (coordination === undefined) return [failure];\n return [coordination.child, ...coordination.postWork];\n}\n","import { attachCommitCertainty } from \"@drivers/driver-error-context\";\nimport { bindExecutionTransactionPhases } from \"@drivers/execution-context\";\nimport type { AnyDriver, QueryExecutionContext } from \"@drivers/exports\";\nimport type {\n BatchTransactionOptions,\n TransactionOptions,\n} from \"@drivers/shared/transaction-options\";\nimport {\n InvalidTransactionInputError,\n isVibORMError,\n PendingOperationError,\n retainWriteOutcomeFailure,\n} from \"@errors\";\nimport {\n admitArrayQueries,\n createArrayDeferred,\n readArrayQuery,\n} from \"@extensions/array-admission\";\nimport {\n prewarmProtectedObservers,\n runProtectedObservers,\n} from \"@extensions/observation\";\nimport {\n decomposeQueryCoordinationFailure,\n TransactionWriteOutcomes,\n type WriteOutcome,\n} from \"@extensions/query\";\nimport type { QueryEngine } from \"@query-engine/query-engine\";\nimport {\n readTransactionOperation,\n type TransactionOperationCapability,\n transactionOperationOwner,\n} from \"@query-engine/transaction-operation\";\nimport { combineArrayFailures } from \"./array-transaction-failures\";\nimport { executeLegacyArrayTransaction } from \"./array-transaction-legacy\";\nimport {\n executeInterceptedNativeArray,\n type NativeArraySlot,\n} from \"./array-transaction-native\";\nimport { assertAtomicArraySupport } from \"./array-transaction-native-batch\";\n\ntype ArraySlot = NativeArraySlot;\n\ninterface ArrayObservationState {\n certainty?: \"committed\" | \"may-have-committed\";\n}\n\n/**\n * Execute one root or nested array transaction. The first arm is the extracted\n * legacy path: synchronous request preparation settles for the complete array\n * before selection; when no member then needs query or write-outcome\n * coordination, execution allocates no slot, deferred result, outcome\n * collector, or admission callback.\n */\nexport function executeArrayTransaction(\n candidates: readonly unknown[],\n engine: QueryEngine,\n options: TransactionOptions | BatchTransactionOptions | undefined,\n context: QueryExecutionContext\n): Promise<unknown[]> {\n let operations: unknown[] | undefined;\n let snapshotFailure: unknown;\n try {\n const length = candidates.length;\n if (\n typeof length !== \"number\" ||\n !Number.isInteger(length) ||\n length < 0 ||\n length > 0xff_ff_ff_ff\n ) {\n throw new InvalidTransactionInputError();\n }\n operations = new Array<unknown>(length);\n for (let index = 0; index < length; index += 1) {\n operations[index] = candidates[index];\n }\n } catch (error) {\n operations = undefined;\n snapshotFailure = error;\n }\n\n const observers = engine.extensionChain?.observe;\n if (operations === undefined) {\n if (observers === undefined || observers.length === 0) {\n throw snapshotFailure;\n }\n return runProtectedObservers(\n { kind: \"batch\", operation: \"$transaction([...])\" },\n observers,\n () => {\n throw snapshotFailure;\n }\n );\n }\n if (observers === undefined || observers.length === 0) {\n assertOwnedOperations(operations, engine);\n if (operations.length === 0) return Promise.resolve(operations);\n prepareRequestAdmissions(operations, engine);\n return canRequireInterceptedArray(engine) &&\n requiresInterceptedArray(operations)\n ? executeInterceptedArray(operations, engine, options, context)\n : executeLegacyArrayTransaction(operations, engine, options, context);\n }\n const observation: ArrayObservationState = {};\n return runProtectedObservers(\n { kind: \"batch\", operation: \"$transaction([...])\" },\n observers,\n () => {\n assertOwnedOperations(operations, engine);\n if (operations.length === 0) return Promise.resolve(operations);\n return canRequireInterceptedArray(engine) &&\n requiresInterceptedArray(operations)\n ? executeInterceptedArray(\n operations,\n engine,\n options,\n context,\n observation\n )\n : executeLegacyArrayTransaction(\n operations,\n engine,\n options,\n context,\n true,\n (certainty) => {\n observation.certainty = certainty;\n }\n );\n },\n () =>\n observation.certainty === undefined\n ? undefined\n : { commitCertainty: observation.certainty }\n );\n}\n\n/**\n * Settle synchronous request work, control admission included, for every\n * member before any provider effect.\n */\nfunction prepareRequestAdmissions(\n operations: readonly TransactionOperationCapability[],\n _engine: QueryEngine\n): void {\n for (const operation of operations) {\n transactionOperationOwner(operation).prepareAdmission(operation);\n }\n for (const operation of operations) {\n transactionOperationOwner(operation).prepareAdmission(operation, \"plan\");\n }\n}\n\nfunction requiresInterceptedArray(\n operations: readonly TransactionOperationCapability[]\n): boolean {\n for (const operation of operations) {\n const owner = transactionOperationOwner(operation);\n if (owner.requiresInterception(operation)) return true;\n }\n return false;\n}\n\nfunction canRequireInterceptedArray(engine: QueryEngine): boolean {\n const chain = engine.extensionChain;\n return (\n chain !== undefined &&\n (chain.hasRequestHandlers || chain.hasQueryHandlers || chain.hasCache)\n );\n}\n\nfunction assertOwnedOperations(\n candidates: unknown[],\n engine: QueryEngine\n): asserts candidates is TransactionOperationCapability[] {\n for (const candidate of candidates) {\n if (candidate === null || typeof candidate !== \"object\") {\n throw new InvalidTransactionInputError();\n }\n const owner = readTransactionOperation(candidate);\n if (owner === undefined) throw new InvalidTransactionInputError();\n if (owner.clientId(candidate) !== engine.clientId) {\n throw PendingOperationError.clientMismatch(\n owner.model(candidate),\n owner.operation(candidate)\n );\n }\n if (owner.scopeId(candidate) !== engine.scopeId) {\n throw PendingOperationError.scopeMismatch(\n owner.model(candidate),\n owner.operation(candidate)\n );\n }\n }\n}\n\nasync function executeInterceptedArray(\n operations: readonly TransactionOperationCapability[],\n engine: QueryEngine,\n options: TransactionOptions | BatchTransactionOptions | undefined,\n context: QueryExecutionContext,\n observation?: ArrayObservationState\n): Promise<unknown[]> {\n const driver = engine.driver;\n assertAtomicArraySupport(driver);\n\n const observerReadiness = prewarmProtectedObservers(\n engine.extensionChain?.observe\n );\n if (observerReadiness !== undefined) await observerReadiness;\n const outcomes = new TransactionWriteOutcomes();\n const slots = operations.map(createArraySlot);\n startArrayOperationObservers(slots, engine);\n try {\n for (const slot of slots) {\n slot.owner.reserveWith(slot.operation, driver);\n }\n for (const slot of slots) {\n await slot.owner.observeBatchPhase(slot.operation, driver, () =>\n slot.owner.prepareAdmission(slot.operation)\n );\n }\n for (const slot of slots) {\n await slot.owner.observeBatchPhase(slot.operation, driver, () =>\n slot.owner.prepareAdmission(slot.operation, \"plan\")\n );\n }\n } catch (error) {\n closeArrayOperationObservers(slots, error);\n throw error;\n }\n for (const slot of slots) {\n slot.owner.stagePackageWriteOutcomes(slot.operation, outcomes);\n }\n const admissionFailures = await admitArrayQueries(\n slots,\n outcomes,\n (slot, child, control) =>\n slot.owner.startInterception(slot.operation, child, outcomes, control)\n );\n if (admissionFailures !== undefined) {\n throw combineArrayFailures(\n admissionFailures[0],\n admissionFailures.slice(1)\n );\n }\n\n if (!driver.supportsTransactions && driver.supportsBatch) {\n return executeInterceptedNativeArray(\n slots,\n outcomes,\n driver,\n options,\n context,\n (certainty) => {\n if (observation) observation.certainty = certainty;\n }\n );\n }\n return executeInterceptedFallback(\n slots,\n outcomes,\n engine,\n options,\n context,\n observation\n );\n}\n\nfunction createArraySlot(operation: TransactionOperationCapability): ArraySlot {\n return {\n operation,\n owner: transactionOperationOwner(operation),\n admitted: false,\n child: createArrayDeferred<unknown>(),\n };\n}\n\nfunction startArrayOperationObservers(\n slots: readonly ArraySlot[],\n engine: QueryEngine\n): void {\n const observers = engine.extensionChain?.observe;\n if (observers === undefined || observers.length === 0) return;\n for (const slot of slots) {\n const observation = createArrayDeferred<unknown>();\n slot.observation = observation;\n if (!slot.owner.hasObservation(slot.operation))\n throw new InvalidTransactionInputError();\n slot.owner\n .observe(\n slot.operation,\n () => observation.promise,\n () =>\n slot.certainty === undefined\n ? undefined\n : { commitCertainty: slot.certainty }\n )\n .catch(() => undefined);\n }\n}\n\nfunction closeArrayOperationObservers(\n slots: readonly ArraySlot[],\n failure: unknown\n): void {\n for (const slot of slots) slot.observation?.reject(failure);\n}\n\n/**\n * Run one transaction whose write outcomes this scope collects. A root scope\n * tracks the commit phases, so a failure after COMMIT was sent still reports\n * its certainty and publishes what may have committed; a savepoint promotes\n * its outcomes into the parent collector, which owns that decision.\n */\nexport async function runOutcomeTransaction<T>(\n driver: AnyDriver,\n outcomes: TransactionWriteOutcomes,\n parentOutcomes: TransactionWriteOutcomes | undefined,\n options: TransactionOptions | undefined,\n context: QueryExecutionContext,\n body: (driver: AnyDriver) => Promise<T>,\n report?: (certainty: WriteOutcome[\"certainty\"]) => void,\n mapFailure: (error: unknown) => unknown = (error) => error\n): Promise<T> {\n let phase: \"ready\" | \"committed\" | undefined;\n let result: T;\n try {\n result = await driver.withTransaction(\n body,\n options,\n parentOutcomes\n ? context\n : bindExecutionTransactionPhases(context, {\n readyToCommit: () => {\n phase = \"ready\";\n },\n committed: () => {\n phase = \"committed\";\n },\n })\n );\n } catch (error) {\n const failure = mapFailure(error);\n if (phase === undefined) {\n outcomes.discardAll();\n throw failure;\n }\n const certainty = phase === \"ready\" ? \"may-have-committed\" : phase;\n report?.(certainty);\n const primary = isVibORMError(failure)\n ? attachCommitCertainty(failure, certainty)\n : failure;\n try {\n await outcomes.publish(certainty);\n } catch (outcomeFailure) {\n throw retainWriteOutcomeFailure(primary, outcomeFailure);\n }\n throw primary;\n }\n if (parentOutcomes) outcomes.promoteTo(parentOutcomes);\n else {\n report?.(\"committed\");\n await outcomes.publishCommitted();\n }\n return result;\n}\n\nfunction executeInterceptedFallback(\n slots: readonly ArraySlot[],\n outcomes: TransactionWriteOutcomes,\n engine: QueryEngine,\n options: TransactionOptions | BatchTransactionOptions | undefined,\n context: QueryExecutionContext,\n observation: ArrayObservationState | undefined\n): Promise<unknown[]> {\n const suppressedPostWork: unknown[] = [];\n return runOutcomeTransaction(\n engine.driver,\n outcomes,\n engine.transactionWriteOutcomes,\n options as TransactionOptions | undefined,\n context,\n async (transactionDriver) => {\n const values: unknown[] = [];\n for (let index = 0; index < slots.length; index += 1) {\n const slot = slots[index]!;\n startFallbackCore(slot, transactionDriver);\n try {\n values.push(await readArrayQuery(slot));\n } catch (error) {\n const firstFailure = decomposeQueryCoordinationFailure(error);\n const childFailure =\n firstFailure === undefined ? error : firstFailure.child;\n if (firstFailure) {\n for (const postWork of firstFailure.postWork) {\n suppressedPostWork.push(postWork);\n }\n }\n for (let later = index + 1; later < slots.length; later += 1) {\n slots[later]!.child.reject(childFailure);\n }\n const laterOutcomes = await Promise.allSettled(\n slots.slice(index + 1).map(readArrayQuery)\n );\n for (const outcome of laterOutcomes) {\n if (outcome.status !== \"rejected\") continue;\n const laterFailure = decomposeQueryCoordinationFailure(\n outcome.reason\n );\n if (laterFailure) {\n if (laterFailure.child !== childFailure) {\n suppressedPostWork.push(laterFailure.child);\n }\n for (const postWork of laterFailure.postWork) {\n suppressedPostWork.push(postWork);\n }\n } else if (outcome.reason !== childFailure) {\n suppressedPostWork.push(outcome.reason);\n }\n }\n throw childFailure;\n }\n }\n return values;\n },\n observation &&\n ((certainty) => {\n observation.certainty = certainty;\n }),\n (error) => combineArrayFailures(error, suppressedPostWork)\n );\n}\n\nfunction startFallbackCore(slot: ArraySlot, driver: AnyDriver): void {\n let core: Promise<unknown>;\n try {\n core = slot.owner.executeCore(slot.operation, driver, slot.notifications);\n } catch (error) {\n slot.child.reject(error);\n return;\n }\n core.then(slot.child.resolve, slot.child.reject);\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 { 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\nconst hasEntries = (value: Record<string, boolean>): boolean =>\n Object.keys(value).length > 0;\n\n/**\n * Build the model → default-omit lookup, or `undefined` when the client\n * configured nothing worth walking for. Keyed by model IDENTITY so a nested\n * relation resolves through its `ResolvedSlot` target without a name\n * round-trip.\n */\nexport const createClientOmitResolver = <S extends Record<string, AnyModel>>(\n schema: S,\n config: ClientOmitConfig<S>,\n relations: ResolvedRelationIndex\n): ClientOmitResolver | undefined => {\n const byModel = new Map<AnyModel, Record<string, boolean>>();\n for (const key of Object.keys(config)) {\n const model = Object.hasOwn(schema, key) ? schema[key] : undefined;\n const entry = config[key as keyof ClientOmitConfig<S>];\n // A config naming a model or field that does not exist is a typo the\n // resolver would otherwise carry silently. The official factory owns\n // structural exactness; this runtime boundary owns hostile JavaScript.\n if (!model) {\n throw new VibORMError(\n `Client 'omit' names model '${key}', which is not in the schema.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model: key } }\n );\n }\n if (!isPlainRecord(entry)) continue;\n const projectable = new Set(projectableScalarNames(model));\n const flags: Record<string, boolean> = {};\n for (const field of Object.keys(entry)) {\n if (!projectable.has(field)) {\n throw new VibORMError(\n `Client 'omit' names field '${field}' on model '${key}', which is not a readable scalar of that model.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model: key, field } }\n );\n }\n if (entry[field] === true) flags[field] = true;\n }\n if (hasEntries(flags)) byModel.set(model, flags);\n }\n if (byModel.size === 0) return undefined;\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 */\nconst PROJECTING_OPERATIONS: ReadonlySet<string> = new Set([\n \"findFirst\",\n \"findFirstOrThrow\",\n \"findMany\",\n \"findUnique\",\n \"findUniqueOrThrow\",\n \"create\",\n \"update\",\n \"upsert\",\n \"delete\",\n]);\n\n/** A bulk write already carrying a projection: the caller opted into rows. */\nconst bulkWriteProjects = (\n operation: string,\n args: Record<string, unknown>\n): boolean =>\n (operation === \"createMany\" ||\n operation === \"updateMany\" ||\n operation === \"deleteMany\") &&\n args.omit !== undefined;\n\n/**\n * Rewrite one payload so every projecting node carries the client defaults.\n * Returns the SAME object when nothing changed, so an unaffected query is not\n * copied.\n */\nexport const applyClientOmit = (\n model: AnyModel,\n operation: Operations | string,\n args: Record<string, unknown>,\n resolve: ClientOmitResolver\n): Record<string, unknown> => {\n const projects =\n PROJECTING_OPERATIONS.has(operation) || bulkWriteProjects(operation, args);\n if (!projects) return args;\n return rewriteNode(model, args, resolve);\n};\n\n/**\n * One node of the projection tree. `select` present means the caller stated the\n * projection, so the client default is not injected. The node's own `omit`\n * remains for validation to subtract, and relation children are still visited.\n */\nconst rewriteNode = (\n model: AnyModel,\n node: Record<string, unknown>,\n resolve: ClientOmitResolver\n): Record<string, unknown> => {\n const selectValue = node.select;\n const includeValue = node.include;\n const hasSelect = isPlainRecord(selectValue);\n\n const nextSelect = hasSelect\n ? rewriteRelationMap(model, selectValue, resolve)\n : selectValue;\n const nextInclude = isPlainRecord(includeValue)\n ? rewriteRelationMap(model, includeValue, resolve)\n : includeValue;\n\n const defaults = hasSelect ? undefined : resolve.omit(model);\n const nextOmit = defaults ? mergeOmit(defaults, node.omit) : node.omit;\n\n if (\n nextSelect === selectValue &&\n nextInclude === includeValue &&\n nextOmit === node.omit\n ) {\n return node;\n }\n\n const next: Record<string, unknown> = { ...node };\n if (nextSelect !== selectValue) next.select = nextSelect;\n if (nextInclude !== includeValue) next.include = nextInclude;\n if (nextOmit !== node.omit) next.omit = nextOmit;\n return next;\n};\n\n/**\n * The client defaults with the caller's own `omit` layered on top, per field —\n * so `{ passwordHash: false }` re-includes exactly one globally hidden column\n * and leaves the rest hidden. Returns the caller's value untouched when it\n * already overrides every default (nothing to add).\n */\nconst mergeOmit = (\n defaults: Record<string, boolean>,\n local: unknown\n): Record<string, unknown> => {\n if (!isPlainRecord(local)) return { ...defaults };\n const merged: Record<string, unknown> = { ...defaults };\n for (const field of Object.keys(local)) merged[field] = local[field];\n return merged;\n};\n\n/**\n * Visit the relation entries of a `select`/`include` map. A bare `true` is\n * promoted to `{ omit: … }` only when the target model has defaults — otherwise\n * the shorthand is left exactly as written, which keeps the payload (and its\n * cache key) identical for the models nobody configured.\n */\nconst rewriteRelationMap = (\n model: AnyModel,\n map: Record<string, unknown>,\n resolve: ClientOmitResolver\n): Record<string, unknown> => {\n const slots = resolve.relations.get(model);\n let changed = false;\n const next: Record<string, unknown> = { ...map };\n\n for (const key of Object.keys(map)) {\n const resolved = slots?.get(key);\n if (!resolved) continue;\n const value = map[key];\n\n // ONE index, split here by the settled EDGE: a direct variant carrier spans\n // several targets and projects a tagged envelope; every other slot — an\n // ordinary pair, or a bound inverse view of one carrier member — reaches\n // exactly one model.\n const carrier = directVariantCarrier(resolved);\n if (carrier) {\n const rewritten = rewriteVariantCarrier(carrier, value, resolve);\n if (rewritten !== value) {\n next[key] = rewritten;\n changed = true;\n }\n continue;\n }\n\n const target = slotTarget(resolved, model);\n if (!target) continue;\n\n if (value === true) {\n const defaults = resolve.omit(target);\n if (!defaults) continue;\n next[key] = { omit: { ...defaults } };\n changed = true;\n continue;\n }\n if (!isPlainRecord(value)) continue;\n\n const rewritten = rewriteNode(target, value, resolve);\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. */\nconst 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 */\nconst slotTarget = (\n resolved: ResolvedSlot,\n source: AnyModel\n): AnyModel | undefined => {\n const edge = resolved.edge;\n if (edge.kind === \"foreignKey\" || edge.kind === \"junction\") {\n const [first, second] = edge.endpoints;\n return first.source === source && first.field === resolved.slot.field\n ? second.source\n : first.source;\n }\n return edge.carrier.source;\n};\n\n/**\n * WHERE a polymorphic arm lives depends on the slot's CARDINALITY, and getting\n * that wrong is not a missed default — it is a thrown query.\n *\n * A to-one slot's projection IS the discriminator map, so an arm is written at\n * the projection's top level. A collection's projection is an envelope whose\n * top level holds exactly two keys, `only` and `variants`; an arm written\n * beside them is an unknown key the strict envelope refuses. Since this rewrite\n * runs BEFORE validation, a top-level arm would make\n * `include: { items: true }` throw on any client that configures an `omit` for\n * a variant's target model — a client-option-shaped failure in a query that\n * never mentioned the option.\n */\nconst rewriteVariantCarrier = (\n edge: ResolvedVariantEdge,\n value: unknown,\n resolve: ClientOmitResolver\n): unknown =>\n edge.kind === \"variantJunctionCarrier\"\n ? rewritePolymorphicCollection(edge, value, resolve)\n : rewritePolymorphicSlot(edge, value, resolve);\n\n/**\n * The arm a client default produces for one target, or `undefined` when that\n * target is unconfigured (leave the caller's payload — and its cache key —\n * exactly as written).\n */\nconst defaultedArm = (\n target: AnyModel,\n variant: unknown,\n resolve: ClientOmitResolver\n): unknown => {\n if (isPlainRecord(variant)) {\n const rewritten = rewriteNode(target, variant, resolve);\n return rewritten === variant ? undefined : rewritten;\n }\n if (variant !== true && variant !== undefined) return undefined;\n const defaults = resolve.omit(target);\n return defaults ? { omit: { ...defaults } } : undefined;\n};\n\n/**\n * A to-one polymorphic projection object overrides individual variants; absent\n * keys still project that target's default scalars. Visit every configured\n * target so client defaults apply to both explicit and defaulted variants.\n */\nconst rewritePolymorphicSlot = (\n edge: Extract<ResolvedVariantEdge, { kind: \"variantRowCarrier\" }>,\n value: unknown,\n resolve: ClientOmitResolver\n): unknown => {\n if (value !== true && !isPlainRecord(value)) return value;\n\n const projection: Record<string, unknown> =\n value === true ? {} : { ...value };\n let changed = false;\n\n for (const member of edge.members) {\n const variant = value === true ? undefined : value[member.variant];\n const arm = defaultedArm(member.targetModel, variant, resolve);\n if (arm === undefined) continue;\n projection[member.variant] = arm;\n changed = true;\n }\n\n return changed ? projection : value;\n};\n\n/**\n * A collection projection: arms go UNDER `variants`, and an allow-list is\n * obeyed rather than worked around.\n *\n * Synthesizing an arm for a variant `only` excludes would fabricate the exact\n * \"Variant 'x' is not in 'only'\" refusal the envelope raises — a client option\n * producing a parse error about a key the caller never wrote.\n */\nconst rewritePolymorphicCollection = (\n edge: Extract<ResolvedVariantEdge, { kind: \"variantJunctionCarrier\" }>,\n value: unknown,\n resolve: ClientOmitResolver\n): unknown => {\n if (value !== true && !isPlainRecord(value)) return value;\n\n const envelope = value === true ? undefined : value;\n const only = envelope?.only;\n const existing = envelope?.variants;\n // A malformed envelope is left ALONE: validation owns the message, and a\n // rewrite here would only add keys to a payload that is already failing.\n if (only !== undefined && !Array.isArray(only)) return value;\n if (existing !== undefined && !isPlainRecord(existing)) return value;\n const allowed = Array.isArray(only) ? new Set<unknown>(only) : undefined;\n\n const variants: Record<string, unknown> = { ...existing };\n let changed = false;\n\n for (const member of edge.members) {\n if (allowed && !allowed.has(member.variant)) continue;\n const arm = defaultedArm(\n member.topology.target.model,\n existing?.[member.variant],\n resolve\n );\n if (arm === undefined) continue;\n variants[member.variant] = arm;\n changed = true;\n }\n\n if (!changed) return value;\n return { ...envelope, variants };\n};\n","import { ValidationError } from \"@errors\";\nimport { baseOperation } from \"@query-engine/routed-operations\";\nimport type { Operation as ValidationOperation } from \"@query-engine/types\";\nimport { isRecord } from \"@validation/value-guards\";\nimport type { Operations } from \"./types\";\n\n/** The unique-selector verbs; an `…OrThrow` verb is refused as its base. */\nconst UNIQUE_SELECTOR_OPERATIONS: ReadonlySet<string> =\n new Set<ValidationOperation>([\"findUnique\", \"update\", \"delete\", \"upsert\"]);\n\nexport function assertNonEmptyUniqueWhere(\n model: string,\n operation: Operations,\n args: unknown\n): void {\n const validationOperation = baseOperation(operation);\n if (!UNIQUE_SELECTOR_OPERATIONS.has(validationOperation)) return;\n if (!isRecord(args)) return;\n const where = args.where;\n if (!isRecord(where)) return;\n\n const hasDiscriminator = Object.keys(where).some(\n (key) => where[key] !== undefined\n );\n if (hasDiscriminator) return;\n\n throw new ValidationError(\n validationOperation,\n [\n {\n path: \"where\",\n message: \"whereUnique requires at least one unique discriminator.\",\n },\n ],\n { meta: { model } }\n );\n}\n","import {\n bindOfficialCacheChain,\n getOfficialCacheChainCapability,\n type OfficialCacheExtension,\n type OfficialCacheQueryContribution,\n officialCacheRuntime,\n} from \"@cache/capability\";\nimport type { CacheExecutionOptions } from \"@cache/driver\";\nimport type { WithCacheOptions } from \"@cache/schema\";\nimport { ASYNC_DISPOSE, type AsyncDisposeMember } from \"@drivers/async-dispose\";\nimport { readDriverIdentity } from \"@drivers/driver-identity\";\nimport type { AnyDriver } from \"@drivers/exports\";\nimport type {\n BatchTransactionOptions,\n TransactionOptions,\n} from \"@drivers/shared/transaction-options\";\nimport { ClientInitializationError, isVibORMError } from \"@errors\";\nimport {\n appendResolvedExtension,\n lookupPlacedControls,\n lookupResolvedExtensionHandlers,\n type ResolvedExtensionChain,\n} from \"@extensions/chain\";\nimport { bindControls, uncacheableRead } from \"@extensions/controls\";\nimport type {\n ClientExtension,\n ContextualExtensionDefinition,\n ExactExtensionDefinition,\n HasNamedClientOmit,\n SchemaBoundExtensionAdmission,\n} from \"@extensions/definition\";\nimport {\n type AccumulatedExtensionState,\n bindExtensionMethods,\n type EmptyClientExtensionState,\n type EnableExtensionCache,\n type ExtensionMethods,\n type ExtensionModelClient,\n type ExtensionStateConstraint,\n type ExtensionStateContributionOf,\n type HasExtensionCache,\n type HasResultConsumingExtension,\n type MergeModelMethods,\n} from \"@extensions/methods\";\nimport { TransactionWriteOutcomes } from \"@extensions/query\";\nimport { applyRequestTransforms } from \"@extensions/request\";\nimport { createOperationExecutionContext } from \"@query-engine/execution-context\";\nimport {\n attachPendingCacheExecution,\n type PendingOperation,\n type PrepareOperationInput,\n type PrepareWriteOutcomeRegistration,\n readPendingCacheResult,\n} from \"@query-engine/pending-operation\";\nimport { QueryEngine } from \"@query-engine/query-engine\";\nimport { createCandidateRoute } from \"@query-engine/raptor3/route/client-route\";\nimport {\n baseOperation,\n isWriteOperation,\n ROUTED_OPERATIONS,\n} from \"@query-engine/routed-operations\";\nimport type { TransactionOperation } from \"@query-engine/transaction-operation\";\nimport { hydrateSchemaNames } from \"@schema/hydration\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport {\n describeDecimalProviderLimitRefusal,\n findDecimalProviderLimitRefusal,\n} from \"@schema/scalars/decimal/provider-limits\";\nimport type { ResolvedRelationIndex } from \"@schema/validation/relation-resolution\";\nimport {\n resolveCheckedSchemaOrThrow,\n resolveSchemaOrThrow,\n} from \"@schema/validation/validator\";\nimport { createResolvedSchemaRegistry } from \"@validation/builder\";\nimport {\n executeArrayTransaction,\n runOutcomeTransaction,\n} from \"./array-transaction\";\nimport {\n getOfficialDefaultOmitChainCapability,\n type OfficialDefaultOmitExtension,\n type OfficialDefaultOmitRequestContribution,\n} from \"./default-omit-extension\";\nimport {\n applyClientOmit,\n type ClientOmitResolver,\n createClientOmitResolver,\n} from \"./omit\";\nimport type {\n DeclaresEvidence,\n GatedConfig,\n ProjectedModelOperations,\n} from \"./projected-types\";\nimport {\n createRawSurface,\n RAW_METHOD_NAMES,\n type RawOperation,\n type RawSurface,\n} from \"./raw\";\nimport type { ClientSchema, LinkedClientConfig } from \"./schema-links\";\nimport type {\n CachedClient,\n Client,\n ClientRowsContext,\n ContextualOperationResult,\n Operations,\n Schema,\n} from \"./types\";\n\nexport type {\n ClientSchema,\n FlatSchema,\n Linked,\n LinkedClientConfig,\n Links,\n RelationLinks,\n} from \"./schema-links\";\n\nimport { assertNonEmptyUniqueWhere } from \"./unique-where-guard\";\n\n/** The schema-bind refusal for an adapter with no physical GeoPoint protocol. */\nfunction refuseGeoPointFields(schema: Schema): void {\n for (const [modelName, model] of Object.entries(schema)) {\n const scalars: Record<string, Scalar> = model[\"~\"].state.scalars;\n for (const [fieldName, scalar] of Object.entries(scalars)) {\n if (scalar[\"~\"].state.type !== \"point\") continue;\n throw new ClientInitializationError(\n `GeoPoint field '${modelName}.${fieldName}' cannot be stored by this driver because its adapter has no GeoPoint protocol.`\n );\n }\n }\n}\n\ninterface OfficialReadCache {\n readonly capability: NonNullable<\n ReturnType<typeof getOfficialCacheChainCapability>\n >;\n readonly options: CacheExecutionOptions;\n}\n\n/**\n * Create a recursive proxy for model operations\n * Operations return the result of createOperation (PendingOperation or Promise)\n */\nfunction createModelProxy<S extends Schema, R>(\n schema: S,\n createOperation: (opts: {\n modelName: keyof S;\n operation: Operations;\n args: unknown;\n }) => R,\n modelMethods?: ExtensionMethods[\"model\"],\n path: string[] = []\n): unknown {\n // A model's own methods, read (and their factories invoked) only once the\n // model itself is.\n const methods = path.length === 1 ? modelMethods?.(path[0]!) : undefined;\n const members = new Set(\n path.length === 0\n ? Object.keys(schema)\n : path.length === 1\n ? [...ROUTED_OPERATIONS, ...Object.keys(methods ?? {})]\n : []\n );\n const children = new Map<string, unknown>();\n const readMember = (key: string | symbol): unknown => {\n if (typeof key !== \"string\" || key === \"then\" || !members.has(key))\n return undefined;\n if (methods !== undefined && Object.hasOwn(methods, key)) {\n return methods[key];\n }\n let child = children.get(key);\n if (child === undefined) {\n child = createModelProxy(schema, createOperation, modelMethods, [\n ...path,\n key,\n ]);\n children.set(key, child);\n }\n return child;\n };\n return new Proxy(path.length === 2 ? () => undefined : {}, {\n get: (target, key) =>\n Object.hasOwn(target, key) ? Reflect.get(target, key) : readMember(key),\n has: (target, key) =>\n Object.hasOwn(target, key) ||\n (typeof key === \"string\" && members.has(key)),\n ownKeys: (target) => [...new Set([...Reflect.ownKeys(target), ...members])],\n getOwnPropertyDescriptor: (target, key) =>\n Reflect.getOwnPropertyDescriptor(target, key) ??\n (typeof key === \"string\" && members.has(key)\n ? {\n configurable: true,\n enumerable: true,\n writable: true,\n value: readMember(key),\n }\n : undefined),\n apply(_target, _thisArg, [args]) {\n const modelName = path[0] as keyof S;\n const operation = path[1] as Operations;\n return createOperation({ modelName, operation, args });\n },\n });\n}\n\ntype BatchTransactionOperation<T = unknown> =\n | PendingOperation<T>\n | RawOperation<T>;\n\n/** What any view's `$transaction` accepts: a callback or an operation array. */\ntype TransactionInput<C extends VibORMConfig> =\n | ((\n tx: TransactionClient<C, ExtensionStateConstraint>\n ) => PromiseLike<unknown>)\n | TransactionOperation<unknown>[];\n\n/** The four raw methods the client and its transaction clients answer. */\nfunction isRawMethodName(prop: string | symbol): prop is keyof RawSurface {\n return typeof prop === \"string\" && Object.hasOwn(RAW_METHOD_NAMES, prop);\n}\n\n/**\n * VibORM Configuration\n */\nexport interface VibORMConfig<S extends Schema = Schema> {\n schema: S;\n driver: AnyDriver;\n /**\n * Skip the schema checks every client otherwise runs when it is created, for\n * a schema `viborm check` validates (in a build or CI step). The client still\n * resolves relations, which it needs to run queries; it trusts identifiers,\n * table and selector names, and the absence of required-relation cycles.\n */\n skipSchemaValidation?: boolean;\n}\n\nexport interface DriverConfig<S extends Schema = Schema>\n extends Omit<VibORMConfig<S>, \"driver\"> {}\n\ntype OrdinaryOfficialExtensionGuard<Definition> = Definition extends {\n readonly name: \"viborm.cache\";\n}\n ? { readonly name: never }\n : Definition extends {\n readonly query: OfficialCacheQueryContribution;\n }\n ? { readonly query: never }\n : Definition extends { readonly name: \"viborm.defaultOmit\" }\n ? { readonly name: never }\n : Definition extends {\n readonly request: OfficialDefaultOmitRequestContribution<object>;\n }\n ? { readonly request: never }\n : unknown;\n\ntype OfficialAwareDefinition<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n Self = unknown,\n> =\n | ContextualExtensionDefinition<C, X, Self>\n | OfficialCacheExtension\n | OfficialDefaultOmitExtension;\n\ntype OfficialCacheAdmission<\n Definition,\n X extends ExtensionStateConstraint,\n> = Record<Exclude<keyof Definition, keyof OfficialCacheExtension>, never> &\n (HasExtensionCache<X> extends true ? { readonly name: never } : unknown);\n\ntype OfficialDefaultOmitAdmission<\n Definition,\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = Record<\n Exclude<keyof Definition, keyof OfficialDefaultOmitExtension>,\n never\n> &\n (HasNamedClientOmit<C> extends true\n ? { readonly name: never }\n : HasResultConsumingExtension<X> extends true\n ? { readonly name: never }\n : unknown);\n\ntype ExtensionAdmission<\n Definition,\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = Definition extends OfficialCacheExtension\n ? OfficialCacheAdmission<Definition, X>\n : Definition extends OfficialDefaultOmitExtension\n ? OfficialDefaultOmitAdmission<Definition, C, X>\n : Definition extends ContextualExtensionDefinition<C, X, Definition>\n ? ExactExtensionDefinition<Definition, C, X> &\n (HasResultConsumingExtension<X> extends true\n ? { readonly rows?: never }\n : unknown) &\n OrdinaryOfficialExtensionGuard<Definition> &\n SchemaBoundExtensionAdmission<Definition, C>\n : never;\n\ntype WithDefaultOmit<C extends VibORMConfig, OmitConfig> = Omit<C, \"omit\"> & {\n readonly omit: OmitConfig;\n};\n\ntype AppliedClientConfig<\n C extends VibORMConfig,\n Definition,\n> = Definition extends OfficialDefaultOmitExtension<infer OmitConfig>\n ? WithDefaultOmit<C, OmitConfig>\n : GatedConfig<C, Definition>;\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 ProjectedContribution<\n Contribution extends ExtensionStateConstraint,\n Projected extends object,\n> extends ExtensionStateConstraint {\n readonly client: Contribution[\"client\"];\n readonly models: MergeModelMethods<Contribution[\"models\"], Projected>;\n readonly cache: Contribution[\"cache\"];\n readonly resultConsumer: Contribution[\"resultConsumer\"];\n readonly controls: Contribution[\"controls\"];\n readonly rows: Contribution[\"rows\"];\n readonly data: Contribution[\"data\"];\n}\n\ntype ContributionOf<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n Definition,\n Contribution extends\n ExtensionStateConstraint = ExtensionStateContributionOf<Definition>,\n> = DeclaresEvidence<C, Definition> extends false\n ? Contribution\n : ProjectedContribution<\n Contribution,\n ProjectedModelOperations<\n GatedConfig<C, Definition>,\n ClientRowsContext<\n GatedConfig<C, Definition>,\n X[\"rows\"] | Contribution[\"rows\"]\n >,\n X[\"controls\"] & Contribution[\"controls\"],\n Definition\n >\n >;\n\ntype AppliedExtensionState<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n Definition,\n> = Definition extends OfficialCacheExtension\n ? EnableExtensionCache<X>\n : Definition extends OfficialDefaultOmitExtension\n ? X\n : AccumulatedExtensionState<X, ContributionOf<C, X, Definition>>;\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/** `$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]\n ? { readonly [clientTypeState]?: readonly [C, X] | object }\n : never;\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 Omit<\n {\n /** Create a client with cache - only read operations available */\n $withCache: (\n config?: WithCacheOptions\n ) => CachedClient<\n C,\n ClientRowsContext<C, X[\"rows\"]>,\n X[\"controls\"],\n X[\"models\"]\n >;\n /** Invalidate cache entries by keys or patterns (use * suffix for prefix matching) */\n $invalidate: (...keys: string[]) => Promise<void>;\n },\n HasExtensionCache<X> extends true ? \"never\" : \"$withCache\" | \"$invalidate\"\n >;\n\n/**\n * The client members no extension state removes. An interface outside the\n * `Omit` above, so a body generic over the extension state still reaches them.\n */\ninterface 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 a named definition or a synchronous factory to this client view.\n * Definitions append to the immutable chain; factories compose through the\n * same `$extends` method. Definition model keys are checked against this schema.\n */\n // Check the factory output here: constraining the client-valued default\n // eagerly expands every delegate, even when applying a plain definition.\n $extends<Result = VibORMClient<C, X>>(\n factory: (client: NoInfer<VibORMClient<C, X>>) => Result & {\n readonly $schema: Schema;\n }\n ): Result;\n $extends<const Definition extends OfficialAwareDefinition<C, X, Definition>>(\n extension: Definition &\n ExtensionAdmission<Definition, C, X> &\n (Definition extends (...args: never[]) => unknown ? never : unknown)\n ): VibORMClient<\n AppliedClientConfig<C, Definition>,\n AppliedExtensionState<C, X, Definition>\n >;\n}\n\ntype ApplyClientExtensions<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n Definitions extends readonly unknown[],\n> = Definitions extends readonly []\n ? VibORMClient<C, X>\n : Definitions extends readonly [\n infer Definition,\n ...infer RemainingDefinitions,\n ]\n ? Definition extends (...args: never[]) => unknown\n ? never\n : Definition extends OfficialAwareDefinition<C, X>\n ? Definition extends ExtensionAdmission<Definition, C, X>\n ? ApplyClientExtensions<\n AppliedClientConfig<C, Definition>,\n AppliedExtensionState<C, X, Definition>,\n RemainingDefinitions\n >\n : never\n : never\n : never;\n\n/**\n * The exact client surface produced by applying an ordered definition tuple.\n * Factory callbacks are composed with `$extends`; name their result with `typeof`.\n *\n * @example\n * ```ts\n * type AppClient = ExtendedClient<\n * typeof db,\n * readonly [typeof defaults, typeof cached, typeof methods]\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/** The extension type-state a derived client carries. */\nexport type ExtensionState = ExtensionStateConstraint;\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 the chain's `rows` 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[\"rows\"]>\n >\n : never\n : never\n : never;\n\n/**\n * VibORM Client\n */\nexport class VibORM<C extends VibORMConfig> {\n readonly #schema: ClientSchema<C>;\n readonly #engine: QueryEngine;\n readonly #relations: ResolvedRelationIndex;\n /** The schema's validation schemas, which also admit `rows` predicates. */\n readonly #registry: PreparedSchema[\"schemaRegistry\"];\n /** One resolved declarative omit per authenticated capability on this client. */\n #extensionOmitResolvers:\n | WeakMap<object, Readonly<{ resolver: ClientOmitResolver | undefined }>>\n | undefined;\n\n /**\n * @param prepared - the ONE resolved topology index the static factory's\n * gate produced, and the registries over it, passed in by identity. The\n * registry, an official default-omit resolver, and every query scope share\n * this exact object; nothing here resolves a second time and nothing\n * copies it (§10E.10, §11.4.10).\n */\n constructor(config: C, { relations, schemaRegistry }: PreparedSchema) {\n this.#schema = config.schema as ClientSchema<C>;\n this.#relations = relations;\n this.#registry = schemaRegistry;\n\n // The Raptor 3 route is the ONE operation owner (C-01). The two resolved\n // views above travel to it by identity, so the route's engine hydrates,\n // validates and registers nothing a second time (B-3).\n this.#engine = new QueryEngine(\n config.driver,\n createCandidateRoute(this.#schema, config.driver, {\n index: relations,\n registry: schemaRegistry,\n })\n );\n }\n\n /**\n * Create the client with model proxies and utility methods\n * Model operations return PendingOperation for deferred execution\n */\n #createClient(\n engine: QueryEngine,\n modelMethods: ExtensionMethods[\"model\"] | undefined,\n clientOmit: ClientOmitResolver | undefined\n ): Client<C> {\n return createModelProxy(\n this.#schema,\n ({ modelName, operation, args }) =>\n this.#prepareModelOperation(\n engine,\n modelName,\n operation,\n args,\n clientOmit\n ),\n modelMethods\n ) 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 officialReadCache?: OfficialReadCache\n ): PendingOperation<unknown> {\n const officialCache = getOfficialCacheChainCapability(\n engine.extensionChain\n );\n const modelNameStr = String(modelName);\n const model = this.#schema[modelName];\n if (!model) {\n throw new ClientInitializationError(\n `Model \"${modelNameStr}\" not found in schema`,\n { meta: { model: modelNameStr, operation: String(operation) } }\n );\n }\n\n const rawArgs = (args ?? {}) as Record<string, unknown>;\n const isWrite = isWriteOperation(operation);\n const chain = engine.extensionChain;\n\n const requestHandlers = lookupResolvedExtensionHandlers(\n chain,\n \"request\",\n modelNameStr,\n operation\n );\n const hasOperationObservers = (chain?.observe.length ?? 0) > 0;\n const hasPlacedControls =\n lookupPlacedControls(chain, modelNameStr, operation).length > 0;\n let operationArgs: Record<string, unknown> = rawArgs;\n let prepareInput: PrepareOperationInput | undefined;\n // Apply the client omit, then refuse an empty unique where.\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 return omittedArgs;\n };\n\n if (\n requestHandlers === undefined &&\n !hasPlacedControls &&\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 controls removed.\n prepareInput = (controlFreeArgs, controls) => {\n const transformed =\n requestHandlers === undefined\n ? controlFreeArgs\n : applyRequestTransforms(\n modelNameStr,\n operation,\n controlFreeArgs,\n requestHandlers,\n chain?.controls === undefined\n ? undefined\n : { names: chain.controls.names, admitted: controls }\n );\n return finish(transformed ?? {});\n };\n }\n\n const prepareWriteOutcomeRegistration:\n | PrepareWriteOutcomeRegistration\n | undefined =\n officialCache === undefined || !isWrite\n ? undefined\n : (context, controls) =>\n officialCacheRuntime().prepareMutationCacheWriteOutcome(\n officialCache.driver,\n modelNameStr,\n operation,\n officialCacheRuntime().readMutationCacheOptions(controls),\n context,\n officialCache.scope\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. A cached read\n // is never a write, so it carries no outcome registration.\n const pendingOperation = engine.prepare(\n model,\n operation,\n operationArgs,\n officialReadCache ? { skipSpan: true } : undefined,\n prepareInput,\n prepareWriteOutcomeRegistration\n );\n if (officialReadCache === undefined) return pendingOperation;\n return this.#wrapOfficialCachedRead(\n engine,\n modelNameStr,\n operation,\n pendingOperation,\n officialReadCache\n );\n }\n\n /** Bind cached reads to the same root or derived engine as their client. */\n #withCache(\n engine: QueryEngine,\n capability: NonNullable<ReturnType<typeof getOfficialCacheChainCapability>>,\n clientOmit: ClientOmitResolver | undefined,\n config?: WithCacheOptions\n ): CachedClient<C> {\n const runtime = officialCacheRuntime();\n const options = runtime.createCacheExecutionOptions(\n config,\n capability.waitUntil,\n readDriverIdentity(engine.driver)\n );\n const officialReadCache = Object.freeze({ capability, options });\n return createModelProxy(this.#schema, ({ modelName, operation, args }) => {\n try {\n runtime.validateCacheableOperation(operation);\n return this.#prepareModelOperation(\n engine,\n modelName,\n operation,\n args,\n clientOmit,\n officialReadCache\n );\n } catch (error) {\n return Promise.reject(error);\n }\n }) as CachedClient<C>;\n }\n\n /** Resolve one authenticated declarative omit once for this client schema. */\n #resolveClientOmit(\n chain: ResolvedExtensionChain\n ): ClientOmitResolver | undefined {\n const capability = getOfficialDefaultOmitChainCapability(chain);\n if (capability === undefined) return undefined;\n const resolvers =\n this.#extensionOmitResolvers ??\n (this.#extensionOmitResolvers = new WeakMap());\n const existing = resolvers.get(capability);\n if (existing !== undefined) return existing.resolver;\n const resolver = createClientOmitResolver(\n this.#schema,\n capability.config,\n this.#relations\n );\n resolvers.set(capability, Object.freeze({ resolver }));\n return resolver;\n }\n\n /** Keep every arbitrary query handler outside the official cache child. */\n #wrapOfficialCachedRead(\n engine: QueryEngine,\n modelName: string,\n operation: Operations,\n pendingOperation: PendingOperation<unknown>,\n cacheRead: OfficialReadCache\n ): PendingOperation<unknown> {\n return attachPendingCacheExecution(\n pendingOperation,\n async (execute, driverOverride) => {\n const cacheResult = readPendingCacheResult(pendingOperation);\n const refused = uncacheableRead(\n engine.extensionChain?.controls?.all ?? [],\n cacheResult.controls,\n modelName,\n baseOperation(operation)\n );\n if (refused) throw refused;\n if (\n driverOverride !== undefined ||\n engine.transactionWriteOutcomes !== undefined ||\n (engine.extensionChain?.statement.length ?? 0) > 0\n ) {\n return execute();\n }\n const runtime = officialCacheRuntime();\n const key = runtime.cacheKeyOf(\n cacheResult.args,\n cacheResult.controls,\n engine.extensionChain?.rows\n );\n if (key === undefined) return execute();\n return runtime.executeCachedResultOperation(\n cacheRead.capability.driver,\n modelName,\n operation,\n key,\n () => execute(),\n {\n ...cacheRead.options,\n executionContext: cacheResult.executionContext,\n },\n cacheResult.codec,\n cacheRead.capability.scope\n );\n }\n );\n }\n\n /**\n * The one get-trap ladder of every concrete view: the root client, an\n * interactive transaction's `tx`, and the scope each extension factory sees.\n * Every utility member is `$`-named or a symbol and a model name never is, so\n * model access is answered first. `extra` adds the root-only utilities, or\n * a scope's `$bind`. No client method takes a core name, so client methods\n * (and their factories) are read only for a member core does not answer.\n */\n #createViewProxy<V>(\n engine: QueryEngine,\n clientOmit: ClientOmitResolver | undefined,\n transaction: CallableFunction,\n methods: ExtensionMethods | undefined,\n extra?: (prop: string | symbol) => unknown\n ): V {\n // Raw SQL rides this view's engine: inside an interactive transaction it\n // shares the transaction's connection and rolls back with it. The surface\n // is built on first `$queryRaw`-family access.\n let rawSurface: RawSurface | undefined;\n return new Proxy(this.#createClient(engine, methods?.model, clientOmit), {\n get: (target, prop) => {\n if (typeof prop === \"string\" && !prop.startsWith(\"$\")) {\n return Reflect.get(target, prop);\n }\n if (prop === \"$schema\") return this.#schema;\n if (prop === \"$transaction\") return transaction;\n if (isRawMethodName(prop)) {\n rawSurface ??= createRawSurface({ engine });\n return rawSurface[prop];\n }\n const member = extra?.(prop);\n if (member !== undefined || typeof prop !== \"string\") return member;\n const client = methods?.client();\n if (client !== undefined && Object.hasOwn(client, prop)) {\n return client[prop];\n }\n // A `$`-named model is still reachable; anything else is absent.\n return Object.hasOwn(this.#schema, prop)\n ? Reflect.get(target, prop)\n : undefined;\n },\n }) as V;\n }\n\n /**\n * Build one concrete view over one engine scope and its extension chain.\n * Each factory scope's `$bind` returns `rebuild` of this engine with the\n * values bound: a view of this view's kind. `eager` invokes every factory\n * now; otherwise each runs when a method it returns is first read.\n */\n #createView<V>(\n engine: QueryEngine,\n clientOmit: ClientOmitResolver | undefined,\n rebuild: ((engine: QueryEngine) => unknown) | undefined,\n eager: boolean,\n extra?: (prop: string | symbol) => unknown\n ): V {\n const transaction = (\n input: TransactionInput<C>,\n options?: TransactionOptions | BatchTransactionOptions\n ) => this.#transact(engine, clientOmit, input, options);\n const chain = engine.extensionChain;\n const methods =\n chain &&\n bindExtensionMethods(chain, (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 bindControls(\n chain.controls?.all ?? [],\n extension,\n values,\n engine.bound\n )\n )\n )\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 // A coordinated chain collects write outcomes per scope: the root\n // publishes them, a savepoint promotes them into its parent's collector.\n const outcomes =\n chain?.hasQueryHandlers ||\n chain?.hasCache ||\n (chain?.observe.length ?? 0) > 0\n ? new TransactionWriteOutcomes()\n : undefined;\n const view = (\n bound: QueryEngine\n ): TransactionClient<C, ExtensionStateConstraint> =>\n this.#createView(bound, clientOmit, view, false);\n const body = async (txDriver: AnyDriver) =>\n input(view(engine.bind(txDriver, chain, outcomes)));\n return outcomes\n ? runOutcomeTransaction(\n engine.driver,\n outcomes,\n engine.transactionWriteOutcomes,\n options as TransactionOptions | undefined,\n context,\n body\n )\n : engine.driver.withTransaction(\n body,\n options as TransactionOptions | undefined,\n context\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 === \"$extends\") {\n return (\n extension:\n | ClientExtension\n | ((client: VibORMClient<ViewConfig, X>) => unknown)\n ) => {\n if (typeof extension === \"function\") return extension(view);\n const extensionChain = appendResolvedExtension(\n chain,\n extension,\n this.#schema,\n this.#registry\n );\n // The one point that holds both the resolved chain and the concrete\n // driver, so the one point that can partition the official cache by\n // this client's dialect and SQL namespace. A chain without the\n // official cache makes no call at all.\n if (extensionChain.hasCache) {\n bindOfficialCacheChain(extensionChain, engine.driver);\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 if (prop === \"$disconnect\" || prop === ASYNC_DISPOSE) return disconnect;\n if (prop !== \"$withCache\" && prop !== \"$invalidate\") return undefined;\n const officialCache = getOfficialCacheChainCapability(chain);\n if (officialCache === undefined) return undefined;\n if (prop === \"$withCache\") {\n return (cacheConfig?: WithCacheOptions) =>\n this.#withCache(engine, officialCache, clientOmit, cacheConfig);\n }\n return async (...keys: string[]) => {\n await officialCacheRuntime().invalidateManualCache(\n officialCache.driver,\n keys,\n createOperationExecutionContext(\"$cache\", \"$invalidate\", chain),\n officialCache.scope\n );\n };\n }\n );\n return view;\n }\n\n /**\n * Create the full client with all utility methods\n */\n static create<\n C extends VibORMConfig,\n ViewConfig extends VibORMConfig = LinkedClientConfig<C>,\n >(config: C): VibORMClient<ViewConfig> {\n if (!config.driver) {\n throw new ClientInitializationError(\n \"Driver is required to create a client. Pass a driver in createClient options.\"\n );\n }\n\n // PostgreSQL always qualifies, so an adapter with no namespace would send\n // this client's SQL wherever the connection's search_path points while\n // migrations altered another schema. Only `PostgresAdapter` owns the\n // `public` default; a custom adapter is refused rather than defaulted.\n if (\n config.driver.dialect === \"postgresql\" &&\n config.driver.adapter.namespace === undefined\n ) {\n throw new ClientInitializationError(\n \"A PostgreSQL driver must supply an adapter with a namespace. Construct PostgresAdapter, or set `namespace` on a custom adapter.\"\n );\n }\n\n // Hydrate schema names (tsName, sqlName) for all models, scalars, and relations.\n // Construction faults (a malformed schema, an invalid identifier) surface as a typed\n // ClientInitializationError instead of a bare Error; already-typed failures pass through\n // unchanged so their own code survives.\n const orm = assertConstructed(() => {\n const checked = config.skipSchemaValidation === true;\n const reused = reusablePreparation(config.schema, checked);\n if (!reused) hydrateSchemaNames(config.schema, checked);\n // The selected adapter's physical capability, asked once here and before\n // any provider I/O (plan §3.1). A decimal domain no dialect could store is\n // a definition error, and the caller learns it at the line that bound the\n // schema rather than at the first UPDATE that could not compute inside it.\n // On SQLite the refusal is load-bearing: past 18 digits its range CHECK\n // stops being exact (see the SQLite adapter's arithmetic guards).\n const decimalRefusal = reused?.fittingDialects.has(config.driver.dialect)\n ? undefined\n : findDecimalProviderLimitRefusal(config.schema, config.driver.dialect);\n if (decimalRefusal !== undefined) {\n throw new ClientInitializationError(\n describeDecimalProviderLimitRefusal(decimalRefusal)\n );\n }\n if (config.driver.adapter.geoPoint === undefined) {\n refuseGeoPointFields(config.schema);\n }\n // ONE resolution for the whole client lifecycle: the gate's index goes\n // straight into the constructor, so the registry and query scopes are\n // composed over the same object (§11.4.10).\n const prepared = reused ?? prepareSchema(config.schema, checked);\n prepared.fittingDialects.add(config.driver.dialect);\n return new VibORM<C>(config, prepared);\n });\n\n return orm.#createRootView<EmptyClientExtensionState, ViewConfig>(\n orm.#engine\n );\n }\n}\n\n/** The driver-independent construction a client derives from its schema. */\ninterface PreparedSchema {\n readonly entries: readonly (readonly [string, unknown])[];\n readonly relations: ResolvedRelationIndex;\n readonly schemaRegistry: ReturnType<typeof createResolvedSchemaRegistry>;\n /** Dialects whose decimal storage limits this schema already fits. */\n readonly fittingDialects: Set<string>;\n /** Whether the full client validation ran, not only relation resolution. */\n readonly validated: boolean;\n}\n\n/**\n * Clients over the same schema object share its validated, resolved views:\n * they derive from the models alone, so a client created per request (one per\n * Worker invocation) skips re-validating and rebuilding them. The entries are\n * compared on reuse, so a schema object that gained or swapped a model since\n * is prepared again.\n */\nconst preparedSchemas = new WeakMap<object, PreparedSchema>();\n\nfunction reusablePreparation(\n schema: Schema,\n checked: boolean\n): PreparedSchema | undefined {\n const prepared = preparedSchemas.get(schema);\n // A validating client never reuses a preparation that skipped validation.\n if (!(prepared && (prepared.validated || checked))) return;\n const keys = Object.keys(schema);\n if (keys.length !== prepared.entries.length) return;\n for (const [index, [key, model]] of prepared.entries.entries()) {\n if (keys[index] !== key || schema[key] !== model) return;\n }\n return prepared;\n}\n\nfunction prepareSchema(schema: Schema, checked: boolean): PreparedSchema {\n const relations = checked\n ? resolveCheckedSchemaOrThrow(schema)\n : resolveSchemaOrThrow(schema);\n const schemaRegistry = createResolvedSchemaRegistry(schema, relations);\n const prepared: PreparedSchema = {\n entries: Object.entries(schema),\n relations,\n schemaRegistry,\n fittingDialects: new Set(),\n validated: !checked,\n };\n preparedSchemas.set(schema, prepared);\n return prepared;\n}\n\n/**\n * Run a client-construction step, re-typing bare failures as ClientInitializationError.\n *\n * Typed VibORM errors (a ValidationError from schema validation, for instance) keep their own\n * class and code — only untyped construction faults are re-typed, and their message is kept\n * verbatim so existing diagnostics still read the same.\n */\nfunction assertConstructed<T>(build: () => T): T {\n try {\n return build();\n } catch (error) {\n if (isVibORMError(error)) {\n throw error;\n }\n const cause = error instanceof Error ? error : undefined;\n throw new ClientInitializationError(\n cause?.message ?? \"Failed to create the VibORM client\",\n cause ? { cause } : undefined\n );\n }\n}\n\n/**\n * Create a VibORM client\n *\n * @example\n * ```ts\n * import { PGlite } from \"@electric-sql/pglite\";\n * import { PGliteDriver } from \"viborm/pglite\";\n * import { createClient } from \"viborm\";\n *\n * const db = new PGlite();\n * const driver = new PGliteDriver({ client: db });\n * const client = createClient({ driver, schema: { user, post } });\n *\n * // Query\n * const users = await client.user.findMany({ where: { name: \"Alice\" } });\n *\n * // Transaction\n * await client.$transaction(async (tx) => {\n * const user = await tx.user.create({ data: { name: \"Bob\" } });\n * await tx.post.create({ data: { title: \"Hello\", authorId: user.id } });\n * });\n *\n * // Raw query\n * const result = await client.$executeRaw(sql`SELECT * FROM users`);\n *\n * // Disconnect\n * await client.$disconnect();\n * ```\n */\nexport const createClient = <S extends Schema, Config extends VibORMConfig<S>>(\n // `Config` captures the whole literal for the result types. The structural\n // refusal rejects unknown keys for fresh and held configuration values.\n config: Config & VibORMConfig<S> & NoExtraConfigKeys<Config, VibORMConfig<S>>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<Config>]: LinkedClientConfig<Config>[P];\n}> => {\n // Explicit `Config`: the parameter's refusal members (`NoExtraConfigKeys`) are\n // there to reject typo'd keys, not to be threaded into the client's result\n // types — inferring `C` from the intersection would carry them along.\n return VibORM.create<\n Config,\n { [P in keyof LinkedClientConfig<Config>]: LinkedClientConfig<Config>[P] }\n >(config);\n};\n\n/**\n * The one driver-wrapper seam. It reads only core client properties, so removed\n * or driver-specific configuration getters are never copied into the core.\n */\nexport const createClientFromDriverConfig = <\n S extends Schema,\n C extends DriverConfig<S>,\n D extends AnyDriver,\n>(\n config: C,\n driver: D\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: D }>]: LinkedClientConfig<\n C & { driver: D }\n >[P];\n}> => {\n const { schema, skipSchemaValidation } = config;\n const coreConfig = {\n schema,\n driver,\n ...(skipSchemaValidation === undefined ? {} : { skipSchemaValidation }),\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":"ihEAkEA,MAAa,GAAmB,OAAO,OAAO,CAC5C,YAAa,GACb,kBAAmB,GACnB,UAAW,GACX,gBAAiB,GAClB,CAAiD,CAGlD,SAAS,WAAW,EAAgC,CAClD,OAAO,IAAW,eAAiB,IAAW,oBAsDhD,SAAS,uBAAuB,EAA+C,CAG7E,OAAO,MAAM,QAAQ,EAAM,EAAI,MAAM,QAAQ,QAAQ,IAAI,EAAO,MAAM,CAAC,CAGzE,SAAS,cACP,EACA,EACA,EACY,CACZ,OAAO,IAAI,GAAW,GAAG,EAAO,GAAG,IAAW,CAC5C,KAAM,EAAgB,cACtB,KACE,IAAmB,IAAA,GAAY,CAAE,SAAQ,CAAG,CAAE,SAAQ,iBAAgB,CACzE,CAAC,CAGJ,SAAS,kBAAkB,EAAuC,CAChE,IAAM,EAAW,MAAe,EAAO,OAAO,CAC9C,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAO,OAAQ,GAAS,EAC9C,OAAO,OAAO,EAAQ,EAAM,GAAE,EAAK,GAAS,EAAO,IAEzD,OAAO,EAGT,SAAS,eAAe,EAAsC,CAC5D,IAAM,EAAW,MAAc,EAAQ,OAAO,CAC9C,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAQ,OAAQ,GAAS,EAAG,CACtD,IAAM,EAAa,OAAO,yBAAyB,EAAS,EAAM,CAClE,GACE,IAAe,IAA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