@prisma/orm-family-sql 8.0.0-rc.23-dev.8 → 8.0.0-rc.23-dev.10

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 (156) hide show
  1. package/dist/{aggregate-descriptor-registry-CkybswmO.mjs → aggregate-descriptor-registry-DM1hmlq-.mjs} +2 -2
  2. package/dist/{aggregate-descriptor-registry-CkybswmO.mjs.map → aggregate-descriptor-registry-DM1hmlq-.mjs.map} +1 -1
  3. package/dist/{ast-C3itulLi.mjs → ast-BO3Wgbrl.mjs} +2 -2
  4. package/dist/ast-BO3Wgbrl.mjs.map +1 -0
  5. package/dist/{ast-BopvCTVF.d.mts → ast-CrnvUofJ.d.mts} +3 -3
  6. package/dist/{ast-BopvCTVF.d.mts.map → ast-CrnvUofJ.d.mts.map} +1 -1
  7. package/dist/builder.d.mts +3 -3
  8. package/dist/builder__runtime.d.mts +7 -7
  9. package/dist/builder__runtime.mjs +24 -15
  10. package/dist/builder__runtime.mjs.map +1 -1
  11. package/dist/builder__types.d.mts +5 -5
  12. package/dist/collection-methods-B6AtdlXI.d.mts +1 -0
  13. package/dist/{collection-methods-B82cPkgc-DY10b2Cq.d.mts → collection-methods-p_bnn5LM-B8bdfRNR.d.mts} +3 -3
  14. package/dist/{collection-methods-B82cPkgc-DY10b2Cq.d.mts.map → collection-methods-p_bnn5LM-B8bdfRNR.d.mts.map} +1 -1
  15. package/dist/{config-types-BSn4oo7q.mjs → config-types-DUvOG4yN.mjs} +2 -2
  16. package/dist/{config-types-BSn4oo7q.mjs.map → config-types-DUvOG4yN.mjs.map} +1 -1
  17. package/dist/{contract-builder-m9XW9MgR.mjs → contract-builder-Drywaj7K.mjs} +3 -3
  18. package/dist/{contract-builder-m9XW9MgR.mjs.map → contract-builder-Drywaj7K.mjs.map} +1 -1
  19. package/dist/contract-prisma7__provider.mjs +5 -5
  20. package/dist/contract-psl.mjs +1 -1
  21. package/dist/contract-psl__attribute-specs.mjs +1 -1
  22. package/dist/contract-psl__provider.mjs +2 -2
  23. package/dist/contract-ts.mjs +3 -3
  24. package/dist/contract-ts__config-types.mjs +1 -1
  25. package/dist/contract-ts__contract-builder.mjs +2 -2
  26. package/dist/contract.mjs +1 -1
  27. package/dist/contract__validators.mjs +1 -1
  28. package/dist/{control-DcEzEBvW.mjs → control-BJWi318s.mjs} +5 -5
  29. package/dist/{control-DcEzEBvW.mjs.map → control-BJWi318s.mjs.map} +1 -1
  30. package/dist/{control--kGmu2Ez.d.mts → control-C0Jp0muh.d.mts} +7 -7
  31. package/dist/{control--kGmu2Ez.d.mts.map → control-C0Jp0muh.d.mts.map} +1 -1
  32. package/dist/{control-adapter-BfyLe7rh-DSiEx96z.d.mts → control-adapter-BfyLe7rh-0LQGA2VV.d.mts} +4 -4
  33. package/dist/{control-adapter-BfyLe7rh-DSiEx96z.d.mts.map → control-adapter-BfyLe7rh-0LQGA2VV.d.mts.map} +1 -1
  34. package/dist/{control-adapter-xJwgaSsO.d.mts → control-adapter-DMrjnUFj.d.mts} +2 -2
  35. package/dist/{control-adapter-xJwgaSsO.d.mts.map → control-adapter-DMrjnUFj.d.mts.map} +1 -1
  36. package/dist/{db-D1d75IvM-C88quYVJ.d.mts → db-DfYeGVcu-NRittTYE.d.mts} +18 -11
  37. package/dist/db-DfYeGVcu-NRittTYE.d.mts.map +1 -0
  38. package/dist/{ddl-types-BeA1kjV1-BUcW52Dx.d.mts → ddl-types-D22OYeFy-Be5-W-5z.d.mts} +3 -3
  39. package/dist/{ddl-types-BeA1kjV1-BUcW52Dx.d.mts.map → ddl-types-D22OYeFy-Be5-W-5z.d.mts.map} +1 -1
  40. package/dist/{derived-checks-zjkmqsa_-D7VKKK_q.mjs → derived-checks-zjkmqsa_-BZv7VzY0.mjs} +2 -2
  41. package/dist/{derived-checks-zjkmqsa_-D7VKKK_q.mjs.map → derived-checks-zjkmqsa_-BZv7VzY0.mjs.map} +1 -1
  42. package/dist/{diff-bSfcDUpu.d.mts → diff-BBEq2-E2.d.mts} +2 -2
  43. package/dist/{diff-bSfcDUpu.d.mts.map → diff-BBEq2-E2.d.mts.map} +1 -1
  44. package/dist/errors.mjs +70 -1
  45. package/dist/errors.mjs.map +1 -0
  46. package/dist/{exports-WNaGWaJR-CVNygh-P.mjs → exports-WNaGWaJR-C6wltYlN.mjs} +3 -3
  47. package/dist/{exports-WNaGWaJR-CVNygh-P.mjs.map → exports-WNaGWaJR-C6wltYlN.mjs.map} +1 -1
  48. package/dist/expression-CMV-f0HM.d.mts +2 -0
  49. package/dist/{expression-DGu7PRyk-Do_Q7JGF.d.mts → expression-DSAx-7Ri-C4W_nQ6T.d.mts} +4 -4
  50. package/dist/expression-DSAx-7Ri-C4W_nQ6T.d.mts.map +1 -0
  51. package/dist/{expression-4Y1d1hJ_-p9KkcaqT.d.mts → expression-DmvKA8dE-D29cLTJG.d.mts} +84 -10
  52. package/dist/expression-DmvKA8dE-D29cLTJG.d.mts.map +1 -0
  53. package/dist/{expression-impl-DtbmFnnz-Dal0IYDE.mjs → expression-impl-DHdjzqE3-Cd9gP7oC.mjs} +16 -9
  54. package/dist/expression-impl-DHdjzqE3-Cd9gP7oC.mjs.map +1 -0
  55. package/dist/family.d.mts +7 -7
  56. package/dist/family.mjs +4 -4
  57. package/dist/family__control-adapter.d.mts +2 -2
  58. package/dist/family__control.d.mts +2 -2
  59. package/dist/family__control.mjs +2 -2
  60. package/dist/family__diff.d.mts +1 -1
  61. package/dist/family__ir.mjs +1 -1
  62. package/dist/family__migration.d.mts +1 -1
  63. package/dist/family__pack.d.mts +1 -1
  64. package/dist/family__pack.mjs +2 -2
  65. package/dist/functions-CLrZo2Gj.d.mts +1 -0
  66. package/dist/{functions-DO1k8KLB.mjs → functions-Cl_egJ2w.mjs} +3 -3
  67. package/dist/{functions-DO1k8KLB.mjs.map → functions-Cl_egJ2w.mjs.map} +1 -1
  68. package/dist/{generator-functions-Hy4pDDr9-DkN0qbPW.mjs → generator-functions-Hy4pDDr9-CAx4Z7af.mjs} +3 -3
  69. package/dist/{generator-functions-Hy4pDDr9-DkN0qbPW.mjs.map → generator-functions-Hy4pDDr9-CAx4Z7af.mjs.map} +1 -1
  70. package/dist/{index-reference--2lpz6Um-CtLxcswa.d.mts → index-reference-2EXdtnBp-BxO97DG1.d.mts} +3 -3
  71. package/dist/{index-reference--2lpz6Um-CtLxcswa.d.mts.map → index-reference-2EXdtnBp-BxO97DG1.d.mts.map} +1 -1
  72. package/dist/index-reference-C4a-sIjK.d.mts +1 -0
  73. package/dist/{index-2YUqocwr.d.mts → index-rlHk9lB3.d.mts} +17 -17
  74. package/dist/{index-2YUqocwr.d.mts.map → index-rlHk9lB3.d.mts.map} +1 -1
  75. package/dist/{interpreter-CVd521dx-B3prmAMy.mjs → interpreter-CVd521dx-PDiCxDLC.mjs} +4 -4
  76. package/dist/{interpreter-CVd521dx-B3prmAMy.mjs.map → interpreter-CVd521dx-PDiCxDLC.mjs.map} +1 -1
  77. package/dist/{middleware-JfHt_Ax8-rWWdDxnq.d.mts → middleware-4P5tDL8a-C1UaoUUN.d.mts} +3 -3
  78. package/dist/{middleware-JfHt_Ax8-rWWdDxnq.d.mts.map → middleware-4P5tDL8a-C1UaoUUN.d.mts.map} +1 -1
  79. package/dist/middleware-DDOdMwm4.d.mts +1 -0
  80. package/dist/{migration-OXM3LDdT.d.mts → migration-CkdSQ8g8.d.mts} +2 -2
  81. package/dist/{migration-OXM3LDdT.d.mts.map → migration-CkdSQ8g8.d.mts.map} +1 -1
  82. package/dist/orm-client.d.mts +22 -22
  83. package/dist/orm-client.d.mts.map +1 -1
  84. package/dist/orm-client.mjs +1399 -1278
  85. package/dist/orm-client.mjs.map +1 -1
  86. package/dist/{pack-Bn5P2Nak.d.mts → pack-7m3efDkY.d.mts} +2 -2
  87. package/dist/{pack-Bn5P2Nak.d.mts.map → pack-7m3efDkY.d.mts.map} +1 -1
  88. package/dist/{plan-CMqVpPq6-Aoza6Dp2.d.mts → plan-49sl7WSN-C22ZPSE9.d.mts} +3 -3
  89. package/dist/{plan-CMqVpPq6-Aoza6Dp2.d.mts.map → plan-49sl7WSN-C22ZPSE9.d.mts.map} +1 -1
  90. package/dist/plan-BEnXVtn1.d.mts +2 -0
  91. package/dist/{psl-field-resolution-GN4iup8d-CcMRk9It.mjs → psl-field-resolution-GN4iup8d-BSjTCYks.mjs} +3 -3
  92. package/dist/{psl-field-resolution-GN4iup8d-CcMRk9It.mjs.map → psl-field-resolution-GN4iup8d-BSjTCYks.mjs.map} +1 -1
  93. package/dist/query-lane-context-CNY3sTaF.d.mts +1 -0
  94. package/dist/{query-lane-context-vp4wQJQD-DNtizzS5.d.mts → query-lane-context-DRO74vm5-BbGhhycI.d.mts} +5 -5
  95. package/dist/{query-lane-context-vp4wQJQD-DNtizzS5.d.mts.map → query-lane-context-DRO74vm5-BbGhhycI.d.mts.map} +1 -1
  96. package/dist/relational-core.d.mts +13 -13
  97. package/dist/relational-core.mjs +4 -4
  98. package/dist/relational-core__aggregate-descriptor-registry.d.mts +1 -1
  99. package/dist/relational-core__aggregate-descriptor-registry.mjs +1 -1
  100. package/dist/relational-core__ast.d.mts +4 -4
  101. package/dist/relational-core__ast.mjs +3 -3
  102. package/dist/relational-core__codec-descriptor-registry.d.mts +2 -2
  103. package/dist/relational-core__collection-methods.d.mts +2 -2
  104. package/dist/relational-core__contract-free.d.mts +2 -2
  105. package/dist/relational-core__contract-free.mjs +1 -1
  106. package/dist/relational-core__contract-free.mjs.map +1 -1
  107. package/dist/relational-core__expression.d.mts +4 -4
  108. package/dist/relational-core__expression.mjs +1 -1
  109. package/dist/relational-core__functions.d.mts +2 -1
  110. package/dist/relational-core__functions.mjs +1 -1
  111. package/dist/relational-core__index-reference.d.mts +2 -2
  112. package/dist/relational-core__middleware.d.mts +2 -2
  113. package/dist/relational-core__plan.d.mts +3 -3
  114. package/dist/relational-core__query-lane-context.d.mts +2 -2
  115. package/dist/relational-core__types.d.mts +2 -2
  116. package/dist/runtime.d.mts +4 -4
  117. package/dist/runtime.mjs +1 -1
  118. package/dist/runtime__internal__prepared-query.d.mts +1 -1
  119. package/dist/{sql-contract-serializer-sMY3prTx-BfYfhVR_.mjs → sql-contract-serializer-sMY3prTx-D_K7uFJk.mjs} +2 -2
  120. package/dist/{sql-contract-serializer-sMY3prTx-BfYfhVR_.mjs.map → sql-contract-serializer-sMY3prTx-D_K7uFJk.mjs.map} +1 -1
  121. package/dist/{sql-execution-plan-CN-FEwrR-BEJ0-g83.d.mts → sql-execution-plan-BeuM3CeD-DIzyMDsA.d.mts} +3 -3
  122. package/dist/sql-execution-plan-BeuM3CeD-DIzyMDsA.d.mts.map +1 -0
  123. package/dist/{transaction-state-DR3nKTmH-Bs2EUG8r.d.mts → transaction-state-DR3nKTmH-DO1YOoZJ.d.mts} +9 -9
  124. package/dist/{transaction-state-DR3nKTmH-Bs2EUG8r.d.mts.map → transaction-state-DR3nKTmH-DO1YOoZJ.d.mts.map} +1 -1
  125. package/dist/{types-COXfSNOP-BKkP-EG1.d.mts → types-COXfSNOP-CA6F1reR.d.mts} +2 -2
  126. package/dist/{types-COXfSNOP-BKkP-EG1.d.mts.map → types-COXfSNOP-CA6F1reR.d.mts.map} +1 -1
  127. package/dist/types-CSORxTRT.d.mts +1 -0
  128. package/dist/{types-ijhejJhK-BqfwP5Cc.d.mts → types-DeimCJiI-CVQS7KCu.d.mts} +12 -9
  129. package/dist/types-DeimCJiI-CVQS7KCu.d.mts.map +1 -0
  130. package/dist/{types-DiPbLKXV-BFa2YXa4.d.mts → types-DpgxiOSn-DrRvhBfy.d.mts} +6 -6
  131. package/dist/{types-DiPbLKXV-BFa2YXa4.d.mts.map → types-DpgxiOSn-DrRvhBfy.d.mts.map} +1 -1
  132. package/dist/{types-BkTuhW3Z-BJfTjcxS.mjs → types-wn1bXh0b-CJPAJi22.mjs} +34 -6
  133. package/dist/types-wn1bXh0b-CJPAJi22.mjs.map +1 -0
  134. package/dist/{validators-qcQteqs2.mjs → validators-CWcdf_jZ.mjs} +6 -6
  135. package/dist/validators-CWcdf_jZ.mjs.map +1 -0
  136. package/package.json +18 -18
  137. package/dist/ast-C3itulLi.mjs.map +0 -1
  138. package/dist/collection-methods-Bmr-a58b.d.mts +0 -1
  139. package/dist/db-D1d75IvM-C88quYVJ.d.mts.map +0 -1
  140. package/dist/dist-CB2NpcCs.mjs +0 -71
  141. package/dist/dist-CB2NpcCs.mjs.map +0 -1
  142. package/dist/expression-4Y1d1hJ_-p9KkcaqT.d.mts.map +0 -1
  143. package/dist/expression-BV_SJGPu.d.mts +0 -2
  144. package/dist/expression-DGu7PRyk-Do_Q7JGF.d.mts.map +0 -1
  145. package/dist/expression-impl-DtbmFnnz-Dal0IYDE.mjs.map +0 -1
  146. package/dist/functions-LZT-hFcE.d.mts +0 -73
  147. package/dist/functions-LZT-hFcE.d.mts.map +0 -1
  148. package/dist/index-reference-BPcC09GP.d.mts +0 -1
  149. package/dist/middleware-Dp3CD7yZ.d.mts +0 -1
  150. package/dist/plan-DINEcqC1.d.mts +0 -2
  151. package/dist/query-lane-context-D0Yc3E72.d.mts +0 -1
  152. package/dist/sql-execution-plan-CN-FEwrR-BEJ0-g83.d.mts.map +0 -1
  153. package/dist/types-B62vy44g.d.mts +0 -1
  154. package/dist/types-BkTuhW3Z-BJfTjcxS.mjs.map +0 -1
  155. package/dist/types-ijhejJhK-BqfwP5Cc.d.mts.map +0 -1
  156. package/dist/validators-qcQteqs2.mjs.map +0 -1
@@ -1,14 +1,13 @@
1
1
  import { t as resolveStorageTable } from "./resolve-storage-table-BHLQsOza.mjs";
2
- import { i as isUniqueConstraintViolation } from "./dist-CB2NpcCs.mjs";
3
- import { A as ParamRef, C as LiteralExpr, E as NullCheckExpr, F as SelectAst, G as isOrderByNulls, I as SubqueryExpr, L as TableSource, M as ProjectionItem, O as OrExpr, R as UpdateAst, S as ListExpression, T as NotExpr, U as isAggregateFn, V as checkLimitOffset, W as isOrderByDirection, _ as InsertAst, b as JsonArrayAggExpr, c as DeleteAst, f as EqColJoinOn, i as CaseExpr, k as OrderByItem, l as DerivedTableSource, n as AndExpr, o as ColumnRef, p as ExistsExpr, q as isWhereExpr, r as BinaryExpr, s as DefaultValueExpr, t as AggregateExpr, v as InsertOnConflict, w as LockingClause, x as JsonObjectExpr, y as JoinAst, z as WindowFuncExpr } from "./types-BkTuhW3Z-BJfTjcxS.mjs";
2
+ import { A as ParamRef, C as LiteralExpr, E as NullCheckExpr, F as SelectAst, G as isOrderByDirection, H as collectTableSources, I as SubqueryExpr, J as isWhereExpr, K as isOrderByNulls, L as TableSource, M as ProjectionItem, O as OrExpr, R as UpdateAst, S as ListExpression, T as NotExpr, V as checkLimitOffset, W as isAggregateFn, _ as InsertAst, b as JsonArrayAggExpr, c as DeleteAst, f as EqColJoinOn, i as CaseExpr, k as OrderByItem, l as DerivedTableSource, n as AndExpr, o as ColumnRef, p as ExistsExpr, r as BinaryExpr, s as DefaultValueExpr, t as AggregateExpr, v as InsertOnConflict, w as LockingClause, x as JsonObjectExpr, y as JoinAst, z as WindowFuncExpr } from "./types-wn1bXh0b-CJPAJi22.mjs";
4
3
  import { t as collectOrderedParamRefs } from "./util-DixeJBri-Cad7x5ec.mjs";
5
- import { D as lockWaitPolicyOf, E as lockStrengthCapabilities, O as missingCapability, T as lockOptionCapabilities, n as JsonDocumentProjection, r as NativeJsonValueProjection, t as CodecJsonValueProjection, w as lockIncompatible } from "./ast-C3itulLi.mjs";
6
- import { a as isExpression, s as toExpr, t as ExpressionImpl } from "./expression-impl-DtbmFnnz-Dal0IYDE.mjs";
4
+ import { D as lockWaitPolicyOf, E as lockStrengthCapabilities, O as missingCapability, T as lockOptionCapabilities, n as JsonDocumentProjection, r as NativeJsonValueProjection, t as CodecJsonValueProjection, w as lockIncompatible } from "./ast-BO3Wgbrl.mjs";
5
+ import { a as isExpression, s as toExpr, t as ExpressionImpl } from "./expression-impl-DHdjzqE3-Cd9gP7oC.mjs";
7
6
  import { n as codecRefForStorageColumn } from "./codec-descriptor-registry-UiFDvDj4.mjs";
8
- import { t as createFunctions } from "./functions-DO1k8KLB.mjs";
7
+ import { t as createFunctions } from "./functions-Cl_egJ2w.mjs";
9
8
  import { t as createIndexReferences } from "./index-reference-BQSrkRfT.mjs";
10
9
  import { o as settlementOf } from "./transaction-state-BfXhs7D7-DhmbySW9.mjs";
11
- import { h as findActivitySource } from "./exports-WNaGWaJR-CVNygh-P.mjs";
10
+ import { h as findActivitySource } from "./exports-WNaGWaJR-C6wltYlN.mjs";
12
11
  import { isStructuredError, structuredError } from "@prisma/orm-framework/utils/structured-error";
13
12
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
14
13
  import { domainModelsAtDefaultNamespace } from "@prisma/orm-framework/contract/types";
@@ -92,7 +91,7 @@ function modelsOf(contract, namespaceId) {
92
91
  function metadataCacheKey(namespaceId, modelName) {
93
92
  return JSON.stringify([namespaceId, modelName]);
94
93
  }
95
- function modelOf(contract, namespaceId, name) {
94
+ function modelOf$1(contract, namespaceId, name) {
96
95
  const model = contract.domain.namespaces[namespaceId]?.models[name];
97
96
  return model === void 0 ? void 0 : blindCast(model);
98
97
  }
@@ -121,7 +120,7 @@ function resolvePolymorphismInfo(contract, namespaceId, modelName) {
121
120
  const mtiVariants = [];
122
121
  for (const [value, variantRef] of Object.entries(model.variants)) {
123
122
  const variantModelName = variantRef.model;
124
- const variantModel = modelOf(contract, variantRef.namespace, variantModelName);
123
+ const variantModel = modelOf$1(contract, variantRef.namespace, variantModelName);
125
124
  if (!variantModel) throw new InternalError(`Model "${modelName}" declares variant "${variantModelName}", but that model is missing from the contract`);
126
125
  const variantTable = variantModel.storage?.table ?? baseTable;
127
126
  const strategy = variantRef.namespace === namespaceId && variantTable === baseTable ? "sti" : "mti";
@@ -167,7 +166,7 @@ function getModelFields(contract, namespaceId, modelName) {
167
166
  namespaceId,
168
167
  modelName
169
168
  ], () => {
170
- const model = modelOf(contract, namespaceId, modelName);
169
+ const model = modelOf$1(contract, namespaceId, modelName);
171
170
  const table = model?.storage?.table;
172
171
  const own = table === void 0 ? {} : Object.fromEntries(Object.entries(getOwnFieldColumns(contract, namespaceId, modelName)).map(([field, column]) => [field, {
173
172
  namespaceId,
@@ -296,7 +295,7 @@ function getUnmappedColumns(contract, namespaceId, modelName) {
296
295
  });
297
296
  }
298
297
  function hierarchyRoot(contract, namespaceId, modelName) {
299
- const base = modelOf(contract, namespaceId, modelName)?.base;
298
+ const base = modelOf$1(contract, namespaceId, modelName)?.base;
300
299
  return base === void 0 ? {
301
300
  namespaceId,
302
301
  modelName
@@ -350,7 +349,7 @@ function getAllTableColumns(contract, namespaceId, tableName) {
350
349
  }
351
350
  }
352
351
  function isMultiTableVariantTable(contract, namespaceId, modelName, tableNamespaceId, tableName) {
353
- const base = modelOf(contract, namespaceId, modelName)?.base;
352
+ const base = modelOf$1(contract, namespaceId, modelName)?.base;
354
353
  return base !== void 0 && namespaceId === tableNamespaceId && domainModelTableInNamespace(contract, namespaceId, modelName) === tableName && (base.namespace !== tableNamespaceId || domainModelTableInNamespace(contract, base.namespace, base.model) !== tableName);
355
354
  }
356
355
  /**
@@ -581,6 +580,9 @@ function assertLockCapability(contract, requirement, methodName) {
581
580
  method: methodName
582
581
  } });
583
582
  }
583
+ function supportsDefaultInInsert(contract) {
584
+ return contract.capabilities["sql"]?.["defaultInInsert"] === true;
585
+ }
584
586
  function hasContractCapability(contract, capability) {
585
587
  const capabilities = contract.capabilities;
586
588
  const value = capabilities[capability];
@@ -1587,159 +1589,6 @@ function compileGroupedAggregate(contract, aggregates, preGroupState, groupByCol
1587
1589
  const { params } = deriveParamsFromAst(ast);
1588
1590
  return buildOrmQueryPlan(contract, ast, params);
1589
1591
  }
1590
- function aliasTarget(namespaceId, tableName) {
1591
- return createTableScope().aliasTable({
1592
- namespaceId,
1593
- tableName
1594
- });
1595
- }
1596
- function projectTableColumn(contract, target, column) {
1597
- const { namespaceId, tableName } = target.storage;
1598
- return ProjectionItem.of(column, target.column(column), codecRefForStorageColumn(contract.storage, namespaceId, tableName, column));
1599
- }
1600
- function projectTableColumns(contract, target, columns) {
1601
- return columns.map((column) => projectTableColumn(contract, target, column));
1602
- }
1603
- function returningProjection(contract, modelName, target, returningColumns) {
1604
- const { namespaceId, tableName } = target.storage;
1605
- return projectTableColumns(contract, target, returningColumns && returningColumns.length > 0 ? [...returningColumns] : getColumnsReadOnTable(contract, namespaceId, modelName, tableName));
1606
- }
1607
- function toParamAssignments(contract, namespaceId, tableName, values) {
1608
- const assignments = {};
1609
- const table = storageTableForContract(contract, namespaceId, tableName);
1610
- for (const [column, value] of Object.entries(values)) {
1611
- if (!table.columns[column]) throw ormError("ORM.COLUMN_UNKNOWN", `Unknown column "${column}" in table "${tableName}"`, { meta: {
1612
- namespaceId,
1613
- tableName,
1614
- column
1615
- } });
1616
- const codec = codecRefForStorageColumn(contract.storage, namespaceId, tableName, column);
1617
- assignments[column] = ParamRef.of(value, {
1618
- name: column,
1619
- ...ifDefined("codec", codec)
1620
- });
1621
- }
1622
- return { assignments };
1623
- }
1624
- function normalizeInsertRows(contract, namespaceId, tableName, rows) {
1625
- if (rows.length === 0) throw new InternalError("normalizeInsertRows requires at least one row");
1626
- const orderedColumns = [];
1627
- const seenColumns = /* @__PURE__ */ new Set();
1628
- for (const row of rows) for (const column of Object.keys(row)) {
1629
- if (seenColumns.has(column)) continue;
1630
- seenColumns.add(column);
1631
- orderedColumns.push(column);
1632
- }
1633
- const table = storageTableForContract(contract, namespaceId, tableName);
1634
- return { rows: rows.map((row) => {
1635
- if (orderedColumns.length === 0) return {};
1636
- const normalizedRow = {};
1637
- for (const column of orderedColumns) {
1638
- if (Object.hasOwn(row, column)) {
1639
- if (!table.columns[column]) throw ormError("ORM.COLUMN_UNKNOWN", `Unknown column "${column}" in table "${tableName}"`, { meta: {
1640
- namespaceId,
1641
- tableName,
1642
- column
1643
- } });
1644
- const codec = codecRefForStorageColumn(contract.storage, namespaceId, tableName, column);
1645
- normalizedRow[column] = ParamRef.of(row[column], {
1646
- name: column,
1647
- ...ifDefined("codec", codec)
1648
- });
1649
- continue;
1650
- }
1651
- normalizedRow[column] = new DefaultValueExpr();
1652
- }
1653
- return normalizedRow;
1654
- }) };
1655
- }
1656
- function conflictSkipClause(target, conflictSkip) {
1657
- if (!conflictSkip) return void 0;
1658
- if (conflictSkip.columns.length === 0) return InsertOnConflict.doNothing();
1659
- return InsertOnConflict.on(conflictSkip.columns.map((column) => target.column(column))).doNothing();
1660
- }
1661
- function insertAst(contract, target, rows, conflictSkip) {
1662
- const { namespaceId, tableName } = target.storage;
1663
- const { rows: normalizedRows } = normalizeInsertRows(contract, namespaceId, tableName, rows);
1664
- return InsertAst.into(target.tableSource(contract)).withRows(normalizedRows).withOnConflict(conflictSkipClause(target, conflictSkip));
1665
- }
1666
- function compileInsertReturning(contract, namespaceId, modelName, tableName, rows, returningColumns, conflictSkip) {
1667
- const target = aliasTarget(namespaceId, tableName);
1668
- const ast = insertAst(contract, target, rows, conflictSkip).withReturning(returningProjection(contract, modelName, target, returningColumns));
1669
- const { params } = deriveParamsFromAst(ast);
1670
- return buildOrmQueryPlan(contract, ast, params);
1671
- }
1672
- function compileInsertCount(contract, namespaceId, tableName, rows, conflictSkip) {
1673
- const ast = insertAst(contract, aliasTarget(namespaceId, tableName), rows, conflictSkip);
1674
- const { params } = deriveParamsFromAst(ast);
1675
- return buildOrmQueryPlan(contract, ast, params);
1676
- }
1677
- function stripUndefinedValues(row) {
1678
- const result = {};
1679
- for (const [key, value] of Object.entries(row)) if (value !== void 0) result[key] = value;
1680
- return result;
1681
- }
1682
- function countMutationWhere(contract, tables, filters, variantValue) {
1683
- const variantTable = variantValue === void 0 ? void 0 : tables.variants.get(variantValue);
1684
- if (variantTable === void 0) return combineWhereExprs(filters);
1685
- const { root } = tables;
1686
- const pkColumns = resolvePrimaryKeyColumns(contract, root.storage.namespaceId, root.storage.tableName);
1687
- const rootCopy = tables.scope.copy().aliasTable(root.storage);
1688
- const where = combineWhereExprs([...pkColumns.map((column) => BinaryExpr.eq(rootCopy.column(column), root.column(column))), ...filters]);
1689
- let subquery = SelectAst.from(rootCopy.tableSource(contract)).withProjection(pkColumns.map((column) => ProjectionItem.of(column, rootCopy.column(column)))).withJoins([JoinAst.inner(variantTable.tableSource(contract), buildPrimaryKeyJoinOn(rootCopy, variantTable, pkColumns))]);
1690
- if (where) subquery = subquery.withWhere(where);
1691
- return ExistsExpr.exists(subquery);
1692
- }
1693
- function groupRowsByColumnSignature(rows) {
1694
- const groups = [];
1695
- let currentKey = "";
1696
- let currentGroup = [];
1697
- for (const rawRow of rows) {
1698
- const row = stripUndefinedValues(rawRow);
1699
- const key = Object.keys(row).sort().join(",");
1700
- if (key !== currentKey || currentGroup.length === 0) {
1701
- if (currentGroup.length > 0) groups.push(currentGroup);
1702
- currentKey = key;
1703
- currentGroup = [row];
1704
- } else currentGroup.push(row);
1705
- }
1706
- if (currentGroup.length > 0) groups.push(currentGroup);
1707
- return groups;
1708
- }
1709
- function upsertAst(contract, target, createValues, conflictColumns, updateSet) {
1710
- const { namespaceId, tableName } = target.storage;
1711
- const createAssignments = toParamAssignments(contract, namespaceId, tableName, createValues);
1712
- const conflictTarget = InsertOnConflict.on(conflictColumns.map((column) => target.column(column)));
1713
- return InsertAst.into(target.tableSource(contract)).withRows([createAssignments.assignments]).withOnConflict(updateSet === void 0 ? conflictTarget.doNothing() : conflictTarget.doUpdateSet(updateSet));
1714
- }
1715
- function updateAssignments(contract, target, values) {
1716
- const { namespaceId, tableName } = target.storage;
1717
- return toParamAssignments(contract, namespaceId, tableName, values).assignments;
1718
- }
1719
- function updateAst(contract, tables, setValues, where) {
1720
- const { root } = tables;
1721
- const { namespaceId, tableName } = root.storage;
1722
- const { assignments } = toParamAssignments(contract, namespaceId, tableName, setValues);
1723
- return UpdateAst.table(root.tableSource(contract)).withSet(assignments).withWhere(where);
1724
- }
1725
- function deleteAst(contract, tables, where) {
1726
- return DeleteAst.from(tables.root.tableSource(contract)).withWhere(where);
1727
- }
1728
- function compileUpdateReturning(contract, modelName, tables, setValues, filters, returningColumns) {
1729
- const ast = updateAst(contract, tables, setValues, combineWhereExprs(filters)).withReturning(returningProjection(contract, modelName, tables.root, returningColumns));
1730
- const { params } = deriveParamsFromAst(ast);
1731
- return buildOrmQueryPlan(contract, ast, params);
1732
- }
1733
- function compileUpdateCount(contract, tables, setValues, filters, variantValue) {
1734
- const ast = updateAst(contract, tables, setValues, countMutationWhere(contract, tables, filters, variantValue));
1735
- const { params } = deriveParamsFromAst(ast);
1736
- return buildOrmQueryPlan(contract, ast, params);
1737
- }
1738
- function compileDeleteCount(contract, tables, filters, variantValue) {
1739
- const ast = deleteAst(contract, tables, countMutationWhere(contract, tables, filters, variantValue));
1740
- const { params } = deriveParamsFromAst(ast);
1741
- return buildOrmQueryPlan(contract, ast, params);
1742
- }
1743
1592
  function includeCarriesLock(include) {
1744
1593
  return [
1745
1594
  include.nested,
@@ -2576,10 +2425,6 @@ function describeCollectionQuery(options) {
2576
2425
  function runQuery(scope, query) {
2577
2426
  return query.consume(queryPlanRows(scope, query.plan));
2578
2427
  }
2579
- function dispatchCollectionRows(options) {
2580
- const { runtime, ...descriptionOptions } = options;
2581
- return describeCollectionQuery(descriptionOptions).rows(runtime);
2582
- }
2583
2428
  function consumeIncludeRows(context, state, namespaceId, modelName, rows) {
2584
2429
  const { contract } = context;
2585
2430
  const generator = async function* () {
@@ -3036,7 +2881,7 @@ function shorthandToWhereExpr(context, namespaceId, modelName, filters, table) {
3036
2881
  return exprs.length === 1 ? exprs[0] : and(...exprs);
3037
2882
  }
3038
2883
  function assertFieldHasEqualityTrait(context, namespaceId, modelName, fieldName) {
3039
- const fieldType = modelOf(context.contract, namespaceId, modelName)?.fields?.[fieldName]?.type;
2884
+ const fieldType = modelOf$1(context.contract, namespaceId, modelName)?.fields?.[fieldName]?.type;
3040
2885
  const codecId = fieldType?.kind === "scalar" ? fieldType.codecId : void 0;
3041
2886
  if (codecId === void 0 || !hasTrait(context, codecId, "equality")) throw ormError("ORM.FILTER_UNSUPPORTED", `Shorthand filter on "${modelName}.${fieldName}": field does not support equality comparisons`, { meta: {
3042
2887
  model: modelName,
@@ -3324,12 +3169,12 @@ function fieldCodecId(collection, field) {
3324
3169
  }
3325
3170
  /** The domain declaration of a model's own or inherited field. */
3326
3171
  function domainFieldOf(contract, namespaceId, modelName, name) {
3327
- let model = modelOf(contract, namespaceId, modelName);
3172
+ let model = modelOf$1(contract, namespaceId, modelName);
3328
3173
  while (model !== void 0) {
3329
3174
  const fields = model.fields ?? {};
3330
3175
  if (Object.hasOwn(fields, name)) return fields[name];
3331
3176
  const base = model.base;
3332
- model = base === void 0 ? void 0 : modelOf(contract, base.namespace, base.model);
3177
+ model = base === void 0 ? void 0 : modelOf$1(contract, base.namespace, base.model);
3333
3178
  }
3334
3179
  }
3335
3180
  function canOrder(collection, field) {
@@ -3342,7 +3187,7 @@ function orderableFieldNames(collection) {
3342
3187
  }
3343
3188
  function whyNotOrderable(collection, name) {
3344
3189
  const { modelName } = collection;
3345
- const model = modelOf(collection.ctx.context.contract, collection.namespaceId, modelName);
3190
+ const model = modelOf$1(collection.ctx.context.contract, collection.namespaceId, modelName);
3346
3191
  const quoted = shown(name).text;
3347
3192
  if (Object.hasOwn(model?.relations ?? {}, name)) return `${quoted} is a relation of ${modelName}, not a field.`;
3348
3193
  if (!Object.hasOwn(getModelFields(collection.ctx.context.contract, collection.namespaceId, modelName), name)) return `${modelName} has no field ${quoted}.`;
@@ -4335,691 +4180,177 @@ function isCollectionState(value) {
4335
4180
  const candidate = value;
4336
4181
  return Array.isArray(candidate.filters) && Array.isArray(candidate.includes);
4337
4182
  }
4338
- function createRelationMutator() {
4339
- return {
4340
- create(data) {
4341
- return {
4342
- kind: "create",
4343
- data: Array.isArray(data) ? [...data] : [data]
4344
- };
4345
- },
4346
- connect(criteria) {
4347
- return {
4348
- kind: "connect",
4349
- criteria: Array.isArray(criteria) ? [...criteria] : [criteria]
4350
- };
4351
- },
4352
- disconnect(criteria) {
4353
- if (!criteria) return { kind: "disconnect" };
4354
- return {
4355
- kind: "disconnect",
4356
- criteria: [...criteria]
4357
- };
4358
- }
4359
- };
4360
- }
4361
- function isRelationMutationDescriptor(value) {
4362
- if (!value || typeof value !== "object") return false;
4363
- const candidate = value;
4364
- if (candidate.kind !== "create" && candidate.kind !== "connect" && candidate.kind !== "disconnect") return false;
4365
- return true;
4366
- }
4367
- function isRelationMutationCallback(value) {
4368
- return typeof value === "function";
4369
- }
4370
- /**
4371
- * The key of each row an insert writes, for reading the rows back without `RETURNING`: the values the client supplies, and at most one auto-increment column, whose value the database reports only for a one-row insert. Refuses, before anything runs, an insert whose rows cannot be found this way.
4372
- */
4373
- function writtenKeys(options) {
4374
- const { context, namespaceId, tableName, modelName, rows, method } = options;
4375
- const identity = readBackIdentity(context.contract, namespaceId, tableName, modelName, method);
4376
- const supplied = identity.filter((column) => rows.every((row) => row[column] !== void 0));
4377
- const keys = rows.map((row) => Object.fromEntries(supplied.map((column) => [column, row[column]])));
4378
- const [column, ...others] = identity.filter((key) => !supplied.includes(key));
4379
- if (column === void 0) return {
4380
- keys,
4381
- generated: void 0
4382
- };
4383
- const refused = (problem) => ormError("ORM.CAPABILITY_MISSING", `${method} on model "${modelName}" ${problem}`, { meta: {
4384
- capability: "returning",
4385
- action: method
4386
- } });
4387
- if (others.length > 0 || !isAutoIncrementColumn(context.contract, namespaceId, tableName, column)) throw refused(`cannot find the row it inserts: key column "${[column, ...others].join("\", \"")}" gets no value from the client and is not an auto-increment column, and the contract does not report capability "returning" to read the value the database chose. Supply the key, or give the column a client-side default.`);
4388
- if (rows.length > 1) throw refused(`cannot return the rows it inserts: their key column "${column}" is generated, and without capability "returning" the database reports a generated value only for a one-row insert. Use createAndCount(), or create() for each row.`);
4389
- const codec = context.contractCodecs.forColumn(namespaceId, tableName, column);
4390
- return {
4391
- keys,
4392
- generated: {
4393
- column,
4394
- decode: async (insertId) => codec === void 0 ? insertId : codec.fromWire(insertId, { column: {
4395
- table: tableName,
4396
- name: column
4397
- } })
4398
- }
4399
- };
4400
- }
4401
- /** The columns a write without `RETURNING` reads its rows back by: the table's row identity, which it must have. */
4402
- function readBackIdentity(contract, namespaceId, tableName, modelName, method) {
4403
- const identity = resolveRowIdentityColumns(contract, namespaceId, tableName);
4404
- if (identity.length > 0) return identity;
4405
- throw ormError("ORM.ROW_IDENTITY_MISSING", `${method} on model "${modelName}" reads the rows it wrote back by key, since the contract does not report capability "returning", so table "${tableName}" needs a primary key or unique constraint`, { meta: {
4406
- model: modelName,
4407
- table: tableName
4408
- } });
4183
+ function projectTableColumn(contract, target, column) {
4184
+ const { namespaceId, tableName } = target.storage;
4185
+ return ProjectionItem.of(column, target.column(column), codecRefForStorageColumn(contract.storage, namespaceId, tableName, column));
4409
4186
  }
4410
- /** The `insertId` a one-row insert reported, or the error that it reported none, which a middleware answering the statement may cause. */
4411
- function reportedInsertId(stats, generated, owner) {
4412
- if (stats.affectedRows === 1 && stats.insertId !== void 0) return stats.insertId;
4413
- throw ormError("ORM.MUTATION_ROW_MISSING", `${owner.operation}() for model "${owner.modelName}" cannot find the row it inserted: the insert's result carried no insert id for key column "${generated.column}". A middleware may have answered the statement in place of the database without one.`, { meta: {
4414
- operation: owner.operation,
4415
- model: owner.modelName,
4416
- phase: "insert-id",
4417
- column: generated.column,
4418
- affectedRows: stats.affectedRows
4419
- } });
4187
+ function projectTableColumns(contract, target, columns) {
4188
+ return columns.map((column) => projectTableColumn(contract, target, column));
4420
4189
  }
4421
- function hasThrough(relation) {
4422
- return relation.through !== void 0;
4190
+ function returningProjection(contract, modelName, target, returningColumns) {
4191
+ const { namespaceId, tableName } = target.storage;
4192
+ return projectTableColumns(contract, target, returningColumns && returningColumns.length > 0 ? [...returningColumns] : getColumnsReadOnTable(contract, namespaceId, modelName, tableName));
4423
4193
  }
4424
- function hasNestedMutationCallbacks(contract, namespaceId, modelName, data) {
4425
- const relationNames = new Set(Object.keys(resolveModelRelations(contract, namespaceId, modelName)));
4426
- for (const [fieldName, value] of Object.entries(data)) {
4427
- if (!relationNames.has(fieldName)) continue;
4428
- if (isRelationMutationCallback(value)) return true;
4194
+ function toParamAssignments(contract, namespaceId, tableName, values) {
4195
+ const assignments = {};
4196
+ const table = storageTableForContract(contract, namespaceId, tableName);
4197
+ for (const [column, value] of Object.entries(values)) {
4198
+ if (!table.columns[column]) throw ormError("ORM.COLUMN_UNKNOWN", `Unknown column "${column}" in table "${tableName}"`, { meta: {
4199
+ namespaceId,
4200
+ tableName,
4201
+ column
4202
+ } });
4203
+ const codec = codecRefForStorageColumn(contract.storage, namespaceId, tableName, column);
4204
+ assignments[column] = ParamRef.of(value, {
4205
+ name: column,
4206
+ ...ifDefined("codec", codec)
4207
+ });
4429
4208
  }
4430
- return false;
4431
- }
4432
- async function executeNestedCreateMutation(options) {
4433
- refuseUnreadableCreate(options.context, options.namespaceId, options.modelName, options.data, []);
4434
- return withMutationScope(options.runtime, async (scope) => createGraph(scope, options.context, options.namespaceId, options.modelName, options.data));
4435
- }
4436
- async function executeNestedUpdateMutation(options) {
4437
- const { context, namespaceId, modelName, data } = options;
4438
- if (!hasContractCapability(context.contract, "returning")) refuseUnreadableRelatedCreates(context, parseMutationInput(context.contract, namespaceId, modelName, data).relationMutations);
4439
- return withMutationScope(options.runtime, async (scope) => updateFirstGraph$1(scope, options.context, options.namespaceId, options.modelName, options.tables, options.filters, options.data));
4209
+ return { assignments };
4440
4210
  }
4441
- /**
4442
- * Without `RETURNING`, each row a nested create inserts is read back by its key. This refuses, before anything runs, a create whose rows could not be found that way: the key values each row gets from its input, a client-side default, or the row it relates to must leave out at most the table's auto-increment column.
4443
- */
4444
- function refuseUnreadableCreate(context, namespaceId, modelName, input, suppliedColumns) {
4445
- const contract = context.contract;
4446
- if (hasContractCapability(contract, "returning")) return;
4447
- const { scalarData, relationMutations } = parseMutationInput(contract, namespaceId, modelName, input);
4448
- const tableName = resolveModelTableName(contract, namespaceId, modelName);
4449
- const row = mapModelDataToStorageRow(contract, namespaceId, modelName, scalarData);
4450
- const defaults = context.applyMutationDefaults({
4451
- op: "create",
4452
- entry: tableName,
4453
- namespace: namespaceId,
4454
- values: { ...row }
4455
- });
4456
- const supplied = [
4457
- ...suppliedColumns,
4458
- ...defaults.map((applied) => applied.field),
4459
- ...partitionByOwnership(relationMutations).parentOwned.flatMap(({ relation }) => relation.localColumns)
4460
- ];
4461
- writtenKeys({
4462
- context,
4463
- namespaceId,
4464
- tableName,
4465
- modelName,
4466
- rows: [{
4467
- ...Object.fromEntries(supplied.map((column) => [column, true])),
4468
- ...row
4469
- }],
4470
- method: "create()"
4471
- });
4472
- refuseUnreadableRelatedCreates(context, relationMutations);
4473
- }
4474
- function refuseUnreadableRelatedCreates(context, relationMutations) {
4475
- const { parentOwned, childOwned } = partitionByOwnership(relationMutations);
4476
- for (const { relation, mutation } of relationMutations) {
4477
- if (mutation.kind !== "create") continue;
4478
- const fromParent = childOwned.some((owned) => owned.relation === relation) ? relation.targetColumns : [];
4479
- const createsOne = parentOwned.some((owned) => owned.relation === relation);
4480
- for (const childInput of createsOne ? mutation.data.slice(0, 1) : mutation.data) refuseUnreadableCreate(context, relation.relatedNamespaceId, relation.relatedModelName, castAs(childInput), fromParent);
4481
- }
4482
- }
4483
- function buildRowIdentityFilterFromRow(contract, namespaceId, modelName, row) {
4484
- const tableName = resolveModelTableName(contract, namespaceId, modelName);
4485
- const identityColumns = resolveRowIdentityColumns(contract, namespaceId, tableName);
4486
- if (identityColumns.length === 0) throw ormError("ORM.ROW_IDENTITY_MISSING", `Nested mutations on model "${modelName}" require table "${tableName}" to have a primary key or unique constraint`, { meta: {
4487
- model: modelName,
4488
- table: tableName
4489
- } });
4490
- const filter = {};
4491
- for (const column of identityColumns) {
4492
- const fieldName = toFieldName(contract, namespaceId, modelName, column);
4493
- const value = row[fieldName];
4494
- if (value === void 0) throw new InternalError(`Missing identity field "${fieldName}" while reloading model "${modelName}"`);
4495
- filter[fieldName] = value;
4496
- }
4497
- return filter;
4498
- }
4499
- async function withMutationScope(runtime, run) {
4500
- if (typeof runtime.transaction === "function") return runInTransaction(await runtime.transaction(), run);
4501
- if (typeof runtime.connection === "function") {
4502
- const connection = await runtime.connection();
4503
- try {
4504
- if (typeof connection.transaction === "function") return await runInTransaction(await connection.transaction(), run);
4505
- return await run(connection);
4506
- } finally {
4507
- await connection.release?.();
4508
- }
4509
- }
4510
- return run(runtime);
4511
- }
4512
- async function runInTransaction(transaction, run) {
4513
- try {
4514
- const result = await run(transaction);
4515
- if (typeof transaction.commit === "function") await transaction.commit();
4516
- return result;
4517
- } catch (error) {
4518
- if (typeof transaction.rollback === "function") try {
4519
- await transaction.rollback();
4520
- } catch (rollbackError) {
4521
- const settlement = settlementOf(transaction);
4522
- if (settlement?.rolledBack !== true) throw rollbackError;
4523
- settlement.logDroppedError(rollbackError);
4524
- }
4525
- throw error;
4526
- }
4527
- }
4528
- async function createGraph(scope, context, namespaceId, modelName, input) {
4529
- const contract = context.contract;
4530
- const parsed = parseMutationInput(contract, namespaceId, modelName, input);
4531
- const { parentOwned, childOwned, junctionOwned } = partitionByOwnership(parsed.relationMutations);
4532
- const scalarData = { ...parsed.scalarData };
4533
- for (const relationMutation of parentOwned) {
4534
- if (relationMutation.mutation.kind === "disconnect") throw ormError("ORM.RELATION_MUTATION_UNSUPPORTED", "disconnect() is only supported in update() nested mutations", { meta: {
4535
- kind: "disconnect",
4536
- relation: relationMutation.relation.relationName
4537
- } });
4538
- await applyParentOwnedMutation(scope, context, namespaceId, modelName, scalarData, relationMutation.relation, relationMutation.mutation);
4539
- }
4540
- for (const relationMutation of junctionOwned) {
4541
- if (relationMutation.mutation.kind === "disconnect") throw ormError("ORM.RELATION_MUTATION_UNSUPPORTED", "disconnect() is only supported in update() nested mutations", { meta: {
4542
- kind: "disconnect",
4543
- relation: relationMutation.relation.relationName
4544
- } });
4545
- await preflightJunctionOwnedCreateMutation(scope, context, relationMutation);
4546
- }
4547
- const parentRow = await insertSingleRow(scope, context, namespaceId, modelName, scalarData);
4548
- for (const relationMutation of childOwned) {
4549
- if (relationMutation.mutation.kind === "disconnect") throw ormError("ORM.RELATION_MUTATION_UNSUPPORTED", "disconnect() is only supported in update() nested mutations", { meta: {
4550
- kind: "disconnect",
4551
- relation: relationMutation.relation.relationName
4552
- } });
4553
- await applyChildOwnedMutation(scope, context, namespaceId, modelName, parentRow, relationMutation.relation, relationMutation.mutation);
4554
- }
4555
- for (const relationMutation of junctionOwned) await applyJunctionOwnedMutation(scope, context, namespaceId, modelName, parentRow, relationMutation.relation, relationMutation.mutation);
4556
- return parentRow;
4557
- }
4558
- async function updateFirstGraph$1(scope, context, namespaceId, modelName, tables, filters, input) {
4559
- const contract = context.contract;
4560
- const existingRow = await findFirstByFilters(scope, contract, namespaceId, modelName, tables, filters);
4561
- if (!existingRow) return null;
4562
- const parsed = parseMutationInput(contract, namespaceId, modelName, input);
4563
- const { parentOwned, childOwned, junctionOwned } = partitionByOwnership(parsed.relationMutations);
4564
- const scalarData = { ...parsed.scalarData };
4565
- for (const relationMutation of parentOwned) await applyParentOwnedMutation(scope, context, namespaceId, modelName, scalarData, relationMutation.relation, relationMutation.mutation);
4566
- for (const relationMutation of junctionOwned) await preflightJunctionOwnedCreateMutation(scope, context, relationMutation);
4567
- let parentRow = existingRow;
4568
- const mappedUpdateData = mapModelDataToStorageRow(contract, namespaceId, modelName, scalarData);
4569
- if (Object.keys(mappedUpdateData).length > 0) {
4570
- const tableName = resolveModelTableName(contract, namespaceId, modelName);
4571
- const appliedUpdateDefaults = context.applyMutationDefaults({
4572
- op: "update",
4573
- entry: tableName,
4574
- namespace: namespaceId,
4575
- values: mappedUpdateData
4576
- });
4577
- for (const def of appliedUpdateDefaults) mappedUpdateData[def.field] = def.value;
4578
- const identityFilter = buildRowIdentityFilterFromRow(contract, namespaceId, modelName, existingRow);
4579
- const identityWhere = shorthandToWhereExpr(context, namespaceId, modelName, castAs(identityFilter), tables.root);
4580
- if (!identityWhere) throw new InternalError(`Failed to build row identity filter for model "${modelName}"`);
4581
- if (hasContractCapability(contract, "returning")) {
4582
- const updatedRaw = (await queryPlanRows(scope, compileUpdateReturning(contract, modelName, tables, mappedUpdateData, [identityWhere], void 0)).toArray())[0];
4583
- if (updatedRaw) parentRow = mapStorageRowToModelFields(contract, namespaceId, modelName, updatedRaw);
4584
- } else {
4585
- await scope.execute(compileUpdateCount(contract, tables, mappedUpdateData, [identityWhere]));
4586
- const updatedIdentity = { ...identityFilter };
4587
- for (const column of readBackIdentity(contract, namespaceId, tableName, modelName, "update()")) if (Object.hasOwn(mappedUpdateData, column)) updatedIdentity[toFieldName(contract, namespaceId, modelName, column)] = mappedUpdateData[column];
4588
- parentRow = await findRowByCriterion(scope, context, namespaceId, modelName, updatedIdentity) ?? parentRow;
4589
- }
4590
- }
4591
- for (const relationMutation of childOwned) await applyChildOwnedMutation(scope, context, namespaceId, modelName, parentRow, relationMutation.relation, relationMutation.mutation);
4592
- for (const relationMutation of junctionOwned) await applyJunctionOwnedMutation(scope, context, namespaceId, modelName, parentRow, relationMutation.relation, relationMutation.mutation);
4593
- return parentRow;
4594
- }
4595
- function parseMutationInput(contract, namespaceId, modelName, input) {
4596
- const scalarData = {};
4597
- const relationDefinitions = new Map(getRelationDefinitions(contract, namespaceId, modelName).map((relation) => [relation.relationName, relation]));
4598
- const relationMutations = [];
4599
- for (const [fieldName, value] of Object.entries(input)) {
4600
- const relation = relationDefinitions.get(fieldName);
4601
- if (!relation) {
4602
- scalarData[fieldName] = value;
4603
- continue;
4604
- }
4605
- if (!isRelationMutationCallback(value)) throw ormError("ORM.RELATION_MUTATION_INVALID", `Relation field "${fieldName}" on model "${modelName}" expects a mutator callback`, { meta: {
4606
- relation: fieldName,
4607
- model: modelName,
4608
- problem: "missing-callback"
4609
- } });
4610
- const mutation = value(createRelationMutator());
4611
- if (!isRelationMutationDescriptor(mutation)) throw ormError("ORM.RELATION_MUTATION_INVALID", `Relation field "${fieldName}" on model "${modelName}" returned an invalid mutation descriptor`, { meta: {
4612
- relation: fieldName,
4613
- model: modelName,
4614
- problem: "invalid-descriptor"
4615
- } });
4616
- relationMutations.push({
4617
- relation,
4618
- mutation
4619
- });
4620
- }
4621
- return {
4622
- scalarData,
4623
- relationMutations
4624
- };
4625
- }
4626
- function partitionByOwnership(relationMutations) {
4627
- const parentOwned = [];
4628
- const childOwned = [];
4629
- const junctionOwned = [];
4630
- for (const relationMutation of relationMutations) {
4631
- if (hasThrough(relationMutation.relation)) {
4632
- junctionOwned.push({
4633
- relation: relationMutation.relation,
4634
- mutation: relationMutation.mutation
4635
- });
4636
- continue;
4637
- }
4638
- if (relationMutation.relation.cardinality === "N:1") {
4639
- parentOwned.push(relationMutation);
4640
- continue;
4641
- }
4642
- childOwned.push(relationMutation);
4643
- }
4644
- return {
4645
- parentOwned,
4646
- childOwned,
4647
- junctionOwned
4648
- };
4649
- }
4650
- async function applyParentOwnedMutation(scope, context, parentNamespaceId, parentModelName, scalarData, relation, mutation) {
4651
- const contract = context.contract;
4652
- if (mutation.kind === "disconnect") {
4653
- for (const localColumn of relation.localColumns) {
4654
- const parentFieldName = toFieldName(contract, parentNamespaceId, parentModelName, localColumn);
4655
- scalarData[parentFieldName] = null;
4656
- }
4657
- return;
4658
- }
4659
- if (mutation.kind === "create") {
4660
- const row = mutation.data[0];
4661
- if (!row) throw ormError("ORM.RELATION_MUTATION_INVALID", `create() nested mutation for relation "${relation.relationName}" requires data`, { meta: {
4662
- kind: "create",
4663
- relation: relation.relationName,
4664
- problem: "missing-data"
4665
- } });
4666
- copyRelatedValuesToParent(contract, parentNamespaceId, parentModelName, relation, scalarData, await createGraph(scope, context, relation.relatedNamespaceId, relation.relatedModelName, castAs(row)));
4667
- return;
4668
- }
4669
- const criterion = mutation.criteria[0];
4670
- if (!criterion) throw ormError("ORM.RELATION_MUTATION_INVALID", `connect() nested mutation for relation "${relation.relationName}" requires criterion`, { meta: {
4671
- kind: "connect",
4672
- relation: relation.relationName,
4673
- problem: "missing-criterion"
4674
- } });
4675
- const relatedRow = await findRowByCriterion(scope, context, relation.relatedNamespaceId, relation.relatedModelName, castAs(criterion));
4676
- if (!relatedRow) throw ormError("ORM.RELATION_ROW_MISSING", `connect() nested mutation for relation "${relation.relationName}" did not find a matching row`, { meta: {
4677
- kind: "connect",
4678
- relation: relation.relationName
4679
- } });
4680
- copyRelatedValuesToParent(contract, parentNamespaceId, parentModelName, relation, scalarData, relatedRow);
4681
- }
4682
- function copyRelatedValuesToParent(contract, parentNamespaceId, parentModelName, relation, scalarData, relatedRow) {
4683
- for (let i = 0; i < relation.localColumns.length; i++) {
4684
- const localColumn = relation.localColumns[i];
4685
- const targetColumn = relation.targetColumns[i];
4686
- if (!localColumn || !targetColumn) continue;
4687
- const parentFieldName = toFieldName(contract, parentNamespaceId, parentModelName, localColumn);
4688
- scalarData[parentFieldName] = relatedRow[toFieldName(contract, relation.relatedNamespaceId, relation.relatedModelName, targetColumn)];
4211
+ function normalizeInsertRows(contract, namespaceId, tableName, rows) {
4212
+ if (rows.length === 0) throw new InternalError("normalizeInsertRows requires at least one row");
4213
+ const orderedColumns = [];
4214
+ const seenColumns = /* @__PURE__ */ new Set();
4215
+ for (const row of rows) for (const column of Object.keys(row)) {
4216
+ if (seenColumns.has(column)) continue;
4217
+ seenColumns.add(column);
4218
+ orderedColumns.push(column);
4689
4219
  }
4690
- }
4691
- async function applyChildOwnedMutation(scope, context, parentNamespaceId, parentModelName, parentRow, relation, mutation) {
4692
- const contract = context.contract;
4693
- const parentValues = readParentColumnValues(contract, parentNamespaceId, parentModelName, relation, parentRow);
4694
- if (mutation.kind === "create") {
4695
- for (const childInput of mutation.data) {
4696
- const payload = { ...castAs(childInput) };
4697
- for (const [childColumn, parentValue] of parentValues.entries()) {
4698
- const childFieldName = toFieldName(contract, relation.relatedNamespaceId, relation.relatedModelName, childColumn);
4699
- payload[childFieldName] = parentValue;
4220
+ const table = storageTableForContract(contract, namespaceId, tableName);
4221
+ return { rows: rows.map((row) => {
4222
+ if (orderedColumns.length === 0) return {};
4223
+ const normalizedRow = {};
4224
+ for (const column of orderedColumns) {
4225
+ if (Object.hasOwn(row, column)) {
4226
+ if (!table.columns[column]) throw ormError("ORM.COLUMN_UNKNOWN", `Unknown column "${column}" in table "${tableName}"`, { meta: {
4227
+ namespaceId,
4228
+ tableName,
4229
+ column
4230
+ } });
4231
+ const codec = codecRefForStorageColumn(contract.storage, namespaceId, tableName, column);
4232
+ normalizedRow[column] = ParamRef.of(row[column], {
4233
+ name: column,
4234
+ ...ifDefined("codec", codec)
4235
+ });
4236
+ continue;
4700
4237
  }
4701
- await createGraph(scope, context, relation.relatedNamespaceId, relation.relatedModelName, castAs(payload));
4702
- }
4703
- return;
4704
- }
4705
- if (mutation.kind === "connect") {
4706
- for (const criterion of mutation.criteria) {
4707
- const related = createRelatedTables(relation);
4708
- const criterionWhere = shorthandToWhereExpr(context, relation.relatedNamespaceId, relation.relatedModelName, castAs(criterion), related.root);
4709
- if (!criterionWhere) throw ormError("ORM.RELATION_MUTATION_INVALID", `connect() nested mutation for relation "${relation.relationName}" requires non-empty criterion`, { meta: {
4710
- kind: "connect",
4711
- relation: relation.relationName,
4712
- problem: "empty-criterion"
4713
- } });
4714
- const setValues = {};
4715
- for (const [childColumn, parentValue] of parentValues.entries()) setValues[childColumn] = parentValue;
4716
- await executeUpdateCount(scope, contract, related, setValues, [criterionWhere]);
4238
+ normalizedRow[column] = new DefaultValueExpr();
4717
4239
  }
4718
- return;
4719
- }
4720
- const setValues = {};
4721
- for (const childColumn of parentValues.keys()) setValues[childColumn] = null;
4722
- if (!mutation.criteria || mutation.criteria.length === 0) {
4723
- const related = createRelatedTables(relation);
4724
- await executeUpdateCount(scope, contract, related, setValues, [buildChildJoinWhere(contract, related.root, parentValues)]);
4725
- return;
4726
- }
4727
- for (const criterion of mutation.criteria) {
4728
- const related = createRelatedTables(relation);
4729
- const criterionWhere = shorthandToWhereExpr(context, relation.relatedNamespaceId, relation.relatedModelName, castAs(criterion), related.root);
4730
- if (!criterionWhere) throw ormError("ORM.RELATION_MUTATION_INVALID", `disconnect() nested mutation for relation "${relation.relationName}" requires non-empty criterion`, { meta: {
4731
- kind: "disconnect",
4732
- relation: relation.relationName,
4733
- problem: "empty-criterion"
4734
- } });
4735
- await executeUpdateCount(scope, contract, related, setValues, [and(buildChildJoinWhere(contract, related.root, parentValues), criterionWhere)]);
4736
- }
4737
- }
4738
- async function applyJunctionOwnedMutation(scope, context, parentNamespaceId, parentModelName, parentRow, relation, mutation) {
4739
- const contract = context.contract;
4740
- const parentPkValues = readJunctionParentValues(contract, parentNamespaceId, parentModelName, relation, parentRow);
4741
- assertJunctionPayloadWritable(relation, mutation.kind);
4742
- if (mutation.kind === "create") {
4743
- for (const childInput of mutation.data) await insertJunctionLink(scope, context, relation, parentPkValues, readJunctionTargetValues(contract, relation, await createGraph(scope, context, relation.relatedNamespaceId, relation.relatedModelName, castAs(childInput))), "create");
4744
- return;
4745
- }
4746
- if (mutation.kind === "connect") {
4747
- for (const criterion of mutation.criteria) await insertJunctionLink(scope, context, relation, parentPkValues, await resolveJunctionTargetValues(scope, context, relation, "connect", criterion), "connect");
4748
- return;
4749
- }
4750
- if (!mutation.criteria || mutation.criteria.length === 0) throw ormError("ORM.RELATION_MUTATION_INVALID", `disconnect() nested mutation for relation "${relation.relationName}" requires criterion`, { meta: {
4751
- kind: "disconnect",
4752
- relation: relation.relationName,
4753
- problem: "missing-criterion"
4754
- } });
4755
- for (const criterion of mutation.criteria) await deleteJunctionLink(scope, context, relation, parentPkValues, await resolveJunctionTargetValues(scope, context, relation, "disconnect", criterion));
4756
- }
4757
- async function preflightJunctionOwnedCreateMutation(scope, context, relationMutation) {
4758
- const { relation, mutation } = relationMutation;
4759
- assertJunctionMetadataShape(relation);
4760
- assertJunctionPayloadWritable(relation, mutation.kind);
4761
- if (mutation.kind !== "connect") return;
4762
- const seenTargetKeys = /* @__PURE__ */ new Set();
4763
- for (const criterion of mutation.criteria) {
4764
- const targetValues = await resolveJunctionTargetValues(scope, context, relation, "connect", criterion);
4765
- const targetKey = JSON.stringify([...targetValues.entries()]);
4766
- if (seenTargetKeys.has(targetKey)) throw ormError("ORM.RELATION_MUTATION_INVALID", `connect() nested mutation for relation "${relation.relationName}" resolved duplicate junction link targets; remove the duplicate criteria`, { meta: {
4767
- kind: "connect",
4768
- relation: relation.relationName,
4769
- problem: "duplicate-criteria"
4770
- } });
4771
- seenTargetKeys.add(targetKey);
4772
- }
4773
- }
4774
- function assertJunctionPayloadWritable(relation, mutationKind) {
4775
- const through = relation.through;
4776
- if (mutationKind !== "create" && mutationKind !== "connect" || through.requiredPayloadColumns.length === 0) return;
4777
- const cols = through.requiredPayloadColumns.map((c) => `\`${c}\``).join(", ");
4778
- throw ormError("ORM.RELATION_MUTATION_UNSUPPORTED", `Cannot \`${mutationKind}\` on relation \`${relation.relationName}\`: its junction \`${through.table}\` has required column(s) ${cols} the relation API can't populate. Write the \`${through.table}\` junction directly or use the SQL builder.`, { meta: {
4779
- kind: mutationKind,
4780
- relation: relation.relationName,
4781
- reason: "junction-required-columns",
4782
- junction: through.table
4783
- } });
4784
- }
4785
- async function resolveJunctionTargetValues(scope, context, relation, kind, criterion) {
4786
- const relatedRow = await findRowByCriterion(scope, context, relation.relatedNamespaceId, relation.relatedModelName, criterion);
4787
- if (!relatedRow) throw ormError("ORM.RELATION_ROW_MISSING", `${kind}() nested mutation for relation "${relation.relationName}" did not find a matching row`, { meta: {
4788
- kind,
4789
- relation: relation.relationName
4790
- } });
4791
- return readJunctionTargetValues(context.contract, relation, relatedRow);
4792
- }
4793
- function readJunctionParentValues(contract, parentNamespaceId, parentModelName, relation, parentRow) {
4794
- const values = /* @__PURE__ */ new Map();
4795
- assertJunctionParentMetadataLength(relation);
4796
- for (let i = 0; i < relation.through.parentColumns.length; i++) {
4797
- const junctionColumn = relation.through.parentColumns[i];
4798
- const parentColumn = relation.localColumns[i];
4799
- if (junctionColumn === void 0 || parentColumn === void 0) throw new InternalError(`Relation "${relation.relationName}" has incomplete junction metadata for parent columns`);
4800
- const parentFieldName = toFieldName(contract, parentNamespaceId, parentModelName, parentColumn);
4801
- const parentValue = parentRow[parentFieldName];
4802
- if (parentValue === void 0) throw new InternalError(`Nested mutation requires parent field "${parentFieldName}" to be present in returned row`);
4803
- values.set(junctionColumn, parentValue);
4804
- }
4805
- return values;
4806
- }
4807
- function readJunctionTargetValues(contract, relation, relatedRow) {
4808
- const values = /* @__PURE__ */ new Map();
4809
- assertJunctionTargetMetadataLength(relation);
4810
- for (let i = 0; i < relation.through.childColumns.length; i++) {
4811
- const junctionColumn = relation.through.childColumns[i];
4812
- const targetColumn = relation.through.targetColumns[i];
4813
- if (junctionColumn === void 0 || targetColumn === void 0) throw new InternalError(`Relation "${relation.relationName}" has incomplete junction metadata for target columns`);
4814
- const targetFieldName = toFieldName(contract, relation.relatedNamespaceId, relation.relatedModelName, targetColumn);
4815
- const targetValue = relatedRow[targetFieldName];
4816
- if (targetValue === void 0) throw new InternalError(`Nested mutation requires target field "${targetFieldName}" to be present in returned row`);
4817
- values.set(junctionColumn, targetValue);
4818
- }
4819
- return values;
4240
+ return normalizedRow;
4241
+ }) };
4820
4242
  }
4821
- function assertJunctionMetadataLength(relation, throughColumnName, throughColumns, pairedColumnName, pairedColumns) {
4822
- if (throughColumns.length === pairedColumns.length) return;
4823
- throw new InternalError(`Relation "${relation.relationName}" has invalid junction metadata: ${throughColumnName} has ${throughColumns.length} column(s), but ${pairedColumnName} has ${pairedColumns.length}`);
4243
+ function conflictSkipClause(target, conflictSkip) {
4244
+ if (!conflictSkip) return void 0;
4245
+ if (conflictSkip.columns.length === 0) return InsertOnConflict.doNothing();
4246
+ return InsertOnConflict.on(conflictSkip.columns.map((column) => target.column(column))).doNothing();
4824
4247
  }
4825
- function assertJunctionParentMetadataLength(relation) {
4826
- assertJunctionMetadataLength(relation, "parentColumns", relation.through.parentColumns, "localColumns", relation.localColumns);
4248
+ function insertAst(contract, target, rows, conflictSkip) {
4249
+ const { namespaceId, tableName } = target.storage;
4250
+ const { rows: normalizedRows } = normalizeInsertRows(contract, namespaceId, tableName, rows);
4251
+ return InsertAst.into(target.tableSource(contract)).withRows(normalizedRows).withOnConflict(conflictSkipClause(target, conflictSkip));
4827
4252
  }
4828
- function assertJunctionTargetMetadataLength(relation) {
4829
- assertJunctionMetadataLength(relation, "childColumns", relation.through.childColumns, "targetColumns", relation.through.targetColumns);
4253
+ function stripUndefinedValues(row) {
4254
+ const result = {};
4255
+ for (const [key, value] of Object.entries(row)) if (value !== void 0) result[key] = value;
4256
+ return result;
4830
4257
  }
4831
- function assertJunctionMetadataShape(relation) {
4832
- assertJunctionParentMetadataLength(relation);
4833
- assertJunctionTargetMetadataLength(relation);
4258
+ function countMutationWhere(contract, tables, filters, variantValue) {
4259
+ const variantTable = variantValue === void 0 ? void 0 : tables.variants.get(variantValue);
4260
+ if (variantTable === void 0) return combineWhereExprs(filters);
4261
+ const { root } = tables;
4262
+ const pkColumns = resolvePrimaryKeyColumns(contract, root.storage.namespaceId, root.storage.tableName);
4263
+ const rootCopy = tables.scope.copy().aliasTable(root.storage);
4264
+ const where = combineWhereExprs([...pkColumns.map((column) => BinaryExpr.eq(rootCopy.column(column), root.column(column))), ...filters]);
4265
+ let subquery = SelectAst.from(rootCopy.tableSource(contract)).withProjection(pkColumns.map((column) => ProjectionItem.of(column, rootCopy.column(column)))).withJoins([JoinAst.inner(variantTable.tableSource(contract), buildPrimaryKeyJoinOn(rootCopy, variantTable, pkColumns))]);
4266
+ if (where) subquery = subquery.withWhere(where);
4267
+ return ExistsExpr.exists(subquery);
4834
4268
  }
4835
- function writeJunctionColumn(junctionRow, through, column, value, relationName) {
4836
- if (Object.hasOwn(junctionRow, column) && !Object.is(junctionRow[column], value)) throw ormError("ORM.RELATION_MUTATION_INVALID", `Cannot write junction "${through.table}": conflicting values for junction column "${column}"`, { meta: {
4837
- relation: relationName,
4838
- junction: through.table,
4839
- column
4840
- } });
4841
- junctionRow[column] = value;
4842
- }
4843
- async function insertJunctionLink(scope, context, relation, parentPkValues, targetPkValues, mutationKind) {
4844
- const through = relation.through;
4845
- const junctionRow = {};
4846
- for (const [column, value] of parentPkValues.entries()) writeJunctionColumn(junctionRow, through, column, value, relation.relationName);
4847
- for (const [column, value] of targetPkValues.entries()) writeJunctionColumn(junctionRow, through, column, value, relation.relationName);
4848
- const applied = context.applyMutationDefaults({
4849
- op: "create",
4850
- entry: through.table,
4851
- namespace: through.namespaceId,
4852
- values: junctionRow
4853
- });
4854
- for (const def of applied) junctionRow[def.field] = def.value;
4855
- const compiled = compileInsertCount(context.contract, through.namespaceId, through.table, [junctionRow]);
4856
- try {
4857
- await scope.execute(compiled);
4858
- } catch (error) {
4859
- if (mutationKind === "connect" && isUniqueConstraintViolation(error)) throw ormError("ORM.RELATION_LINK_DUPLICATE", `connect() nested mutation for relation "${relation.relationName}" violated a unique constraint on junction "${through.table}"; the junction link may already be present`, {
4860
- meta: {
4861
- relation: relation.relationName,
4862
- junction: through.table
4863
- },
4864
- cause: error
4865
- });
4866
- throw error;
4269
+ function groupRowsByColumnSignature(rows) {
4270
+ const groups = [];
4271
+ let currentKey = "";
4272
+ let currentGroup = [];
4273
+ for (const rawRow of rows) {
4274
+ const row = stripUndefinedValues(rawRow);
4275
+ const key = Object.keys(row).sort().join(",");
4276
+ if (key !== currentKey || currentGroup.length === 0) {
4277
+ if (currentGroup.length > 0) groups.push(currentGroup);
4278
+ currentKey = key;
4279
+ currentGroup = [row];
4280
+ } else currentGroup.push(row);
4867
4281
  }
4282
+ if (currentGroup.length > 0) groups.push(currentGroup);
4283
+ return groups;
4868
4284
  }
4869
- async function deleteJunctionLink(scope, context, relation, parentPkValues, targetPkValues) {
4870
- const through = relation.through;
4871
- const junctionRow = {};
4872
- for (const [column, value] of parentPkValues.entries()) writeJunctionColumn(junctionRow, through, column, value, relation.relationName);
4873
- for (const [column, value] of targetPkValues.entries()) writeJunctionColumn(junctionRow, through, column, value, relation.relationName);
4874
- const junction = createStatementTables({
4875
- namespaceId: through.namespaceId,
4876
- tableName: through.table
4877
- });
4878
- const exprs = [];
4879
- for (const [column, value] of Object.entries(junctionRow)) exprs.push(BinaryExpr.eq(junction.root.column(column), paramRefForStorageColumn(context.contract, junction.root.storage, column, value)));
4880
- const first = exprs[0];
4881
- const where = exprs.length === 1 && first !== void 0 ? first : and(...exprs);
4882
- const compiled = compileDeleteCount(context.contract, junction, [where]);
4883
- await scope.execute(compiled);
4884
- }
4885
- function readParentColumnValues(contract, parentNamespaceId, parentModelName, relation, parentRow) {
4886
- const values = /* @__PURE__ */ new Map();
4887
- for (let i = 0; i < relation.localColumns.length; i++) {
4888
- const localColumn = relation.localColumns[i];
4889
- const targetColumn = relation.targetColumns[i];
4890
- if (!localColumn || !targetColumn) continue;
4891
- const parentFieldName = toFieldName(contract, parentNamespaceId, parentModelName, localColumn);
4892
- const parentValue = parentRow[parentFieldName];
4893
- if (parentValue === void 0) throw new InternalError(`Nested mutation requires parent field "${parentFieldName}" to be present in returned row`);
4894
- values.set(targetColumn, parentValue);
4895
- }
4896
- return values;
4285
+ function upsertAst(contract, target, createValues, conflictColumns, updateSet) {
4286
+ const { namespaceId, tableName } = target.storage;
4287
+ const createAssignments = toParamAssignments(contract, namespaceId, tableName, createValues);
4288
+ const conflictTarget = InsertOnConflict.on(conflictColumns.map((column) => target.column(column)));
4289
+ return InsertAst.into(target.tableSource(contract)).withRows([createAssignments.assignments]).withOnConflict(updateSet === void 0 ? conflictTarget.doNothing() : conflictTarget.doUpdateSet(updateSet));
4897
4290
  }
4898
- function createRelatedTables(relation) {
4899
- return createStatementTables({
4900
- namespaceId: relation.relatedNamespaceId,
4901
- tableName: relation.relatedTableName
4902
- });
4291
+ function updateAssignments(contract, target, values) {
4292
+ const { namespaceId, tableName } = target.storage;
4293
+ return toParamAssignments(contract, namespaceId, tableName, values).assignments;
4903
4294
  }
4904
- function buildChildJoinWhere(contract, related, childValues) {
4905
- const exprs = [];
4906
- for (const [childColumn, parentValue] of childValues.entries()) exprs.push(BinaryExpr.eq(related.column(childColumn), paramRefForStorageColumn(contract, related.storage, childColumn, parentValue)));
4907
- const first = exprs[0];
4908
- if (exprs.length === 1 && first !== void 0) return first;
4909
- return and(...exprs);
4295
+ function updateAst(contract, tables, setValues, where) {
4296
+ const { root } = tables;
4297
+ const { namespaceId, tableName } = root.storage;
4298
+ const { assignments } = toParamAssignments(contract, namespaceId, tableName, setValues);
4299
+ return UpdateAst.table(root.tableSource(contract)).withSet(assignments).withWhere(where);
4910
4300
  }
4911
- async function insertSingleRow(scope, context, namespaceId, modelName, data) {
4912
- const contract = context.contract;
4913
- const tableName = resolveModelTableName(contract, namespaceId, modelName);
4914
- const mappedData = mapModelDataToStorageRow(contract, namespaceId, modelName, data);
4915
- const applied = context.applyMutationDefaults({
4916
- op: "create",
4917
- entry: tableName,
4918
- namespace: namespaceId,
4919
- values: mappedData
4920
- });
4921
- for (const def of applied) mappedData[def.field] = def.value;
4922
- if (!hasContractCapability(contract, "returning")) return insertAndReadBack(scope, context, namespaceId, modelName, tableName, mappedData);
4923
- const firstRow = (await queryPlanRows(scope, compileInsertReturning(contract, namespaceId, modelName, tableName, [mappedData], void 0)).toArray())[0];
4924
- if (!firstRow) throw ormError("ORM.MUTATION_ROW_MISSING", `Nested create for model "${modelName}" did not return a row`, { meta: {
4925
- operation: "create",
4926
- model: modelName,
4927
- phase: "nested"
4928
- } });
4929
- return mapStorageRowToModelFields(contract, namespaceId, modelName, firstRow);
4301
+ function deleteAst(contract, tables, where) {
4302
+ return DeleteAst.from(tables.root.tableSource(contract)).withWhere(where);
4930
4303
  }
4931
- async function insertAndReadBack(scope, context, namespaceId, modelName, tableName, row) {
4932
- const contract = context.contract;
4933
- const { keys: [suppliedKey = {}], generated } = writtenKeys({
4934
- context,
4935
- namespaceId,
4936
- tableName,
4937
- modelName,
4938
- rows: [row],
4939
- method: "create()"
4940
- });
4941
- const stats = await scope.execute(compileInsertCount(contract, namespaceId, tableName, [row]));
4942
- const key = generated === void 0 ? suppliedKey : {
4943
- ...suppliedKey,
4944
- [generated.column]: await generated.decode(reportedInsertId(stats, generated, {
4945
- operation: "create",
4946
- modelName
4947
- }))
4304
+ /**
4305
+ * The key of each row an insert writes, for reading the rows back without `RETURNING`: the values the client supplies, and at most one auto-increment column, whose value the database reports only for a one-row insert. Refuses, before anything runs, an insert whose rows cannot be found this way.
4306
+ */
4307
+ function writtenKeys(options) {
4308
+ const { context, namespaceId, tableName, modelName, rows, method } = options;
4309
+ const identity = readBackIdentity(context.contract, namespaceId, tableName, modelName, method);
4310
+ const supplied = identity.filter((column) => rows.every((row) => row[column] !== void 0));
4311
+ const keys = rows.map((row) => Object.fromEntries(supplied.map((column) => [column, row[column]])));
4312
+ const [column, ...others] = identity.filter((key) => !supplied.includes(key));
4313
+ if (column === void 0) return {
4314
+ keys,
4315
+ generated: void 0
4948
4316
  };
4949
- const created = await findRowByCriterion(scope, context, namespaceId, modelName, Object.fromEntries(Object.entries(key).map(([column, value]) => [toFieldName(contract, namespaceId, modelName, column), value])));
4950
- if (!created) throw ormError("ORM.MUTATION_ROW_MISSING", `Nested create for model "${modelName}" did not find the row it inserted`, { meta: {
4951
- operation: "create",
4952
- model: modelName,
4953
- phase: "nested"
4317
+ const refused = (problem) => ormError("ORM.CAPABILITY_MISSING", `${method} on model "${modelName}" ${problem}`, { meta: {
4318
+ capability: "returning",
4319
+ action: method
4954
4320
  } });
4955
- return created;
4321
+ if (others.length > 0 || !isAutoIncrementColumn(context.contract, namespaceId, tableName, column)) throw refused(`cannot find the row it inserts: key column "${[column, ...others].join("\", \"")}" gets no value from the client and is not an auto-increment column, and the contract does not report capability "returning" to read the value the database chose. Supply the key, or give the column a client-side default.`);
4322
+ if (rows.length > 1) throw refused(`cannot return the rows it inserts: their key column "${column}" is generated, and without capability "returning" the database reports a generated value only for a one-row insert. Use createAndCount(), or create() for each row.`);
4323
+ const codec = context.contractCodecs.forColumn(namespaceId, tableName, column);
4324
+ return {
4325
+ keys,
4326
+ generated: {
4327
+ column,
4328
+ decode: async (insertId) => codec === void 0 ? insertId : codec.fromWire(insertId, { column: {
4329
+ table: tableName,
4330
+ name: column
4331
+ } })
4332
+ }
4333
+ };
4956
4334
  }
4957
- async function findRowByCriterion(scope, context, namespaceId, modelName, criterion) {
4958
- const contract = context.contract;
4959
- const tables = createStatementTables({
4960
- namespaceId,
4961
- tableName: resolveModelTableName(contract, namespaceId, modelName)
4962
- });
4963
- const whereExpr = shorthandToWhereExpr(context, namespaceId, modelName, castAs(criterion), tables.root);
4964
- if (!whereExpr) throw ormError("ORM.RELATION_MUTATION_INVALID", `Nested connect for model "${modelName}" requires non-empty criterion`, { meta: {
4965
- kind: "connect",
4335
+ /** The columns a write without `RETURNING` reads its rows back by: the table's row identity, which it must have. */
4336
+ function readBackIdentity(contract, namespaceId, tableName, modelName, method) {
4337
+ const identity = resolveRowIdentityColumns(contract, namespaceId, tableName);
4338
+ if (identity.length > 0) return identity;
4339
+ throw ormError("ORM.ROW_IDENTITY_MISSING", `${method} on model "${modelName}" reads the rows it wrote back by key, since the contract does not report capability "returning", so table "${tableName}" needs a primary key or unique constraint`, { meta: {
4966
4340
  model: modelName,
4967
- problem: "empty-criterion"
4341
+ table: tableName
4968
4342
  } });
4969
- const firstRow = (await queryPlanRows(scope, compileSelect(contract, modelName, {
4970
- ...emptyState(tables),
4971
- filters: [whereExpr],
4972
- limit: 1
4973
- })).toArray())[0];
4974
- if (!firstRow) return null;
4975
- return mapStorageRowToModelFields(contract, namespaceId, modelName, firstRow);
4976
- }
4977
- async function findFirstByFilters(scope, contract, namespaceId, modelName, tables, filters) {
4978
- const firstRow = (await queryPlanRows(scope, compileSelect(contract, modelName, {
4979
- ...emptyState(tables),
4980
- filters,
4981
- limit: 1
4982
- })).toArray())[0];
4983
- if (!firstRow) return null;
4984
- return mapStorageRowToModelFields(contract, namespaceId, modelName, firstRow);
4985
- }
4986
- async function executeUpdateCount(scope, contract, tables, setValues, filters) {
4987
- const compiled = compileUpdateCount(contract, tables, setValues, filters);
4988
- await scope.execute(compiled);
4989
4343
  }
4990
- const relationDefsCache = /* @__PURE__ */ new WeakMap();
4991
- function getRelationDefinitions(contract, namespaceId, modelName) {
4992
- let perContract = relationDefsCache.get(contract);
4993
- if (!perContract) {
4994
- perContract = /* @__PURE__ */ new Map();
4995
- relationDefsCache.set(contract, perContract);
4996
- }
4997
- const cacheKey = JSON.stringify([namespaceId, modelName]);
4998
- const cached = perContract.get(cacheKey);
4999
- if (cached) return cached;
5000
- const relations = resolveModelRelations(contract, namespaceId, modelName);
5001
- const definitions = Object.entries(relations).map(([relationName, relation]) => ({
5002
- relationName,
5003
- relatedModelName: relation.to,
5004
- relatedNamespaceId: relation.toNamespace,
5005
- relatedTableName: resolveModelTableName(contract, relation.toNamespace, relation.to),
5006
- cardinality: relation.cardinality,
5007
- localColumns: relation.on.localFields.map((f) => columnOfContractField(contract, namespaceId, modelName, f)),
5008
- targetColumns: resolveRelationTargetColumns(contract, relation),
5009
- through: relation.through ? {
5010
- table: relation.through.table,
5011
- namespaceId: relation.through.namespaceId,
5012
- parentColumns: relation.through.parentColumns,
5013
- childColumns: relation.through.childColumns,
5014
- targetColumns: relation.through.targetColumns,
5015
- requiredPayloadColumns: relation.through.requiredPayloadColumns
5016
- } : void 0
5017
- }));
5018
- perContract.set(cacheKey, definitions);
5019
- return definitions;
5020
- }
5021
- function toFieldName(contract, namespaceId, modelName, columnName) {
5022
- return fieldOfColumn(getModelColumnFields(contract, namespaceId, modelName), modelName, columnName);
4344
+ /** The `insertId` a one-row insert reported, or the error that it reported none, which a middleware answering the statement may cause. */
4345
+ function reportedInsertId(stats, generated, owner) {
4346
+ if (stats.affectedRows === 1 && stats.insertId !== void 0) return stats.insertId;
4347
+ throw ormError("ORM.MUTATION_ROW_MISSING", `${owner.operation}() for model "${owner.modelName}" cannot find the row it inserted: the insert's result carried no insert id for key column "${generated.column}". A middleware may have answered the statement in place of the database without one.`, { meta: {
4348
+ operation: owner.operation,
4349
+ model: owner.modelName,
4350
+ phase: "insert-id",
4351
+ column: generated.column,
4352
+ affectedRows: stats.affectedRows
4353
+ } });
5023
4354
  }
5024
4355
  var Node = class {};
5025
4356
  function executeStatement$1(ast, run) {
@@ -5032,21 +4363,55 @@ function rowsResult(rows) {
5032
4363
  return new AsyncIterableResult(generator());
5033
4364
  }
5034
4365
  var CrossJoin = class extends Node {
4366
+ slots = {
4367
+ left: "one",
4368
+ right: "one"
4369
+ };
5035
4370
  constructor() {
5036
4371
  super();
5037
4372
  Object.freeze(this);
5038
4373
  }
5039
- execute(inputs, _run) {
5040
- const [left] = inputs.left;
5041
- const [right] = inputs.right;
5042
- if (left === void 0 || right === void 0) return rowsResult([]);
5043
- return rowsResult([{
5044
- ...left,
5045
- ...right
5046
- }]);
4374
+ execute(inputs, _run) {
4375
+ const [left] = inputs.left;
4376
+ const [right] = inputs.right;
4377
+ if (left === void 0 || right === void 0) return rowsResult([]);
4378
+ return rowsResult([{
4379
+ ...left,
4380
+ ...right
4381
+ }]);
4382
+ }
4383
+ };
4384
+ var Edge = class {
4385
+ from;
4386
+ constructor(from) {
4387
+ this.from = from;
4388
+ }
4389
+ };
4390
+ var DataEdge = class extends Edge {
4391
+ columns;
4392
+ constructor(from, columns) {
4393
+ super(from);
4394
+ this.columns = Object.freeze([...columns]);
4395
+ }
4396
+ };
4397
+ var Requires = class extends Edge {
4398
+ constructor(from) {
4399
+ super(from);
4400
+ Object.freeze(this);
5047
4401
  }
4402
+ output() {}
5048
4403
  };
5049
- function executeFiltered(ast, filter, run) {
4404
+ function requirementUnmet(requires) {
4405
+ return requires?.some((rows) => rows.length === 0) === true;
4406
+ }
4407
+ const filteredSlots = {
4408
+ filter: "list",
4409
+ state: "list",
4410
+ requires: "list"
4411
+ };
4412
+ function executeFiltered(ast, inputs, run) {
4413
+ const { filter } = inputs;
4414
+ if (requirementUnmet(inputs.requires)) return rowsResult([]);
5050
4415
  if (filter === null) return executeStatement$1(ast, run);
5051
4416
  if (filter.some((conditions) => conditions.length === 0)) return rowsResult([]);
5052
4417
  const where = combineWhereExprs([...ast.where === void 0 ? [] : [ast.where], ...filter.map(anyOf)]);
@@ -5073,29 +4438,25 @@ function withColumns(returned, columns) {
5073
4438
  return [...returned, ...columns.filter((column) => !present.has(column.alias))];
5074
4439
  }
5075
4440
  var StatementNode = class extends Node {};
5076
- var Delete = class Delete extends StatementNode {
4441
+ var Find = class Find extends StatementNode {
4442
+ slots = filteredSlots;
5077
4443
  ast;
5078
4444
  constructor(ast) {
5079
4445
  super();
5080
4446
  this.ast = ast;
5081
4447
  Object.freeze(this);
5082
4448
  }
4449
+ get statements() {
4450
+ return [this.ast];
4451
+ }
5083
4452
  get returns() {
5084
- return this.ast.returning ?? [];
4453
+ return this.ast.projection;
5085
4454
  }
5086
4455
  execute(inputs, run) {
5087
- return executeFiltered(this.ast, inputs.filter, run);
4456
+ return executeFiltered(this.ast, inputs, run);
5088
4457
  }
5089
4458
  withReturning(columns) {
5090
- return new Delete(this.ast.withReturning(withColumns(this.returns, columns)));
5091
- }
5092
- };
5093
- var Edge = class {
5094
- from;
5095
- columns;
5096
- constructor(from, columns) {
5097
- this.from = from;
5098
- this.columns = Object.freeze([...columns]);
4459
+ return new Find(this.ast.withProjection(withColumns(this.returns, columns)));
5099
4460
  }
5100
4461
  };
5101
4462
  /** The condition that matches the row whose source columns hold the values in `sourceRow`. */
@@ -5108,249 +4469,1083 @@ function keyCondition(columns, sourceRow) {
5108
4469
  return first !== void 0 && others.length === 0 ? first : AndExpr.of(conditions);
5109
4470
  }
5110
4471
  /** Matches each source row's row in the reading statement. `changed` holds new values, by source column, that a write between the two gave every row. */
5111
- var FilterData = class extends Edge {
4472
+ var FilterData = class extends DataEdge {
5112
4473
  changed;
5113
4474
  constructor(from, columns, changed = {}) {
5114
4475
  super(from, columns);
5115
4476
  this.changed = changed;
5116
4477
  Object.freeze(this);
5117
4478
  }
5118
- output(sourceRow) {
5119
- return keyCondition(this.columns, {
5120
- ...sourceRow,
5121
- ...this.changed
5122
- });
4479
+ output(sourceRow) {
4480
+ return keyCondition(this.columns, {
4481
+ ...sourceRow,
4482
+ ...this.changed
4483
+ });
4484
+ }
4485
+ };
4486
+ /** Keys per read-back statement. The `ORDER BY CASE` costs the database the number of keys times the number of rows it returns, so the keys are read in chunks of this size. */
4487
+ const KEYS_PER_STATEMENT = 500;
4488
+ /**
4489
+ * Reads the rows an insert wrote back by their keys, for a database without `RETURNING`, in the order the insert wrote them, and fails when it finds fewer rows than keys, so the transaction rolls back. It reads at most 500 keys per statement.
4490
+ *
4491
+ * A `Find` with a `FilterData` edge cannot do this: the edge hands the `Find` conditions, not the key values, so the `Find` cannot order the rows by key or count the keys. The database does both comparisons, with its own rules for collation and precision: each key's condition both selects its row and, in an `ORDER BY CASE`, places it.
4492
+ */
4493
+ var FindByKeys = class FindByKeys extends StatementNode {
4494
+ slots = {
4495
+ keys: "one",
4496
+ state: "list",
4497
+ requires: "list"
4498
+ };
4499
+ ast;
4500
+ keyColumns;
4501
+ owner;
4502
+ constructor(ast, keyColumns, owner) {
4503
+ super();
4504
+ this.ast = ast;
4505
+ this.keyColumns = Object.freeze([...keyColumns]);
4506
+ this.owner = owner;
4507
+ Object.freeze(this);
4508
+ }
4509
+ get statements() {
4510
+ return [this.ast];
4511
+ }
4512
+ get returns() {
4513
+ return this.ast.projection;
4514
+ }
4515
+ execute(inputs, run) {
4516
+ const keys = inputs.keys;
4517
+ if (requirementUnmet(inputs.requires) || keys.length === 0) return rowsResult([]);
4518
+ const chunks = Array.from({ length: Math.ceil(keys.length / KEYS_PER_STATEMENT) }, (_, index) => keys.slice(index * KEYS_PER_STATEMENT, (index + 1) * KEYS_PER_STATEMENT));
4519
+ const { owner } = this;
4520
+ const statementFor = (chunk) => this.#statementFor(chunk);
4521
+ const generator = async function* () {
4522
+ for (const chunk of chunks) {
4523
+ const rows = await run.query(statementFor(chunk)).toArray();
4524
+ if (rows.length < chunk.length) throw ormError("ORM.MUTATION_ROW_MISSING", `${owner.operation}() for model "${owner.modelName}" did not find the row it wrote`, { meta: {
4525
+ operation: owner.operation,
4526
+ model: owner.modelName,
4527
+ phase: "read-back"
4528
+ } });
4529
+ yield* rows;
4530
+ }
4531
+ };
4532
+ return new AsyncIterableResult(generator());
4533
+ }
4534
+ #statementFor(keys) {
4535
+ const conditions = keys.map((key) => keyCondition(this.keyColumns, key));
4536
+ const existing = this.ast.where === void 0 ? [] : [this.ast.where];
4537
+ const found = this.ast.withWhere(combineWhereExprs([...existing, anyOf(conditions)]));
4538
+ return conditions.length === 1 ? found : found.withOrderBy([OrderByItem.asc(CaseExpr.of(conditions.map((condition, position) => ({
4539
+ condition,
4540
+ value: LiteralExpr.of(position)
4541
+ }))))]);
4542
+ }
4543
+ withReturning(columns) {
4544
+ return new FindByKeys(this.ast.withProjection(withColumns(this.returns, columns)), this.keyColumns, this.owner);
4545
+ }
4546
+ };
4547
+ function tableKey(table) {
4548
+ return JSON.stringify([table.namespaceId, table.tableName]);
4549
+ }
4550
+ function changedBy(contract, write, table) {
4551
+ if (write === "insert") return [table];
4552
+ return cachedFor(contract, [
4553
+ "changedBy",
4554
+ write,
4555
+ table.namespaceId,
4556
+ table.tableName
4557
+ ], () => {
4558
+ const changed = /* @__PURE__ */ new Map([[tableKey(table), table]]);
4559
+ const visited = /* @__PURE__ */ new Set([stepKey({
4560
+ table,
4561
+ kind: write
4562
+ })]);
4563
+ const pending = [{
4564
+ table,
4565
+ kind: write
4566
+ }];
4567
+ for (let step = pending.shift(); step !== void 0; step = pending.shift()) for (const reference of referencesTo(contract, step.table)) {
4568
+ const next = nextStep(step.kind, reference);
4569
+ if (next !== void 0 && !visited.has(stepKey(next))) {
4570
+ visited.add(stepKey(next));
4571
+ changed.set(tableKey(next.table), next.table);
4572
+ pending.push(next);
4573
+ }
4574
+ }
4575
+ return Object.freeze([...changed.values()]);
4576
+ });
4577
+ }
4578
+ function referencesTo(contract, target) {
4579
+ return Object.entries(contract.storage.namespaces).flatMap(([namespaceId, namespace]) => Object.entries(namespace.entries.table ?? {}).flatMap(([tableName, table]) => table.foreignKeys.filter((foreignKey) => foreignKey.target.namespaceId === target.namespaceId && foreignKey.target.tableName === target.tableName).map((foreignKey) => ({
4580
+ table: {
4581
+ namespaceId,
4582
+ tableName
4583
+ },
4584
+ onDelete: foreignKey.onDelete,
4585
+ onUpdate: foreignKey.onUpdate
4586
+ }))));
4587
+ }
4588
+ function nextStep(kind, reference) {
4589
+ switch (kind === "delete" ? reference.onDelete : reference.onUpdate) {
4590
+ case "cascade": return {
4591
+ table: reference.table,
4592
+ kind
4593
+ };
4594
+ case "setNull":
4595
+ case "setDefault": return {
4596
+ table: reference.table,
4597
+ kind: "update"
4598
+ };
4599
+ default: return;
4600
+ }
4601
+ }
4602
+ function stepKey(step) {
4603
+ return JSON.stringify([
4604
+ step.kind,
4605
+ step.table.namespaceId,
4606
+ step.table.tableName
4607
+ ]);
4608
+ }
4609
+ var PayloadData = class extends DataEdge {
4610
+ constructor(from, columns) {
4611
+ super(from, columns);
4612
+ Object.freeze(this);
4613
+ }
4614
+ output(sourceRow) {
4615
+ return Object.fromEntries(this.columns.map(([source, target]) => [target.alias, ParamRef.of(sourceRow[source.alias], {
4616
+ name: target.alias,
4617
+ ...ifDefined("codec", target.codec)
4618
+ })]));
4619
+ }
4620
+ };
4621
+ var Rows = class extends DataEdge {
4622
+ constructor(from, columns) {
4623
+ super(from, columns);
4624
+ Object.freeze(this);
4625
+ }
4626
+ output(sourceRow) {
4627
+ return Object.fromEntries(this.columns.map(([source]) => [source.alias, sourceRow[source.alias]]));
4628
+ }
4629
+ };
4630
+ var StateEdge = class extends Edge {
4631
+ table;
4632
+ constructor(from, table) {
4633
+ super(from);
4634
+ this.table = table;
4635
+ Object.freeze(this);
4636
+ }
4637
+ output() {}
4638
+ };
4639
+ var State = class extends Node {
4640
+ slots = { write: "list" };
4641
+ table;
4642
+ constructor(table) {
4643
+ super();
4644
+ this.table = table;
4645
+ Object.freeze(this);
4646
+ }
4647
+ execute(_inputs, _run) {
4648
+ return rowsResult([]);
4649
+ }
4650
+ };
4651
+ var Graph = class {
4652
+ #contract;
4653
+ #ids = [];
4654
+ #nodes = [];
4655
+ #inputs = [];
4656
+ #readers = [];
4657
+ #states = /* @__PURE__ */ new Map();
4658
+ #result = void 0;
4659
+ constructor(contract) {
4660
+ this.#contract = contract;
4661
+ }
4662
+ get result() {
4663
+ return this.#result;
4664
+ }
4665
+ setResult(node) {
4666
+ this.#result = node;
4667
+ }
4668
+ add(node) {
4669
+ if (!(node instanceof StatementNode)) return this.#append(node);
4670
+ const stateEdges = tablesReadBy(node.statements).map((table) => new StateEdge(this.#stateOf(table), table));
4671
+ const id = this.#append(node);
4672
+ for (const edge of stateEdges) this.#connect(id, "state", edge);
4673
+ for (const table of this.#tablesWrittenBy(node.statements)) {
4674
+ const state = this.#append(new State(table));
4675
+ this.#connect(state, "write", new StateEdge(id, table));
4676
+ this.#states.set(tableKey(table), state);
4677
+ }
4678
+ return id;
4679
+ }
4680
+ addFilterDataEdge(from, to, columns, changed = {}) {
4681
+ this.#read(from, columns);
4682
+ this.#connect(to, "filter", new FilterData(from, columns, changed));
4683
+ }
4684
+ addPayloadDataEdge(from, to, columns) {
4685
+ this.#read(from, columns);
4686
+ this.#connect(to, "payload", new PayloadData(from, columns));
4687
+ }
4688
+ addRowsEdge(from, to, slot, columns) {
4689
+ this.#read(from, columns);
4690
+ this.#connect(to, slot, new Rows(from, columns));
4691
+ }
4692
+ addRequiresEdge(from, to) {
4693
+ this.#connect(to, "requires", new Requires(from));
4694
+ }
4695
+ sameState(a, b, table) {
4696
+ const stateA = this.#stateEdgeOf(a, table);
4697
+ return stateA !== void 0 && stateA.from === this.#stateEdgeOf(b, table)?.from;
4698
+ }
4699
+ columnsReadFrom(id) {
4700
+ return this.readersOf(id).flatMap(({ edge }) => edge instanceof DataEdge ? edge.columns.map(([source]) => source) : []);
4701
+ }
4702
+ replace(id, next) {
4703
+ this.#nodes[id] = next;
4704
+ }
4705
+ remove(id) {
4706
+ for (const edge of edgesIn(this.inputsOf(id))) this.#readers[edge.from] = this.readersOf(edge.from).filter((entry) => entry.edge !== edge);
4707
+ for (const { reader, edge } of this.readersOf(id)) this.#inputs[reader] = Object.fromEntries(Object.entries(this.inputsOf(reader)).map(([name, slot]) => [name, Array.isArray(slot) ? slot.filter((other) => other !== edge) : slot]));
4708
+ this.#nodes[id] = void 0;
4709
+ this.#inputs[id] = {};
4710
+ this.#readers[id] = [];
4711
+ }
4712
+ nodes() {
4713
+ return this.#ids.flatMap((id) => {
4714
+ const node = this.#nodes[id];
4715
+ return node === void 0 ? [] : [[id, node]];
4716
+ });
4717
+ }
4718
+ inputsOf(id) {
4719
+ return this.#inputs[id] ?? {};
4720
+ }
4721
+ readersOf(id) {
4722
+ return this.#readers[id] ?? [];
4723
+ }
4724
+ #append(node) {
4725
+ const id = blindCast(this.#nodes.length);
4726
+ this.#ids.push(id);
4727
+ this.#nodes.push(node);
4728
+ this.#inputs.push(Object.fromEntries(Object.entries(node.slots).filter(([, kind]) => kind === "list").map(([name]) => [name, []])));
4729
+ this.#readers.push([]);
4730
+ return id;
4731
+ }
4732
+ #connect(to, slot, edge) {
4733
+ const current = this.inputsOf(to)[slot];
4734
+ this.#inputs[to] = {
4735
+ ...this.inputsOf(to),
4736
+ [slot]: Array.isArray(current) ? [...current, edge] : edge
4737
+ };
4738
+ this.#readers[edge.from]?.push({
4739
+ reader: to,
4740
+ edge
4741
+ });
4742
+ }
4743
+ #read(from, columns) {
4744
+ const source = this.#nodes[from];
4745
+ if (source instanceof StatementNode) this.#nodes[from] = source.withReturning(columns.map(([column]) => column));
4746
+ }
4747
+ #stateOf(table) {
4748
+ const current = this.#states.get(tableKey(table));
4749
+ if (current !== void 0) return current;
4750
+ const initial = this.#append(new State(table));
4751
+ this.#states.set(tableKey(table), initial);
4752
+ return initial;
4753
+ }
4754
+ #stateEdgeOf(id, table) {
4755
+ return edgesIn(this.inputsOf(id)).find((edge) => edge instanceof StateEdge && edge.table.namespaceId === table.namespaceId && edge.table.tableName === table.tableName);
4756
+ }
4757
+ #tablesWrittenBy(statements) {
4758
+ return uniqueTables(statements.flatMap((ast) => {
4759
+ const write = writeOf(ast);
4760
+ return write === void 0 ? [] : changedBy(this.#contract, write.kind, storageOf(write.target));
4761
+ }));
4762
+ }
4763
+ };
4764
+ function edgesIn(slots) {
4765
+ return Object.values(slots).flat();
4766
+ }
4767
+ function tablesReadBy(statements) {
4768
+ return uniqueTables(statements.flatMap((ast) => collectTableSources(ast).map(storageOf)));
4769
+ }
4770
+ function storageOf(source) {
4771
+ return {
4772
+ namespaceId: blindCast(source.namespaceId),
4773
+ tableName: source.name
4774
+ };
4775
+ }
4776
+ function uniqueTables(tables) {
4777
+ return [...new Map(tables.map((table) => [tableKey(table), table])).values()];
4778
+ }
4779
+ function writeOf(ast) {
4780
+ switch (ast.kind) {
4781
+ case "insert": return {
4782
+ kind: ast.onConflict?.action.kind === "do-update-set" ? "update" : "insert",
4783
+ target: ast.table
4784
+ };
4785
+ case "update":
4786
+ case "delete": return {
4787
+ kind: ast.kind,
4788
+ target: ast.table
4789
+ };
4790
+ case "select": return;
4791
+ }
4792
+ }
4793
+ function assertOneValuePerColumn(values, { relation, junction }) {
4794
+ const seen = /* @__PURE__ */ new Map();
4795
+ for (const [column, value] of values) {
4796
+ if (seen.has(column) && !Object.is(seen.get(column), value)) throw ormError("ORM.RELATION_MUTATION_INVALID", `Cannot write junction "${junction}": conflicting values for junction column "${column}"`, { meta: {
4797
+ relation,
4798
+ junction,
4799
+ column
4800
+ } });
4801
+ seen.set(column, value);
4802
+ }
4803
+ }
4804
+ var Insert = class Insert extends StatementNode {
4805
+ slots = {
4806
+ payload: "list",
4807
+ state: "list",
4808
+ requires: "list"
4809
+ };
4810
+ ast;
4811
+ junction;
4812
+ constructor(ast, junction) {
4813
+ super();
4814
+ this.ast = ast;
4815
+ this.junction = junction;
4816
+ Object.freeze(this);
4817
+ }
4818
+ get statements() {
4819
+ return [this.ast];
4820
+ }
4821
+ get returns() {
4822
+ return this.ast.returning ?? [];
4823
+ }
4824
+ execute(inputs, run) {
4825
+ if (requirementUnmet(inputs.requires)) return rowsResult([]);
4826
+ if (inputs.payload === null) return executeStatement$1(this.ast, run);
4827
+ if (inputs.payload.some((records) => records.length === 0)) return rowsResult([]);
4828
+ return executeStatement$1(withPayload(this.ast, payloadOf(inputs.payload, this.junction)), run);
4829
+ }
4830
+ withReturning(columns) {
4831
+ return new Insert(this.ast.withReturning(withColumns(this.returns, columns)), this.junction);
4832
+ }
4833
+ };
4834
+ /** The values the `PayloadData` edges give every row, each edge's first record. */
4835
+ function payloadOf(payload, junction) {
4836
+ const records = payload.map(([record]) => record ?? {});
4837
+ if (junction !== void 0) assertOneValuePerColumn(records.flatMap((record) => Object.entries(record).map(([column, param]) => [column, param.value])), junction);
4838
+ return Object.assign({}, ...records);
4839
+ }
4840
+ function withPayload(ast, payload) {
4841
+ return ast.withRows(ast.rows.map((row) => ({
4842
+ ...row,
4843
+ ...payload
4844
+ })));
4845
+ }
4846
+ /**
4847
+ * Inserts without `RETURNING` and reports the key of each row it inserted: the values the client wrote, those a `PayloadData` edge gives, and, for a one-row insert, the value the database generated, which the driver reports as `insertId`. When it reports none, the insert fails, so the transaction it runs in rolls back.
4848
+ */
4849
+ var InsertReportingKeys = class extends StatementNode {
4850
+ slots = {
4851
+ payload: "list",
4852
+ state: "list",
4853
+ requires: "list"
4854
+ };
4855
+ asts;
4856
+ keys;
4857
+ generated;
4858
+ owner;
4859
+ constructor(asts, keys, generated, owner) {
4860
+ super();
4861
+ this.asts = Object.freeze([...asts]);
4862
+ this.keys = Object.freeze([...keys]);
4863
+ this.generated = generated;
4864
+ this.owner = owner;
4865
+ Object.freeze(this);
4866
+ }
4867
+ get statements() {
4868
+ return this.asts;
4869
+ }
4870
+ get returns() {
4871
+ return [];
4872
+ }
4873
+ execute(inputs, run) {
4874
+ const payloads = inputs.payload ?? [];
4875
+ if (requirementUnmet(inputs.requires) || payloads.some((records) => records.length === 0)) return rowsResult([]);
4876
+ const record = Object.assign({}, ...payloads.map(([row]) => row));
4877
+ const asts = this.asts.map((ast) => ast.withRows(ast.rows.map((row) => ({
4878
+ ...row,
4879
+ ...record
4880
+ }))));
4881
+ const keys = this.keys.map((key) => Object.fromEntries(Object.entries(key).map(([column, value]) => [column, record[column]?.value ?? value])));
4882
+ const { generated, owner } = this;
4883
+ const generator = async function* () {
4884
+ for (const ast of asts) {
4885
+ const stats = await run.execute(ast);
4886
+ if (generated !== void 0) {
4887
+ const insertId = reportedInsertId(stats, generated, owner);
4888
+ yield {
4889
+ ...keys[0],
4890
+ [generated.column]: await generated.decode(insertId)
4891
+ };
4892
+ return;
4893
+ }
4894
+ }
4895
+ yield* keys;
4896
+ };
4897
+ return new AsyncIterableResult(generator());
4898
+ }
4899
+ withReturning(_columns) {
4900
+ return this;
5123
4901
  }
5124
4902
  };
5125
- var Find = class Find extends StatementNode {
4903
+ var Delete = class Delete extends StatementNode {
4904
+ slots = filteredSlots;
5126
4905
  ast;
5127
4906
  constructor(ast) {
5128
4907
  super();
5129
4908
  this.ast = ast;
5130
4909
  Object.freeze(this);
5131
4910
  }
4911
+ get statements() {
4912
+ return [this.ast];
4913
+ }
5132
4914
  get returns() {
5133
- return this.ast.projection;
4915
+ return this.ast.returning ?? [];
5134
4916
  }
5135
4917
  execute(inputs, run) {
5136
- return executeFiltered(this.ast, inputs.filter, run);
4918
+ return executeFiltered(this.ast, inputs, run);
5137
4919
  }
5138
4920
  withReturning(columns) {
5139
- return new Find(this.ast.withProjection(withColumns(this.returns, columns)));
4921
+ return new Delete(this.ast.withReturning(withColumns(this.returns, columns)));
5140
4922
  }
5141
4923
  };
5142
- /** Keys per read-back statement. The `ORDER BY CASE` costs the database the number of keys times the number of rows it returns, so the keys are read in chunks of this size. */
5143
- const KEYS_PER_STATEMENT = 500;
5144
- /**
5145
- * Reads the rows an insert wrote back by their keys, for a database without `RETURNING`, in the order the insert wrote them, and fails when it finds fewer rows than keys, so the transaction rolls back. It reads at most 500 keys per statement.
5146
- *
5147
- * A `Find` with a `FilterData` edge cannot do this: the edge hands the `Find` conditions, not the key values, so the `Find` cannot order the rows by key or count the keys. The database does both comparisons, with its own rules for collation and precision: each key's condition both selects its row and, in an `ORDER BY CASE`, places it.
5148
- */
5149
- var FindByKeys = class FindByKeys extends StatementNode {
5150
- ast;
5151
- keyColumns;
5152
- owner;
5153
- constructor(ast, keyColumns, owner) {
4924
+ var InsertChunked = class InsertChunked extends StatementNode {
4925
+ slots = {
4926
+ payload: "list",
4927
+ state: "list",
4928
+ requires: "list"
4929
+ };
4930
+ asts;
4931
+ junction;
4932
+ constructor(asts, junction) {
5154
4933
  super();
5155
- this.ast = ast;
5156
- this.keyColumns = Object.freeze([...keyColumns]);
5157
- this.owner = owner;
4934
+ this.asts = Object.freeze([...asts]);
4935
+ this.junction = junction;
5158
4936
  Object.freeze(this);
5159
4937
  }
4938
+ get statements() {
4939
+ return this.asts;
4940
+ }
5160
4941
  get returns() {
5161
- return this.ast.projection;
4942
+ return this.asts[0]?.returning ?? [];
5162
4943
  }
5163
4944
  execute(inputs, run) {
5164
- const keys = inputs.keys;
5165
- if (keys.length === 0) return rowsResult([]);
5166
- const chunks = Array.from({ length: Math.ceil(keys.length / KEYS_PER_STATEMENT) }, (_, index) => keys.slice(index * KEYS_PER_STATEMENT, (index + 1) * KEYS_PER_STATEMENT));
5167
- const { owner } = this;
5168
- const statementFor = (chunk) => this.#statementFor(chunk);
4945
+ if (requirementUnmet(inputs.requires)) return rowsResult([]);
4946
+ if (inputs.payload?.some((records) => records.length === 0)) return rowsResult([]);
4947
+ const payload = inputs.payload === null ? void 0 : payloadOf(inputs.payload, this.junction);
4948
+ const asts = payload === void 0 ? this.asts : this.asts.map((ast) => withPayload(ast, payload));
4949
+ if (this.returns.length === 0) return this.#sumOfCounts(asts, run);
5169
4950
  const generator = async function* () {
5170
- for (const chunk of chunks) {
5171
- const rows = await run.query(statementFor(chunk)).toArray();
5172
- if (rows.length < chunk.length) throw ormError("ORM.MUTATION_ROW_MISSING", `${owner.operation}() for model "${owner.modelName}" did not find the row it wrote`, { meta: {
5173
- operation: owner.operation,
5174
- model: owner.modelName,
5175
- phase: "read-back"
5176
- } });
5177
- yield* rows;
5178
- }
4951
+ for (const ast of asts) yield* run.query(ast);
5179
4952
  };
5180
4953
  return new AsyncIterableResult(generator());
5181
4954
  }
5182
- #statementFor(keys) {
5183
- const conditions = keys.map((key) => keyCondition(this.keyColumns, key));
5184
- const existing = this.ast.where === void 0 ? [] : [this.ast.where];
5185
- const found = this.ast.withWhere(combineWhereExprs([...existing, anyOf(conditions)]));
5186
- return conditions.length === 1 ? found : found.withOrderBy([OrderByItem.asc(CaseExpr.of(conditions.map((condition, position) => ({
5187
- condition,
5188
- value: LiteralExpr.of(position)
5189
- }))))]);
5190
- }
5191
4955
  withReturning(columns) {
5192
- return new FindByKeys(this.ast.withProjection(withColumns(this.returns, columns)), this.keyColumns, this.owner);
5193
- }
5194
- };
5195
- var Graph = class {
5196
- #ids = [];
5197
- #nodes = [];
5198
- #inputs = [];
5199
- #readers = [];
5200
- #result = void 0;
5201
- get result() {
5202
- return this.#result;
5203
- }
5204
- setResult(node) {
5205
- this.#result = node;
5206
- }
5207
- add(node, inputs) {
5208
- const id = blindCast(this.#nodes.length);
5209
- this.#ids.push(id);
5210
- this.#nodes.push(node);
5211
- this.#inputs.push(inputs);
5212
- this.#readers.push([]);
5213
- for (const edge of Object.values(inputs).flat()) {
5214
- this.#readers[edge.from]?.push({
5215
- reader: id,
5216
- edge
5217
- });
5218
- const source = this.#nodes[edge.from];
5219
- if (source instanceof StatementNode) this.#nodes[edge.from] = source.withReturning(edge.columns.map(([column]) => column));
5220
- }
5221
- return id;
5222
- }
5223
- replace(id, next) {
5224
- this.#nodes[id] = next;
5225
- }
5226
- remove(id) {
5227
- for (const edge of Object.values(this.inputsOf(id)).flat()) this.#readers[edge.from] = this.readersOf(edge.from).filter((entry) => entry.edge !== edge);
5228
- for (const { reader, edge } of this.readersOf(id)) this.#inputs[reader] = Object.fromEntries(Object.entries(this.inputsOf(reader)).map(([name, slot]) => [name, Array.isArray(slot) ? slot.filter((other) => other !== edge) : slot]));
5229
- this.#nodes[id] = void 0;
5230
- this.#inputs[id] = {};
5231
- this.#readers[id] = [];
5232
- }
5233
- nodes() {
5234
- return this.#ids.flatMap((id) => {
5235
- const node = this.#nodes[id];
5236
- return node === void 0 ? [] : [[id, node]];
5237
- });
5238
- }
5239
- inputsOf(id) {
5240
- return this.#inputs[id] ?? {};
4956
+ return new InsertChunked(this.asts.map((ast) => ast.withReturning(withColumns(ast.returning ?? [], columns))), this.junction);
5241
4957
  }
5242
- readersOf(id) {
5243
- return this.#readers[id] ?? [];
4958
+ async #sumOfCounts(asts, run) {
4959
+ let affectedRows = 0;
4960
+ for (const ast of asts) affectedRows += (await run.execute(ast)).affectedRows;
4961
+ return { affectedRows };
5244
4962
  }
5245
4963
  };
5246
- var Insert = class Insert extends StatementNode {
4964
+ var Update = class Update extends StatementNode {
4965
+ slots = {
4966
+ filter: "list",
4967
+ payload: "list",
4968
+ state: "list",
4969
+ requires: "list"
4970
+ };
5247
4971
  ast;
5248
4972
  constructor(ast) {
5249
4973
  super();
5250
4974
  this.ast = ast;
5251
4975
  Object.freeze(this);
5252
4976
  }
4977
+ get statements() {
4978
+ return [this.ast];
4979
+ }
5253
4980
  get returns() {
5254
4981
  return this.ast.returning ?? [];
5255
4982
  }
5256
4983
  execute(inputs, run) {
5257
- if (inputs.payload === null) return executeStatement$1(this.ast, run);
5258
- if (inputs.payload.some((records) => records.length === 0)) return rowsResult([]);
4984
+ if (inputs.payload === null) return executeFiltered(this.ast, inputs, run);
4985
+ if (requirementUnmet(inputs.requires) || inputs.payload.some((records) => records.length === 0)) return rowsResult([]);
5259
4986
  const payload = Object.assign({}, ...inputs.payload.map(([record]) => record));
5260
- const rows = this.ast.rows.map((row) => ({
5261
- ...row,
4987
+ return executeFiltered(this.ast.withSet({
4988
+ ...this.ast.set,
5262
4989
  ...payload
5263
- }));
5264
- return executeStatement$1(this.ast.withRows(rows), run);
4990
+ }), inputs, run);
5265
4991
  }
5266
4992
  withReturning(columns) {
5267
- return new Insert(this.ast.withReturning(withColumns(this.returns, columns)));
4993
+ return new Update(this.ast.withReturning(withColumns(this.returns, columns)));
5268
4994
  }
5269
4995
  };
5270
- var InsertChunked = class InsertChunked extends StatementNode {
5271
- asts;
5272
- constructor(asts) {
4996
+ function addInsertRows(graph, contract, table, rows, { conflict, keys, junction }) {
4997
+ const inserted = supportsDefaultInInsert(contract) ? graph.add(new Insert(insertAst(contract, table, rows, conflict), junction)) : graph.add(new InsertChunked(groupRowsByColumnSignature(rows).map((group) => insertAst(contract, table, group, conflict)), junction));
4998
+ for (const { from, columns } of keys) graph.addPayloadDataEdge(from, inserted, columns);
4999
+ return inserted;
5000
+ }
5001
+ function selectAstOf(context, model, state, columns) {
5002
+ const { contract } = context;
5003
+ const { modelName, tables } = model;
5004
+ if (columns === "identity") {
5005
+ const { namespaceId, tableName } = tables.root.storage;
5006
+ return collectionSelectAst(contract, modelName, {
5007
+ ...state,
5008
+ includes: [],
5009
+ selectedFields: resolveRowIdentityColumns(contract, namespaceId, tableName)
5010
+ });
5011
+ }
5012
+ if (state.includes.length === 0) return collectionSelectAst(contract, modelName, state);
5013
+ return collectionSelectWithIncludesAst(contract, context.aggregateDescriptors, modelName, state);
5014
+ }
5015
+ function addUpdateRows(graph, contract, tables, values, { where, filters, payloads }) {
5016
+ const updated = graph.add(new Update(updateAst(contract, tables, values, where)));
5017
+ for (const { from, columns } of filters) graph.addFilterDataEdge(from, updated, columns);
5018
+ for (const { from, columns } of payloads) graph.addPayloadDataEdge(from, updated, columns);
5019
+ return updated;
5020
+ }
5021
+ function addDeleteRows(graph, contract, tables, { where, filters }) {
5022
+ const deleted = graph.add(new Delete(deleteAst(contract, tables, where)));
5023
+ for (const { from, columns } of filters) graph.addFilterDataEdge(from, deleted, columns);
5024
+ return deleted;
5025
+ }
5026
+ function createRelationMutator() {
5027
+ return {
5028
+ create(data) {
5029
+ return {
5030
+ kind: "create",
5031
+ data: Array.isArray(data) ? [...data] : [data]
5032
+ };
5033
+ },
5034
+ connect(criteria) {
5035
+ return {
5036
+ kind: "connect",
5037
+ criteria: Array.isArray(criteria) ? [...criteria] : [criteria]
5038
+ };
5039
+ },
5040
+ disconnect(criteria) {
5041
+ if (!criteria) return { kind: "disconnect" };
5042
+ return {
5043
+ kind: "disconnect",
5044
+ criteria: [...criteria]
5045
+ };
5046
+ }
5047
+ };
5048
+ }
5049
+ function isRelationMutationDescriptor(value) {
5050
+ if (!value || typeof value !== "object") return false;
5051
+ const candidate = value;
5052
+ if (candidate.kind !== "create" && candidate.kind !== "connect" && candidate.kind !== "disconnect") return false;
5053
+ return true;
5054
+ }
5055
+ function isRelationMutationCallback(value) {
5056
+ return typeof value === "function";
5057
+ }
5058
+ function hasThrough(relation) {
5059
+ return relation.through !== void 0;
5060
+ }
5061
+ function parseMutationInput(contract, namespaceId, modelName, input) {
5062
+ const scalarData = {};
5063
+ const relations = resolveModelRelations(contract, namespaceId, modelName);
5064
+ const relationMutations = [];
5065
+ for (const [fieldName, value] of Object.entries(input)) {
5066
+ const relation = Object.hasOwn(relations, fieldName) ? relations[fieldName] : void 0;
5067
+ if (relation === void 0) {
5068
+ scalarData[fieldName] = value;
5069
+ continue;
5070
+ }
5071
+ if (value === void 0) continue;
5072
+ if (!isRelationMutationCallback(value)) throw ormError("ORM.RELATION_MUTATION_INVALID", `Relation field "${fieldName}" on model "${modelName}" expects a mutator callback`, { meta: {
5073
+ relation: fieldName,
5074
+ model: modelName,
5075
+ problem: "missing-callback"
5076
+ } });
5077
+ const mutation = value(createRelationMutator());
5078
+ if (!isRelationMutationDescriptor(mutation)) throw ormError("ORM.RELATION_MUTATION_INVALID", `Relation field "${fieldName}" on model "${modelName}" returned an invalid mutation descriptor`, { meta: {
5079
+ relation: fieldName,
5080
+ model: modelName,
5081
+ problem: "invalid-descriptor"
5082
+ } });
5083
+ relationMutations.push({
5084
+ name: fieldName,
5085
+ relation,
5086
+ mutation
5087
+ });
5088
+ }
5089
+ return {
5090
+ scalarData,
5091
+ relationMutations
5092
+ };
5093
+ }
5094
+ function partitionByOwnership(relationMutations) {
5095
+ const parentOwned = [];
5096
+ const childOwned = [];
5097
+ const junctionOwned = [];
5098
+ for (const relationMutation of relationMutations) {
5099
+ if (hasThrough(relationMutation.relation)) {
5100
+ junctionOwned.push({
5101
+ ...relationMutation,
5102
+ relation: relationMutation.relation
5103
+ });
5104
+ continue;
5105
+ }
5106
+ if (relationMutation.relation.cardinality === "N:1") {
5107
+ parentOwned.push(relationMutation);
5108
+ continue;
5109
+ }
5110
+ childOwned.push(relationMutation);
5111
+ }
5112
+ return {
5113
+ parentOwned,
5114
+ childOwned,
5115
+ junctionOwned
5116
+ };
5117
+ }
5118
+ function assertJunctionPayloadWritable({ name, relation, mutation }) {
5119
+ const { through } = relation;
5120
+ if (mutation.kind !== "create" && mutation.kind !== "connect" || through.requiredPayloadColumns.length === 0) return;
5121
+ const cols = through.requiredPayloadColumns.map((c) => `\`${c}\``).join(", ");
5122
+ throw ormError("ORM.RELATION_MUTATION_UNSUPPORTED", `Cannot \`${mutation.kind}\` on relation \`${name}\`: its junction \`${through.table}\` has required column(s) ${cols} the relation API can't populate. Write the \`${through.table}\` junction directly or use the SQL builder.`, { meta: {
5123
+ kind: mutation.kind,
5124
+ relation: name,
5125
+ reason: "junction-required-columns",
5126
+ junction: through.table
5127
+ } });
5128
+ }
5129
+ function assertJunctionMetadataLength(name, throughColumnName, throughColumns, pairedColumnName, pairedColumns) {
5130
+ if (throughColumns.length === pairedColumns.length) return;
5131
+ throw new InternalError(`Relation "${name}" has invalid junction metadata: ${throughColumnName} has ${throughColumns.length} column(s), but ${pairedColumnName} has ${pairedColumns.length}`);
5132
+ }
5133
+ function assertJunctionMetadataShape({ name, relation }) {
5134
+ assertJunctionMetadataLength(name, "parentColumns", relation.through.parentColumns, "localColumns", relation.on.localFields);
5135
+ assertJunctionMetadataLength(name, "childColumns", relation.through.childColumns, "targetColumns", relation.through.targetColumns);
5136
+ }
5137
+ var Assert = class extends Node {
5138
+ slots = {
5139
+ rows: "one",
5140
+ requires: "list"
5141
+ };
5142
+ error;
5143
+ constructor(error) {
5273
5144
  super();
5274
- this.asts = Object.freeze([...asts]);
5145
+ this.error = error;
5275
5146
  Object.freeze(this);
5276
5147
  }
5277
- get returns() {
5278
- return this.asts[0]?.returning ?? [];
5148
+ execute(inputs, _run) {
5149
+ if (requirementUnmet(inputs.requires)) return rowsResult([]);
5150
+ if (inputs.rows.length === 0) throw this.error;
5151
+ return rowsResult([]);
5152
+ }
5153
+ };
5154
+ const nothingBefore = {
5155
+ keys: [],
5156
+ nullColumns: {}
5157
+ };
5158
+ function modelOf(collection) {
5159
+ const { modelName, namespaceId, state } = collection;
5160
+ return {
5161
+ namespaceId,
5162
+ modelName,
5163
+ tables: state.tables
5164
+ };
5165
+ }
5166
+ function createRowsOf(collection, rows) {
5167
+ const model = modelOf(collection);
5168
+ const defaultValueCache = /* @__PURE__ */ new Map();
5169
+ return rows.map((row) => createRowOf(collection.context, model, collection.state.variantValue, row, defaultValueCache));
5170
+ }
5171
+ function createRowOf(context, model, variantValue, row, defaultValueCache) {
5172
+ const { namespaceId, tableName } = model.tables.root.storage;
5173
+ return withCreateDefaults(context, namespaceId, tableName, mappedCreateRow(context.contract, model, variantValue, row), defaultValueCache);
5174
+ }
5175
+ function withCreateDefaults(context, namespaceId, tableName, values, defaultValueCache) {
5176
+ const withDefaults = { ...values };
5177
+ for (const applied of context.applyMutationDefaults({
5178
+ op: "create",
5179
+ entry: tableName,
5180
+ namespace: namespaceId,
5181
+ values,
5182
+ ...ifDefined("defaultValueCache", defaultValueCache)
5183
+ })) withDefaults[applied.field] = applied.value;
5184
+ return withDefaults;
5185
+ }
5186
+ function mappedCreateRow(contract, model, variantValue, row) {
5187
+ const { namespaceId, modelName } = model;
5188
+ const polyInfo = variantValue === void 0 ? void 0 : resolvePolymorphismInfo(contract, namespaceId, modelName);
5189
+ const variant = variantValue === void 0 ? void 0 : polyInfo?.variants.get(variantValue);
5190
+ if (polyInfo === void 0 || variant === void 0) return mapModelDataToStorageRow(contract, namespaceId, modelName, row);
5191
+ const mergedFieldToColumn = getModelAndVariantFieldColumns(contract, namespaceId, modelName, variant.value);
5192
+ const mapped = {};
5193
+ for (const [fieldName, value] of Object.entries(row)) {
5194
+ if (value === void 0) continue;
5195
+ mapped[columnOfCallerField(contract, variant.namespaceId, mergedFieldToColumn, variant.modelName, fieldName)] = value;
5196
+ }
5197
+ mapped[polyInfo.discriminatorColumn] = variant.value;
5198
+ return mapped;
5199
+ }
5200
+ function mtiCreateContextOf(collection) {
5201
+ const { context, modelName, namespaceId, state } = collection;
5202
+ const { contract } = context;
5203
+ const { variantValue } = state;
5204
+ if (!variantValue) return void 0;
5205
+ const polyInfo = resolvePolymorphismInfo(contract, namespaceId, modelName);
5206
+ if (!polyInfo) return void 0;
5207
+ const variant = polyInfo.variants.get(variantValue);
5208
+ if (!isMtiVariantInfo(variant)) return void 0;
5209
+ return {
5210
+ polyInfo,
5211
+ variant,
5212
+ baseFieldToColumn: getModelFieldColumns(contract, namespaceId, modelName),
5213
+ variantFieldToColumn: getOwnFieldColumns(contract, variant.namespaceId, variant.modelName),
5214
+ mergedFieldToColumn: getModelAndVariantFieldColumns(contract, namespaceId, modelName, variant.value)
5215
+ };
5216
+ }
5217
+ function isMtiVariantInfo(variant) {
5218
+ return variant?.strategy === "mti";
5219
+ }
5220
+ function variantCreateRowsOf(collection, mti, variantTable, rows) {
5221
+ const { context, namespaceId, state } = collection;
5222
+ const { contract } = context;
5223
+ const { polyInfo, variant, baseFieldToColumn, variantFieldToColumn, mergedFieldToColumn } = mti;
5224
+ const baseFieldColumns = new Set(Object.values(baseFieldToColumn));
5225
+ const variantFieldColumns = new Set(Object.values(variantFieldToColumn));
5226
+ const defaultValueCache = /* @__PURE__ */ new Map();
5227
+ const base = state.tables.root.storage;
5228
+ return rows.map((row) => {
5229
+ const allMapped = {};
5230
+ for (const [fieldName, value] of Object.entries(row)) {
5231
+ if (value === void 0) continue;
5232
+ allMapped[columnOfCallerField(contract, namespaceId, mergedFieldToColumn, variant.modelName, fieldName)] = value;
5233
+ }
5234
+ allMapped[polyInfo.discriminatorColumn] = variant.value;
5235
+ const baseRow = {};
5236
+ const variantRow = {};
5237
+ for (const [column, value] of Object.entries(allMapped)) {
5238
+ if (baseFieldColumns.has(column) || column === polyInfo.discriminatorColumn) baseRow[column] = value;
5239
+ if (variantFieldColumns.has(column)) variantRow[column] = value;
5240
+ }
5241
+ return {
5242
+ base: withCreateDefaults(context, base.namespaceId, base.tableName, baseRow, defaultValueCache),
5243
+ variant: withCreateDefaults(context, variantTable.storage.namespaceId, variantTable.storage.tableName, variantRow, defaultValueCache)
5244
+ };
5245
+ });
5246
+ }
5247
+ function updateValuesOf(collection, data) {
5248
+ return withUpdateDefaults(collection, mappedUpdateRow(collection, data), nothingBefore);
5249
+ }
5250
+ function mappedUpdateRow(collection, data) {
5251
+ const { context, modelName, namespaceId } = collection;
5252
+ return mapModelDataToStorageRow(context.contract, namespaceId, modelName, data);
5253
+ }
5254
+ function withUpdateDefaults(collection, set, before) {
5255
+ const values = {
5256
+ ...set,
5257
+ ...before.nullColumns
5258
+ };
5259
+ const keyColumns = before.keys.flatMap(({ columns }) => columns.map(([, target]) => target.alias));
5260
+ const written = {
5261
+ ...Object.fromEntries(keyColumns.map((column) => [column, true])),
5262
+ ...values
5263
+ };
5264
+ if (Object.keys(written).length === 0) return values;
5265
+ const { namespaceId, tableName } = collection.state.tables.root.storage;
5266
+ for (const applied of collection.context.applyMutationDefaults({
5267
+ op: "update",
5268
+ entry: tableName,
5269
+ namespace: namespaceId,
5270
+ values: written
5271
+ })) values[applied.field] = applied.value;
5272
+ return values;
5273
+ }
5274
+ function addCreateWithRelations(t, model, parsed, keysFromParent, requiresParentRow = false) {
5275
+ for (const relationMutation of parsed.relationMutations) rejectDisconnect(relationMutation);
5276
+ const before = addBeforeWrite(t, model, parsed.relationMutations);
5277
+ const keys = [...keysFromParent, ...before.keys];
5278
+ const row = createRowOf(t.context, model, void 0, parsed.scalarData, void 0);
5279
+ const parent = t.readsBack ? addInsertAndReadBack(t, model, row, keys, requiresParentRow) : addParentInsert(t, model, row, keys, requiresParentRow);
5280
+ addAfterWrite(t, model, parent, parsed.relationMutations);
5281
+ return parent;
5282
+ }
5283
+ function addParentInsert(t, model, row, keys, requiresParentRow) {
5284
+ const insert = addInsertRows(t.graph, t.context.contract, model.tables.root, [row], {
5285
+ conflict: void 0,
5286
+ keys,
5287
+ junction: void 0
5288
+ });
5289
+ if (requiresParentRow) requireParentRow(t, insert);
5290
+ return insert;
5291
+ }
5292
+ function addInsertAndReadBack(t, model, row, keys, requiresParentRow) {
5293
+ const { graph, context } = t;
5294
+ const { contract } = context;
5295
+ const { root } = model.tables;
5296
+ const { namespaceId, tableName } = root.storage;
5297
+ const owner = {
5298
+ operation: "create",
5299
+ modelName: model.modelName
5300
+ };
5301
+ const written = writtenKeysOf(t, model, row, keys);
5302
+ const insert = graph.add(new InsertReportingKeys([insertAst(contract, root, [row], void 0)], written.keys, written.generated, owner));
5303
+ for (const { from, columns } of keys) graph.addPayloadDataEdge(from, insert, columns);
5304
+ if (requiresParentRow) requireParentRow(t, insert);
5305
+ const identityMappings = projectTableColumns(contract, root, readBackIdentity(contract, namespaceId, tableName, model.modelName, "create()")).map((column) => [column, column]);
5306
+ const read = graph.add(new FindByKeys(collectionSelectAst(contract, model.modelName, emptyState(model.tables)), identityMappings, owner));
5307
+ graph.addRowsEdge(insert, read, "keys", identityMappings);
5308
+ return read;
5309
+ }
5310
+ function writtenKeysOf(t, model, row, keys) {
5311
+ const { namespaceId, tableName } = model.tables.root.storage;
5312
+ const fromEdges = keys.flatMap(({ columns }) => columns.map(([, target]) => target.alias));
5313
+ return writtenKeys({
5314
+ context: t.context,
5315
+ namespaceId,
5316
+ tableName,
5317
+ modelName: model.modelName,
5318
+ rows: [{
5319
+ ...Object.fromEntries(fromEdges.map((column) => [column, true])),
5320
+ ...row
5321
+ }],
5322
+ method: "create()"
5323
+ });
5324
+ }
5325
+ function addBeforeWrite(t, model, relationMutations) {
5326
+ const { parentOwned, junctionOwned } = partitionByOwnership(relationMutations);
5327
+ for (const relationMutation of junctionOwned) {
5328
+ assertJunctionMetadataShape(relationMutation);
5329
+ assertJunctionPayloadWritable(relationMutation);
5330
+ }
5331
+ const keys = [];
5332
+ const nullColumns = {};
5333
+ for (const relationMutation of parentOwned) {
5334
+ const { relation, mutation } = relationMutation;
5335
+ if (mutation.kind === "disconnect") for (const column of localColumnsOf(t.context.contract, model, relation)) nullColumns[column] = null;
5336
+ else keys.push(addParentOwned(t, model, relationMutation, mutation));
5279
5337
  }
5280
- execute(_inputs, run) {
5281
- if (this.returns.length === 0) return this.#sumOfCounts(run);
5282
- const asts = this.asts;
5283
- const generator = async function* () {
5284
- for (const ast of asts) yield* run.query(ast);
5338
+ return {
5339
+ keys,
5340
+ nullColumns
5341
+ };
5342
+ }
5343
+ function addAfterWrite(t, model, parent, relationMutations) {
5344
+ const { childOwned, junctionOwned } = partitionByOwnership(relationMutations);
5345
+ for (const relationMutation of childOwned) addChildOwned(t, model, parent, relationMutation);
5346
+ for (const relationMutation of junctionOwned) addJunctionOwned(t, model, parent, relationMutation);
5347
+ }
5348
+ function rejectDisconnect({ name, mutation }) {
5349
+ if (mutation.kind === "disconnect") throw ormError("ORM.RELATION_MUTATION_UNSUPPORTED", "disconnect() is only supported in update() nested mutations", { meta: {
5350
+ kind: "disconnect",
5351
+ relation: name
5352
+ } });
5353
+ }
5354
+ function addParentOwned(t, model, { name, relation }, mutation) {
5355
+ const { contract } = t.context;
5356
+ const related = relatedModel(contract, relation);
5357
+ const columns = columnMappings(contract, related.tables.root, resolveRelationTargetColumns(contract, relation), model.tables.root, localColumnsOf(contract, model, relation));
5358
+ if (mutation.kind === "create") {
5359
+ const [row] = mutation.data;
5360
+ if (row === void 0) throw ormError("ORM.RELATION_MUTATION_INVALID", `create() nested mutation for relation "${name}" requires data`, { meta: {
5361
+ kind: "create",
5362
+ relation: name,
5363
+ problem: "missing-data"
5364
+ } });
5365
+ return {
5366
+ from: addCreateWithRelations(t, related, parseCreateInput(t, related, row), [], true),
5367
+ columns
5285
5368
  };
5286
- return new AsyncIterableResult(generator());
5287
5369
  }
5288
- withReturning(columns) {
5289
- return new InsertChunked(this.asts.map((ast) => ast.withReturning(withColumns(ast.returning ?? [], columns))));
5290
- }
5291
- async #sumOfCounts(run) {
5292
- let affectedRows = 0;
5293
- for (const ast of this.asts) affectedRows += (await run.execute(ast)).affectedRows;
5294
- return { affectedRows };
5370
+ const [criterion] = mutation.criteria;
5371
+ if (criterion === void 0) throw ormError("ORM.RELATION_MUTATION_INVALID", `connect() nested mutation for relation "${name}" requires criterion`, { meta: {
5372
+ kind: "connect",
5373
+ relation: name,
5374
+ problem: "missing-criterion"
5375
+ } });
5376
+ return {
5377
+ from: addFindAndAssert(t, related, name, "connect", criterion, columns),
5378
+ columns
5379
+ };
5380
+ }
5381
+ function addChildOwned(t, model, parent, { name, relation, mutation }) {
5382
+ const { graph, context } = t;
5383
+ const { contract } = context;
5384
+ const related = relatedModel(contract, relation);
5385
+ const targetColumns = resolveRelationTargetColumns(contract, relation);
5386
+ const fromParent = columnMappings(contract, model.tables.root, localColumnsOf(contract, model, relation), related.tables.root, targetColumns);
5387
+ if (mutation.kind === "create") {
5388
+ const keys = [{
5389
+ from: parent,
5390
+ columns: fromParent
5391
+ }];
5392
+ const rows = mutation.data.map((row) => parseCreateInput(t, related, row));
5393
+ if (rows.some((row) => row.relationMutations.length > 0)) {
5394
+ for (const row of rows) addCreateWithRelations(t, related, row, keys);
5395
+ return;
5396
+ }
5397
+ addChildInserts(t, related, rows.map((row) => row.scalarData), keys);
5398
+ return;
5295
5399
  }
5296
- };
5297
- /**
5298
- * Inserts without `RETURNING` and reports the key of each row it inserted: the values the client wrote, and, for a one-row insert, the value the database generated, which the driver reports as `insertId`. When it reports none, the insert fails, so the transaction it runs in rolls back.
5299
- */
5300
- var InsertReportingKeys = class extends Node {
5301
- asts;
5302
- keys;
5303
- generated;
5304
- owner;
5305
- constructor(asts, keys, generated, owner) {
5306
- super();
5307
- this.asts = Object.freeze([...asts]);
5308
- this.keys = Object.freeze([...keys]);
5309
- this.generated = generated;
5310
- this.owner = owner;
5311
- Object.freeze(this);
5400
+ if (mutation.kind === "connect") {
5401
+ for (const criterion of mutation.criteria) addUpdateRows(graph, context.contract, related.tables, {}, {
5402
+ where: requiredCriterion(context, related, name, "connect", criterion),
5403
+ filters: [],
5404
+ payloads: [{
5405
+ from: parent,
5406
+ columns: fromParent
5407
+ }]
5408
+ });
5409
+ return;
5312
5410
  }
5313
- execute(_inputs, run) {
5314
- const { asts, keys, generated, owner } = this;
5315
- const generator = async function* () {
5316
- for (const ast of asts) {
5317
- const stats = await run.execute(ast);
5318
- if (generated !== void 0) {
5319
- const insertId = reportedInsertId(stats, generated, owner);
5320
- yield {
5321
- ...keys[0],
5322
- [generated.column]: await generated.decode(insertId)
5323
- };
5324
- return;
5325
- }
5411
+ const unlink = Object.fromEntries(targetColumns.map((column) => [column, null]));
5412
+ const criteria = mutation.criteria ?? [];
5413
+ const wheres = criteria.length === 0 ? [void 0] : criteria.map((criterion) => requiredCriterion(context, related, name, "disconnect", criterion));
5414
+ for (const where of wheres) addUpdateRows(graph, context.contract, related.tables, unlink, {
5415
+ where,
5416
+ filters: [{
5417
+ from: parent,
5418
+ columns: fromParent
5419
+ }],
5420
+ payloads: []
5421
+ });
5422
+ }
5423
+ function addJunctionOwned(t, model, parent, { name, relation, mutation }) {
5424
+ const { graph, context } = t;
5425
+ const { contract } = context;
5426
+ const { through } = relation;
5427
+ const related = relatedModel(contract, relation);
5428
+ const junction = createStatementTables({
5429
+ namespaceId: through.namespaceId,
5430
+ tableName: through.table
5431
+ });
5432
+ const fromParent = columnMappings(contract, model.tables.root, localColumnsOf(contract, model, relation), junction.root, through.parentColumns);
5433
+ const fromTarget = columnMappings(contract, related.tables.root, through.targetColumns, junction.root, through.childColumns);
5434
+ const addLink = (target, conflict) => {
5435
+ const values = withCreateDefaults(context, through.namespaceId, through.table, {}, void 0);
5436
+ addInsertRows(graph, contract, junction.root, [values], {
5437
+ conflict,
5438
+ keys: [{
5439
+ from: parent,
5440
+ columns: fromParent
5441
+ }, {
5442
+ from: target,
5443
+ columns: fromTarget
5444
+ }],
5445
+ junction: {
5446
+ relation: name,
5447
+ junction: through.table
5326
5448
  }
5327
- yield* keys;
5328
- };
5329
- return new AsyncIterableResult(generator());
5330
- }
5331
- };
5332
- var PayloadData = class extends Edge {
5333
- constructor(from, columns) {
5334
- super(from, columns);
5335
- Object.freeze(this);
5336
- }
5337
- output(sourceRow) {
5338
- return Object.fromEntries(this.columns.map(([source, target]) => [target.alias, ParamRef.of(sourceRow[source.alias], {
5339
- name: target.alias,
5340
- ...ifDefined("codec", target.codec)
5341
- })]));
5449
+ });
5450
+ };
5451
+ if (mutation.kind === "create") {
5452
+ for (const row of mutation.data) addLink(addCreateWithRelations(t, related, parseCreateInput(t, related, row), [], true), void 0);
5453
+ return;
5342
5454
  }
5343
- };
5344
- var Rows = class extends Edge {
5345
- constructor(from, columns) {
5346
- super(from, columns);
5347
- Object.freeze(this);
5455
+ if (mutation.kind === "connect") {
5456
+ const conflict = linkKeyConflict(contract, relation);
5457
+ for (const criterion of mutation.criteria) addLink(addFindAndAssert(t, related, name, "connect", criterion, fromTarget), conflict);
5458
+ return;
5348
5459
  }
5349
- output(sourceRow) {
5350
- return Object.fromEntries(this.columns.map(([source]) => [source.alias, sourceRow[source.alias]]));
5460
+ const criteria = mutation.criteria ?? [];
5461
+ if (criteria.length === 0) throw ormError("ORM.RELATION_MUTATION_INVALID", `disconnect() nested mutation for relation "${name}" requires criterion`, { meta: {
5462
+ kind: "disconnect",
5463
+ relation: name,
5464
+ problem: "missing-criterion"
5465
+ } });
5466
+ for (const criterion of criteria) {
5467
+ const target = addFindAndAssert(t, related, name, "disconnect", criterion, fromTarget);
5468
+ addDeleteRows(graph, contract, junction, {
5469
+ where: void 0,
5470
+ filters: [{
5471
+ from: parent,
5472
+ columns: fromParent
5473
+ }, {
5474
+ from: target,
5475
+ columns: fromTarget
5476
+ }]
5477
+ });
5351
5478
  }
5352
- };
5479
+ }
5480
+ function addChildInserts(t, model, rows, keys) {
5481
+ const values = rows.map((row) => createRowOf(t.context, model, void 0, row, void 0));
5482
+ if (t.readsBack) for (const row of values) writtenKeysOf(t, model, row, keys);
5483
+ addInsertRows(t.graph, t.context.contract, model.tables.root, values, {
5484
+ conflict: void 0,
5485
+ keys,
5486
+ junction: void 0
5487
+ });
5488
+ }
5489
+ function addFindAndAssert(t, related, name, kind, criterion, columns) {
5490
+ const { graph, context } = t;
5491
+ const where = requiredCriterion(context, related, name, kind, criterion);
5492
+ const find = graph.add(new Find(selectAstOf(context, related, {
5493
+ ...emptyState(related.tables),
5494
+ filters: [where],
5495
+ limit: 1
5496
+ }, "selection")));
5497
+ requireParentRow(t, find);
5498
+ const assert = graph.add(new Assert(ormError("ORM.RELATION_ROW_MISSING", `${kind}() nested mutation for relation "${name}" did not find a matching row`, { meta: {
5499
+ kind,
5500
+ relation: name
5501
+ } })));
5502
+ graph.addRowsEdge(find, assert, "rows", columns.map(([source]) => [source, source]));
5503
+ requireParentRow(t, assert);
5504
+ return find;
5505
+ }
5506
+ function requiredCriterion(context, model, name, kind, criterion) {
5507
+ const where = criterionWhere(context, model, criterion);
5508
+ if (where === void 0) throw ormError("ORM.RELATION_MUTATION_INVALID", `${kind}() nested mutation for relation "${name}" requires non-empty criterion`, { meta: {
5509
+ kind,
5510
+ relation: name,
5511
+ problem: "empty-criterion"
5512
+ } });
5513
+ return where;
5514
+ }
5515
+ function requireParentRow(t, node) {
5516
+ if (t.parentRow !== void 0) t.graph.addRequiresEdge(t.parentRow, node);
5517
+ }
5518
+ function criterionWhere(context, model, criterion) {
5519
+ return shorthandToWhereExpr(context, model.namespaceId, model.modelName, castAs(criterion), model.tables.root);
5520
+ }
5521
+ function linkKeyConflict(contract, relation) {
5522
+ const { through } = relation;
5523
+ const linkColumns = /* @__PURE__ */ new Set([...through.parentColumns, ...through.childColumns]);
5524
+ const table = storageTableForContract(contract, through.namespaceId, through.table);
5525
+ const key = [...table.primaryKey === void 0 ? [] : [table.primaryKey.columns], ...table.uniques.map((unique) => unique.columns)].find((columns) => columns.length === linkColumns.size && columns.every((column) => linkColumns.has(column)));
5526
+ return key === void 0 ? void 0 : { columns: key };
5527
+ }
5528
+ function relatedModel(contract, relation) {
5529
+ return {
5530
+ namespaceId: relation.toNamespace,
5531
+ modelName: relation.to,
5532
+ tables: createStatementTables({
5533
+ namespaceId: relation.toNamespace,
5534
+ tableName: resolveModelTableName(contract, relation.toNamespace, relation.to)
5535
+ })
5536
+ };
5537
+ }
5538
+ function localColumnsOf(contract, model, relation) {
5539
+ return relation.on.localFields.map((field) => columnOfContractField(contract, model.namespaceId, model.modelName, field));
5540
+ }
5541
+ function parseCreateInput(t, model, row) {
5542
+ return parseMutationInput(t.context.contract, model.namespaceId, model.modelName, row);
5543
+ }
5544
+ function columnMappings(contract, from, fromColumns, to, toColumns) {
5545
+ return fromColumns.map((column, index) => [projectTableColumn(contract, from, column), projectTableColumn(contract, to, blindCast(toColumns[index]))]);
5546
+ }
5353
5547
  var UnionAll = class extends Node {
5548
+ slots = { rows: "list" };
5354
5549
  constructor() {
5355
5550
  super();
5356
5551
  Object.freeze(this);
@@ -5359,96 +5554,120 @@ var UnionAll = class extends Node {
5359
5554
  return rowsResult((inputs.rows ?? []).flat());
5360
5555
  }
5361
5556
  };
5362
- var Update = class Update extends StatementNode {
5363
- ast;
5364
- constructor(ast) {
5365
- super();
5366
- this.ast = ast;
5367
- Object.freeze(this);
5368
- }
5369
- get returns() {
5370
- return this.ast.returning ?? [];
5371
- }
5372
- execute(inputs, run) {
5373
- return executeFiltered(this.ast, inputs.filter, run);
5374
- }
5375
- withReturning(columns) {
5376
- return new Update(this.ast.withReturning(withColumns(this.returns, columns)));
5377
- }
5378
- };
5379
5557
  function updateAllGraph(collection, set, returns) {
5380
5558
  const { context, state } = collection;
5381
- const graph = new Graph();
5559
+ const graph = new Graph(context.contract);
5382
5560
  if (Object.keys(set).length === 0) {
5383
- graph.setResult(graph.add(new Find(selectRowsAst(collection, state)), { filter: [] }));
5561
+ graph.setResult(graph.add(new Find(selectRowsAst(collection, state))));
5384
5562
  return graph;
5385
5563
  }
5386
5564
  requireIdentityColumnsForIncludes(collection);
5387
- const update = updateAst(context.contract, state.tables, set, whereOf(collection));
5565
+ const update = {
5566
+ where: whereOf(collection),
5567
+ filters: [],
5568
+ payloads: []
5569
+ };
5388
5570
  if (readsBack(collection, returns)) {
5389
5571
  const { namespaceId, tableName } = state.tables.root.storage;
5390
5572
  readBackIdentity(context.contract, namespaceId, tableName, collection.modelName, "updateAll()");
5391
- const found = graph.add(new Find(selectIdentityAst(collection, state)), { filter: [] });
5392
- graph.add(new Update(update), { filter: [] });
5393
- graph.setResult(addReadBack(graph, collection, found, keyOverrides(collection, set)));
5573
+ const found = graph.add(new Find(selectIdentityAst(collection, state)));
5574
+ addUpdateRows(graph, context.contract, state.tables, set, update);
5575
+ graph.setResult(addReadBack(graph, collection, found, keyOverrides(collection, set), state.includes));
5394
5576
  return graph;
5395
5577
  }
5396
- const updated = graph.add(new Update(update), { filter: [] });
5578
+ const updated = addUpdateRows(graph, context.contract, state.tables, set, update);
5397
5579
  graph.setResult(addWithIncludes(graph, collection, updated));
5398
5580
  return graph;
5399
5581
  }
5400
5582
  function deleteAllGraph(collection, returns) {
5401
5583
  const { context, state } = collection;
5402
- const graph = new Graph();
5403
- const del = new Delete(deleteAst(context.contract, state.tables, whereOf(collection)));
5584
+ const graph = new Graph(context.contract);
5585
+ const del = {
5586
+ where: whereOf(collection),
5587
+ filters: []
5588
+ };
5404
5589
  if (state.includes.length === 0 && !readsBack(collection, returns)) {
5405
- graph.setResult(graph.add(del, { filter: [] }));
5590
+ graph.setResult(addDeleteRows(graph, context.contract, state.tables, del));
5406
5591
  return graph;
5407
5592
  }
5408
- graph.setResult(graph.add(new Find(selectRowsAst(collection, state)), { filter: [] }));
5409
- graph.add(del, { filter: [] });
5593
+ graph.setResult(graph.add(new Find(selectRowsAst(collection, state))));
5594
+ addDeleteRows(graph, context.contract, state.tables, del);
5410
5595
  return graph;
5411
5596
  }
5412
- function updateFirstGraph(collection, set) {
5597
+ function updateFirstGraph(collection, data, relationMutations = []) {
5413
5598
  const { context, state } = collection;
5414
- const graph = new Graph();
5415
- const nothingToSet = Object.keys(set).length === 0;
5416
- if (!nothingToSet) {
5599
+ const graph = new Graph(context.contract);
5600
+ const set = mappedUpdateRow(collection, data);
5601
+ const bare = Object.keys(set).length === 0 && relationMutations.length === 0;
5602
+ if (!bare) {
5417
5603
  requireIdentityColumns(collection);
5418
5604
  requireIdentityColumnsForIncludes(collection);
5419
5605
  }
5420
- const find = addFindOfFirstRow(graph, collection, nothingToSet ? selectRowsAst : selectIdentityAst);
5606
+ const find = addFindOfFirstRow(graph, collection, bare ? selectRowsAst : selectIdentityAst);
5421
5607
  if (find === void 0) return graph;
5422
- if (nothingToSet) {
5608
+ if (bare) {
5423
5609
  graph.setResult(find);
5424
5610
  return graph;
5425
5611
  }
5426
- const update = updateAst(context.contract, state.tables, set, void 0);
5427
- if (readsBack(collection, "rows")) {
5428
- graph.add(new Update(update), { filter: [sameRow(find, collection)] });
5429
- graph.setResult(addReadBack(graph, collection, find, keyOverrides(collection, set)));
5612
+ const model = modelOf(collection);
5613
+ const t = {
5614
+ graph,
5615
+ context,
5616
+ parentRow: find,
5617
+ readsBack: readsBack(collection, "rows")
5618
+ };
5619
+ const before = addBeforeWrite(t, model, relationMutations);
5620
+ const values = withUpdateDefaults(collection, set, before);
5621
+ if (Object.keys(values).length === 0 && before.keys.length === 0) {
5622
+ addAfterWrite(t, model, find, relationMutations);
5623
+ graph.setResult(addWithIncludes(graph, collection, find));
5430
5624
  return graph;
5431
5625
  }
5432
- const updated = graph.add(new Update(update), { filter: [sameRow(find, collection)] });
5433
- graph.setResult(addWithIncludes(graph, collection, updated));
5626
+ const updated = addUpdateRows(graph, context.contract, state.tables, values, {
5627
+ where: void 0,
5628
+ filters: [{
5629
+ from: find,
5630
+ columns: sameRowColumns(collection)
5631
+ }],
5632
+ payloads: before.keys
5633
+ });
5634
+ if (!t.readsBack) {
5635
+ addAfterWrite(t, model, updated, relationMutations);
5636
+ graph.setResult(addWithIncludes(graph, collection, updated));
5637
+ return graph;
5638
+ }
5639
+ const changed = keyOverrides(collection, values);
5640
+ if (relationMutations.length === 0) {
5641
+ graph.setResult(addReadBack(graph, collection, find, changed, state.includes));
5642
+ return graph;
5643
+ }
5644
+ const updatedRow = addReadBack(graph, collection, find, changed, []);
5645
+ addAfterWrite(t, model, updatedRow, relationMutations);
5646
+ graph.setResult(addWithIncludes(graph, collection, updatedRow));
5434
5647
  return graph;
5435
5648
  }
5436
5649
  function deleteFirstGraph(collection) {
5437
5650
  const { context, state } = collection;
5438
5651
  const readsRowsFirst = state.includes.length > 0 || readsBack(collection, "rows");
5439
- const graph = new Graph();
5652
+ const graph = new Graph(context.contract);
5440
5653
  requireIdentityColumns(collection);
5441
5654
  const find = addFindOfFirstRow(graph, collection, readsRowsFirst ? selectRowsAst : selectIdentityAst);
5442
5655
  if (find === void 0) return graph;
5443
- const del = deleteAst(context.contract, state.tables, void 0);
5444
- const deleted = graph.add(new Delete(del), { filter: [sameRow(find, collection)] });
5656
+ const deleted = addDeleteRows(graph, context.contract, state.tables, {
5657
+ where: void 0,
5658
+ filters: [{
5659
+ from: find,
5660
+ columns: sameRowColumns(collection)
5661
+ }]
5662
+ });
5445
5663
  graph.setResult(readsRowsFirst ? find : deleted);
5446
5664
  return graph;
5447
5665
  }
5448
- function createAllGraph(collection, rows, conflict, returns) {
5666
+ function createAllGraph(collection, data, conflict, returns) {
5449
5667
  const { context, state } = collection;
5450
- const graph = new Graph();
5451
- if (rows.length === 0) return graph;
5668
+ const graph = new Graph(context.contract);
5669
+ if (data.length === 0) return graph;
5670
+ const rows = createRowsOf(collection, data);
5452
5671
  requireIdentityColumnsForIncludes(collection);
5453
5672
  const { contract } = context;
5454
5673
  const { root } = state.tables;
@@ -5468,52 +5687,73 @@ function createAllGraph(collection, rows, conflict, returns) {
5468
5687
  operation: rows.length === 1 ? "create" : "createAll",
5469
5688
  modelName: collection.modelName
5470
5689
  };
5471
- const inserted = graph.add(new InsertReportingKeys(asts, keys, generated, owner), {});
5690
+ const inserted = graph.add(new InsertReportingKeys(asts, keys, generated, owner));
5472
5691
  graph.setResult(addFindOfWrittenRows(graph, collection, inserted, identityProjection(collection), owner));
5473
5692
  return graph;
5474
5693
  }
5475
- const inserted = supportsDefaultInInsert(contract) ? graph.add(new Insert(insertAst(contract, root, rows, conflict)), { payload: [] }) : graph.add(new InsertChunked(groupRowsByColumnSignature(rows).map((group) => insertAst(contract, root, group, conflict))), {});
5694
+ const inserted = addInsertRows(graph, contract, root, rows, {
5695
+ conflict,
5696
+ keys: [],
5697
+ junction: void 0
5698
+ });
5476
5699
  graph.setResult(addWithIncludes(graph, collection, inserted));
5477
5700
  return graph;
5478
5701
  }
5479
- function supportsDefaultInInsert(contract) {
5480
- return contract.capabilities["sql"]?.["defaultInInsert"] === true;
5702
+ function createGraph(collection, parsed) {
5703
+ const { context } = collection;
5704
+ const graph = new Graph(context.contract);
5705
+ requireIdentityColumnsForIncludes(collection);
5706
+ const created = addCreateWithRelations({
5707
+ graph,
5708
+ context,
5709
+ parentRow: void 0,
5710
+ readsBack: readsBack(collection, "rows")
5711
+ }, modelOf(collection), parsed, []);
5712
+ graph.setResult(addWithIncludes(graph, collection, created));
5713
+ return graph;
5481
5714
  }
5482
- function createAllVariantGraph(collection, variantTable, variantModelName, rows) {
5715
+ function createAllVariantGraph(collection, variantTable, mti, data) {
5483
5716
  const { context, modelName, state } = collection;
5717
+ const variantModelName = mti.variant.modelName;
5718
+ const rows = variantCreateRowsOf(collection, mti, variantTable, data);
5484
5719
  const { contract } = context;
5485
5720
  const { root } = state.tables;
5486
- const graph = new Graph();
5721
+ const graph = new Graph(contract);
5487
5722
  const keyColumns = resolvePrimaryKeyColumns(contract, root.storage.namespaceId, root.storage.tableName);
5488
- const keyPairs = keyColumns.map((column) => [projectTableColumn(contract, root, column), projectTableColumn(contract, variantTable, column)]);
5723
+ const keyMappings = keyColumns.map((column) => [projectTableColumn(contract, root, column), projectTableColumn(contract, variantTable, column)]);
5489
5724
  const baseColumns = returningProjection(contract, modelName, root, void 0);
5490
5725
  const variantColumns = variantReturning(contract, variantTable, variantModelName, keyColumns);
5491
5726
  const joins = rows.map((row) => {
5492
5727
  const baseInsert = insertAst(contract, root, [row.base], void 0).withReturning(baseColumns);
5493
- const base = graph.add(new Insert(baseInsert), { payload: [] });
5728
+ const base = graph.add(new Insert(baseInsert));
5494
5729
  const variantInsert = insertAst(contract, variantTable, [row.variant], void 0).withReturning(variantColumns);
5495
- const variant = graph.add(new Insert(variantInsert), { payload: [new PayloadData(base, keyPairs)] });
5496
- return graph.add(new CrossJoin(), {
5497
- left: new Rows(base, sameColumns(baseColumns)),
5498
- right: new Rows(variant, sameColumns(variantColumns))
5499
- });
5730
+ const variant = graph.add(new Insert(variantInsert));
5731
+ graph.addPayloadDataEdge(base, variant, keyMappings);
5732
+ const join = graph.add(new CrossJoin());
5733
+ graph.addRowsEdge(base, join, "left", sameColumns(baseColumns));
5734
+ graph.addRowsEdge(variant, join, "right", sameColumns(variantColumns));
5735
+ return join;
5500
5736
  });
5501
5737
  const [only, ...others] = joins;
5502
5738
  if (only !== void 0 && others.length === 0) graph.setResult(only);
5503
5739
  else if (only !== void 0) {
5504
5740
  const joined = sameColumns([...baseColumns, ...variantColumns]);
5505
- graph.setResult(graph.add(new UnionAll(), { rows: joins.map((join) => new Rows(join, joined)) }));
5741
+ const union = graph.add(new UnionAll());
5742
+ for (const join of joins) graph.addRowsEdge(join, union, "rows", joined);
5743
+ graph.setResult(union);
5506
5744
  }
5507
5745
  return graph;
5508
5746
  }
5509
5747
  function sameColumns(columns) {
5510
5748
  return columns.map((column) => [column, column]);
5511
5749
  }
5512
- function upsertGraph(collection, create, update, conflictColumns) {
5750
+ function upsertGraph(collection, createData, updateData, conflictColumns) {
5513
5751
  const { context, state } = collection;
5752
+ const create = createRowOf(context, modelOf(collection), state.variantValue, createData, /* @__PURE__ */ new Map());
5753
+ const update = updateValuesOf(collection, updateData);
5514
5754
  const { contract } = context;
5515
5755
  const { root } = state.tables;
5516
- const graph = new Graph();
5756
+ const graph = new Graph(context.contract);
5517
5757
  requireIdentityColumnsForIncludes(collection);
5518
5758
  const targeted = hasContractCapability(contract, "insertOnConflictTarget");
5519
5759
  if (!targeted) requireOnlyCollidingKey(collection, create, conflictColumns);
@@ -5525,24 +5765,26 @@ function upsertGraph(collection, create, update, conflictColumns) {
5525
5765
  operation: "upsert",
5526
5766
  modelName: collection.modelName
5527
5767
  };
5528
- const upserted = graph.add(new InsertReportingKeys([upsert], [conflictValues], void 0, upsertOwner), {});
5768
+ const upserted = graph.add(new InsertReportingKeys([upsert], [conflictValues], void 0, upsertOwner));
5529
5769
  graph.setResult(addFindOfWrittenRows(graph, collection, upserted, projectTableColumns(contract, root, conflictColumns), upsertOwner));
5530
5770
  return graph;
5531
5771
  }
5532
- const upserted = graph.add(new Insert(upsert), { payload: [] });
5772
+ const upserted = graph.add(new Insert(upsert));
5533
5773
  graph.setResult(addWithIncludes(graph, collection, upserted));
5534
5774
  return graph;
5535
5775
  }
5536
5776
  function addWithIncludes(graph, collection, written) {
5537
5777
  if (collection.state.includes.length === 0) return written;
5538
- return graph.add(new Find(readBackAst(collection)), { filter: [sameRow(written, collection)] });
5778
+ const find = graph.add(new Find(readBackAst(collection, collection.state.includes)));
5779
+ graph.addFilterDataEdge(written, find, sameRowColumns(collection));
5780
+ return find;
5539
5781
  }
5540
- function readBackAst(collection) {
5782
+ function readBackAst(collection, includes) {
5541
5783
  const { state } = collection;
5542
5784
  return selectRowsAst(collection, {
5543
5785
  ...emptyState(state.tables),
5544
5786
  selectedFields: state.selectedFields,
5545
- includes: state.includes
5787
+ includes
5546
5788
  });
5547
5789
  }
5548
5790
  /**
@@ -5552,12 +5794,16 @@ function readsBack(collection, returns) {
5552
5794
  return returns === "rows" && !hasContractCapability(collection.context.contract, "returning");
5553
5795
  }
5554
5796
  /** A read of the rows a write changed, by the keys `keysFrom` found, with the new values of any key column the write set. */
5555
- function addReadBack(graph, collection, keysFrom, changed) {
5556
- return graph.add(new Find(readBackAst(collection)), { filter: [new FilterData(keysFrom, sameColumns(identityProjection(collection)), changed)] });
5797
+ function addReadBack(graph, collection, keysFrom, changed, includes) {
5798
+ const find = graph.add(new Find(readBackAst(collection, includes)));
5799
+ graph.addFilterDataEdge(keysFrom, find, sameColumns(identityProjection(collection)), changed);
5800
+ return find;
5557
5801
  }
5558
5802
  function addFindOfWrittenRows(graph, collection, inserted, keyColumns, owner) {
5559
- const pairs = sameColumns(keyColumns);
5560
- return graph.add(new FindByKeys(readBackAst(collection), pairs, owner), { keys: new Rows(inserted, pairs) });
5803
+ const mappings = sameColumns(keyColumns);
5804
+ const found = graph.add(new FindByKeys(readBackAst(collection, collection.state.includes), mappings, owner));
5805
+ graph.addRowsEdge(inserted, found, "keys", mappings);
5806
+ return found;
5561
5807
  }
5562
5808
  function identityProjection(collection) {
5563
5809
  const { context, state } = collection;
@@ -5615,7 +5861,7 @@ function addFindOfFirstRow(graph, collection, select) {
5615
5861
  return graph.add(new Find(select(collection, {
5616
5862
  ...state,
5617
5863
  limit: 1
5618
- })), { filter: [] });
5864
+ })));
5619
5865
  }
5620
5866
  function requireIdentityColumns(collection) {
5621
5867
  const { modelName, state } = collection;
@@ -5626,24 +5872,17 @@ function requireIdentityColumns(collection) {
5626
5872
  } });
5627
5873
  }
5628
5874
  function selectIdentityAst(collection, state) {
5629
- return collectionSelectAst(collection.context.contract, collection.modelName, {
5630
- ...state,
5631
- includes: [],
5632
- selectedFields: identityColumnsOf(collection)
5633
- });
5875
+ return selectAstOf(collection.context, modelOf(collection), state, "identity");
5634
5876
  }
5635
5877
  function selectRowsAst(collection, state) {
5636
- const { context, modelName } = collection;
5637
- if (state.includes.length === 0) return collectionSelectAst(context.contract, modelName, state);
5638
- return collectionSelectWithIncludesAst(context.contract, context.aggregateDescriptors, modelName, state);
5878
+ return selectAstOf(collection.context, modelOf(collection), state, "selection");
5639
5879
  }
5640
5880
  function identityColumnsOf(collection) {
5641
5881
  const { namespaceId, tableName } = collection.state.tables.root.storage;
5642
5882
  return resolveRowIdentityColumns(collection.context.contract, namespaceId, tableName);
5643
5883
  }
5644
- function sameRow(find, collection) {
5645
- const { context, state } = collection;
5646
- return new FilterData(find, projectTableColumns(context.contract, state.tables.root, identityColumnsOf(collection)).map((column) => [column, column]));
5884
+ function sameRowColumns(collection) {
5885
+ return sameColumns(identityProjection(collection));
5647
5886
  }
5648
5887
  function whereOf(collection) {
5649
5888
  const { context, state } = collection;
@@ -5651,7 +5890,7 @@ function whereOf(collection) {
5651
5890
  }
5652
5891
  function queryGraph(graph, ctx, callerRows) {
5653
5892
  returnCallerColumns(graph, callerRows);
5654
- const [only, ...others] = graph.nodes();
5893
+ const [only, ...others] = statementNodes(graph);
5655
5894
  if (only !== void 0 && others.length === 0 && only[0] === graph.result) {
5656
5895
  const [id, node] = only;
5657
5896
  const run = runOn(ctx, ctx.runtime);
@@ -5670,9 +5909,26 @@ function returnCallerColumns(graph, callerRows) {
5670
5909
  const columns = returningProjection(context.contract, modelName, state.tables.root, state.selectedFields);
5671
5910
  for (const [id, node] of graph.nodes()) if (id === graph.result && node instanceof StatementNode) graph.replace(id, node.withReturning(columns));
5672
5911
  }
5673
- function runAllNodes(graph, ctx, callerRows) {
5674
- if (graph.nodes().length > 1) return withMutationScope(ctx.runtime, (scope) => runNodesInOrder(graph, ctx, scope, callerRows));
5675
- return runNodesInOrder(graph, ctx, ctx.runtime, callerRows);
5912
+ async function runAllNodes(graph, ctx, callerRows) {
5913
+ const { runtime } = ctx;
5914
+ if (statementNodes(graph).length > 1 && runtime.transaction !== void 0) return runInTransaction(await runtime.transaction(), (scope) => runNodesInOrder(graph, ctx, scope, callerRows));
5915
+ return runNodesInOrder(graph, ctx, runtime, callerRows);
5916
+ }
5917
+ async function runInTransaction(transaction, run) {
5918
+ try {
5919
+ const result = await run(transaction);
5920
+ await transaction.commit();
5921
+ return result;
5922
+ } catch (error) {
5923
+ try {
5924
+ await transaction.rollback();
5925
+ } catch (rollbackError) {
5926
+ const settlement = settlementOf(transaction);
5927
+ if (settlement?.rolledBack !== true) throw rollbackError;
5928
+ settlement.logDroppedError(rollbackError);
5929
+ }
5930
+ throw error;
5931
+ }
5676
5932
  }
5677
5933
  async function runNodesInOrder(graph, ctx, scope, callerRows) {
5678
5934
  const run = runOn(ctx, scope);
@@ -5712,12 +5968,15 @@ function shapeRows(graph, id, storageRows, callerRows) {
5712
5968
  const { contract } = context;
5713
5969
  const { tableName } = state.tables.root.storage;
5714
5970
  const selected = state.selectedFields ?? getColumnsReadOnTable(contract, namespaceId, modelName, tableName);
5715
- const hiddenColumns = graph.readersOf(id).flatMap(({ edge }) => edge.columns.map(([source]) => source.alias)).filter((column) => !selected.includes(column));
5971
+ const hiddenColumns = graph.columnsReadFrom(id).map((column) => column.alias).filter((column) => !selected.includes(column));
5716
5972
  return mapResultRows(consumeCollectionRows(callerRows, storageRows), (row) => {
5717
5973
  stripHiddenMappedFields(contract, namespaceId, modelName, row, hiddenColumns);
5718
5974
  return blindCast(row);
5719
5975
  });
5720
5976
  }
5977
+ function statementNodes(graph) {
5978
+ return graph.nodes().filter(([, node]) => node instanceof StatementNode);
5979
+ }
5721
5980
  function rowsOf(executed) {
5722
5981
  return Array.isArray(executed) ? executed : [];
5723
5982
  }
@@ -5833,27 +6092,6 @@ function assertRelationUpdateIgnoresNothing(state, modelName) {
5833
6092
  }
5834
6093
  });
5835
6094
  }
5836
- function applyCreateDefaults(ctx, namespaceId, tableName, rows, defaultValueCache = /* @__PURE__ */ new Map()) {
5837
- for (const row of rows) {
5838
- const applied = ctx.context.applyMutationDefaults({
5839
- op: "create",
5840
- entry: tableName,
5841
- namespace: namespaceId,
5842
- values: row,
5843
- defaultValueCache
5844
- });
5845
- for (const def of applied) row[def.field] = def.value;
5846
- }
5847
- }
5848
- function applyUpdateDefaults(ctx, namespaceId, tableName, values) {
5849
- const applied = ctx.context.applyMutationDefaults({
5850
- op: "update",
5851
- entry: tableName,
5852
- namespace: namespaceId,
5853
- values
5854
- });
5855
- for (const def of applied) values[def.field] = def.value;
5856
- }
5857
6095
  function isToWhereExprInput(value) {
5858
6096
  return typeof value === "object" && value !== null && "toWhereExpr" in value && typeof value.toWhereExpr === "function";
5859
6097
  }
@@ -5870,9 +6108,6 @@ function splitCreateArguments(optionsOrConfigure, configure) {
5870
6108
  configureCallback: configure
5871
6109
  };
5872
6110
  }
5873
- function isMtiVariantInfo(variant) {
5874
- return variant?.strategy === "mti";
5875
- }
5876
6111
  var CollectionBase = class CollectionBase {
5877
6112
  /** @internal */
5878
6113
  ctx;
@@ -6329,21 +6564,14 @@ var CollectionBase = class CollectionBase {
6329
6564
  return runOrmCall(this.ctx.runtime, this.#writeCall("create", annotations, ormResults.row), (queryable) => this.#create(queryable, data));
6330
6565
  }
6331
6566
  async #create(queryable, data) {
6332
- if (hasNestedMutationCallbacks(this.contract, this.namespaceId, this.modelName, blindCast(data))) {
6333
- const createdRow = await executeNestedCreateMutation({
6334
- context: this.ctx.context,
6335
- runtime: queryable,
6336
- namespaceId: this.namespaceId,
6337
- modelName: this.modelName,
6338
- data: blindCast(data)
6339
- });
6340
- const identityCriterion = buildRowIdentityFilterFromRow(this.contract, this.namespaceId, this.modelName, createdRow);
6341
- const reloaded = await this.#reloadMutationRowByIdentity(queryable, identityCriterion);
6342
- if (!reloaded) throw ormError("ORM.MUTATION_ROW_MISSING", `create() for model "${this.modelName}" did not return a row`, { meta: {
6567
+ const parsed = parseMutationInput(this.contract, this.namespaceId, this.modelName, blindCast(data));
6568
+ if (parsed.relationMutations.length > 0) {
6569
+ const [created] = await queryGraph(createGraph(this.#descriptionOptions(), parsed), this.#on(queryable), this.#descriptionOptions()).toArray();
6570
+ if (created === void 0) throw ormError("ORM.MUTATION_ROW_MISSING", `create() for model "${this.modelName}" did not return a row`, { meta: {
6343
6571
  operation: "create",
6344
6572
  model: this.modelName
6345
6573
  } });
6346
- return reloaded;
6574
+ return created;
6347
6575
  }
6348
6576
  const created = (await this.#createAllRows([blindCast(data)])(queryable))[0];
6349
6577
  if (created) return created;
@@ -6365,21 +6593,16 @@ var CollectionBase = class CollectionBase {
6365
6593
  return () => new AsyncIterableResult(generator());
6366
6594
  }
6367
6595
  const rows = blindCast(data);
6368
- const mtiContext = this.#resolveMtiCreateContext();
6596
+ const mtiContext = mtiCreateContextOf(this.#descriptionOptions());
6369
6597
  if (mtiContext) {
6370
6598
  assertReturningCapability(this.contract, "createAll()");
6371
6599
  const variantTable = requireVariantTable(this.state.tables, mtiContext.variant.value);
6372
- const graph = createAllVariantGraph(this.#descriptionWithoutIncludes(), variantTable, mtiContext.variant.modelName, this.#variantCreateRows(rows, mtiContext, variantTable));
6600
+ const graph = createAllVariantGraph(this.#descriptionWithoutIncludes(), variantTable, mtiContext, rows);
6373
6601
  return (queryable) => queryGraph(graph, this.#on(queryable), this.#descriptionWithoutIncludes());
6374
6602
  }
6375
- const graph = createAllGraph(this.#descriptionOptions(), this.#createValues(rows), conflictSkip, "rows");
6603
+ const graph = createAllGraph(this.#descriptionOptions(), rows, conflictSkip, "rows");
6376
6604
  return (queryable) => queryGraph(graph, this.#on(queryable), this.#descriptionOptions());
6377
6605
  }
6378
- #createValues(rows) {
6379
- const mappedRows = this.#mapCreateRows(rows);
6380
- applyCreateDefaults(this.ctx, this.namespaceId, this.tableName, mappedRows);
6381
- return mappedRows;
6382
- }
6383
6606
  #resolveConflictSkip(options, method) {
6384
6607
  if (options === void 0) return void 0;
6385
6608
  if (options.onConflict !== "skip") throw ormError("ORM.ARGUMENT_INVALID", `${method} onConflict must be "skip"; received ${JSON.stringify(options.onConflict)}`, { meta: {
@@ -6399,7 +6622,7 @@ var CollectionBase = class CollectionBase {
6399
6622
  this.#refuseOnMtiVariant(method, `The onConflict option is not supported on variant "${this.#variantModelName()}" of model "${this.modelName}" because the variant is stored in its own table. Call createAll(rows) without the option; a duplicate row then makes the call fail.`);
6400
6623
  }
6401
6624
  #refuseOnMtiVariant(method, message) {
6402
- if (!this.#resolveMtiCreateContext()) return;
6625
+ if (!mtiCreateContextOf(this.#descriptionOptions())) return;
6403
6626
  throw ormError("ORM.OPERATION_UNSUPPORTED", message, { meta: {
6404
6627
  method,
6405
6628
  model: this.modelName,
@@ -6410,65 +6633,6 @@ var CollectionBase = class CollectionBase {
6410
6633
  #variantModelName() {
6411
6634
  return addressedModel(this.contract, this.namespaceId, this.modelName, this.state.variantValue)[1];
6412
6635
  }
6413
- #resolveMtiCreateContext() {
6414
- const variantValue = this.state.variantValue;
6415
- if (!variantValue) return null;
6416
- const polyInfo = resolvePolymorphismInfo(this.contract, this.namespaceId, this.modelName);
6417
- if (!polyInfo) return null;
6418
- const variant = polyInfo.variants.get(variantValue);
6419
- if (!isMtiVariantInfo(variant)) return null;
6420
- return {
6421
- polyInfo,
6422
- variant,
6423
- baseFieldToColumn: getModelFieldColumns(this.contract, this.namespaceId, this.modelName),
6424
- variantFieldToColumn: getOwnFieldColumns(this.contract, variant.namespaceId, variant.modelName),
6425
- mergedFieldToColumn: getModelAndVariantFieldColumns(this.contract, this.namespaceId, this.modelName, variant.value)
6426
- };
6427
- }
6428
- #variantCreateRows(data, mtiCtx, variantTable) {
6429
- const { polyInfo, variant, baseFieldToColumn, variantFieldToColumn, mergedFieldToColumn } = mtiCtx;
6430
- const baseFieldColumns = new Set(Object.values(baseFieldToColumn));
6431
- const variantFieldColumns = new Set(Object.values(variantFieldToColumn));
6432
- const defaultValueCache = /* @__PURE__ */ new Map();
6433
- return data.map((row) => {
6434
- const allMapped = {};
6435
- for (const [fieldName, value] of Object.entries(row)) {
6436
- if (value === void 0) continue;
6437
- allMapped[columnOfCallerField(this.contract, this.namespaceId, mergedFieldToColumn, variant.modelName, fieldName)] = value;
6438
- }
6439
- allMapped[polyInfo.discriminatorColumn] = variant.value;
6440
- const baseRow = {};
6441
- const variantRow = {};
6442
- for (const [column, value] of Object.entries(allMapped)) {
6443
- if (baseFieldColumns.has(column) || column === polyInfo.discriminatorColumn) baseRow[column] = value;
6444
- if (variantFieldColumns.has(column)) variantRow[column] = value;
6445
- }
6446
- applyCreateDefaults(this.ctx, this.namespaceId, this.tableName, [baseRow], defaultValueCache);
6447
- applyCreateDefaults(this.ctx, variantTable.storage.namespaceId, variantTable.storage.tableName, [variantRow], defaultValueCache);
6448
- return {
6449
- base: baseRow,
6450
- variant: variantRow
6451
- };
6452
- });
6453
- }
6454
- #mapCreateRows(data) {
6455
- const variantValue = this.state.variantValue;
6456
- if (!variantValue) return data.map((row) => mapModelDataToStorageRow(this.contract, this.namespaceId, this.modelName, row));
6457
- const polyInfo = resolvePolymorphismInfo(this.contract, this.namespaceId, this.modelName);
6458
- if (!polyInfo) return data.map((row) => mapModelDataToStorageRow(this.contract, this.namespaceId, this.modelName, row));
6459
- const variant = polyInfo.variants.get(variantValue);
6460
- if (!variant) return data.map((row) => mapModelDataToStorageRow(this.contract, this.namespaceId, this.modelName, row));
6461
- const mergedFieldToColumn = getModelAndVariantFieldColumns(this.contract, this.namespaceId, this.modelName, variant.value);
6462
- return data.map((row) => {
6463
- const mapped = {};
6464
- for (const [fieldName, value] of Object.entries(row)) {
6465
- if (value === void 0) continue;
6466
- mapped[columnOfCallerField(this.contract, variant.namespaceId, mergedFieldToColumn, variant.modelName, fieldName)] = value;
6467
- }
6468
- mapped[polyInfo.discriminatorColumn] = variant.value;
6469
- return mapped;
6470
- });
6471
- }
6472
6636
  /**
6473
6637
  * Write terminal: insert many rows without materializing the
6474
6638
  * inserted rows, returning the number of rows the database reports
@@ -6503,7 +6667,7 @@ var CollectionBase = class CollectionBase {
6503
6667
  if (data.length === 0) return runOrmCall(this.ctx.runtime, call, async () => 0);
6504
6668
  this.#assertNotMtiVariant("createAndCount()");
6505
6669
  const rows = blindCast(data);
6506
- const graph = createAllGraph(this.#descriptionWithoutIncludes(), this.#createValues(rows), conflictSkip, "count");
6670
+ const graph = createAllGraph(this.#descriptionWithoutIncludes(), rows, conflictSkip, "count");
6507
6671
  return this.#countCall(call, graph);
6508
6672
  }
6509
6673
  #countCall(call, graph) {
@@ -6515,16 +6679,12 @@ var CollectionBase = class CollectionBase {
6515
6679
  assertLockCompatible(this.state, "mutation");
6516
6680
  this.#assertNotMtiVariant("upsert()");
6517
6681
  const annotations = this.#collectAnnotationsFromMeta(configure, "write", "upsert");
6518
- const createValues = this.#mapCreateRows([blindCast(input.create)])[0] ?? {};
6519
- applyCreateDefaults(this.ctx, this.namespaceId, this.tableName, [createValues]);
6520
- const updateValues = mapModelDataToStorageRow(this.contract, this.namespaceId, this.modelName, input.update);
6521
- if (Object.keys(updateValues).length > 0) applyUpdateDefaults(this.ctx, this.namespaceId, this.tableName, updateValues);
6522
6682
  const conflictColumns = resolveUpsertConflictColumns(this.contract, this.namespaceId, this.modelName, blindCast(input.conflictOn));
6523
6683
  if (conflictColumns.length === 0) throw ormError("ORM.ARGUMENT_INVALID", `upsert() for model "${this.modelName}" requires conflict columns`, { meta: {
6524
6684
  method: "upsert",
6525
6685
  model: this.modelName
6526
6686
  } });
6527
- const graph = upsertGraph(this.#descriptionOptions(), createValues, updateValues, conflictColumns);
6687
+ const graph = upsertGraph(this.#descriptionOptions(), blindCast(input.create), input.update, conflictColumns);
6528
6688
  return runOrmCall(this.ctx.runtime, this.#writeCall("upsert", annotations, ormResults.row), async (queryable) => {
6529
6689
  const row = await consumeFirstRow(queryGraph(graph, this.#on(queryable), this.#descriptionOptions()));
6530
6690
  if (row) return row;
@@ -6540,30 +6700,17 @@ var CollectionBase = class CollectionBase {
6540
6700
  return runOrmCall(this.ctx.runtime, this.#writeCall("update", annotations, ormResults.rowOrNull), (queryable) => this.#update(queryable, data));
6541
6701
  }
6542
6702
  async #update(queryable, data) {
6543
- if (hasNestedMutationCallbacks(this.contract, this.namespaceId, this.modelName, blindCast(data))) {
6544
- assertRelationUpdateIgnoresNothing(this.state, this.modelName);
6545
- const updatedRow = await executeNestedUpdateMutation({
6546
- context: this.ctx.context,
6547
- runtime: queryable,
6548
- namespaceId: this.namespaceId,
6549
- modelName: this.modelName,
6550
- tables: this.state.tables,
6551
- filters: this.state.filters,
6552
- data: blindCast(data)
6553
- });
6554
- if (!updatedRow) return null;
6555
- const identityCriterion = buildRowIdentityFilterFromRow(this.contract, this.namespaceId, this.modelName, updatedRow);
6556
- return this.#reloadMutationRowByIdentity(queryable, identityCriterion);
6557
- }
6558
- assertModelFieldNames(this.contract, this.namespaceId, this.modelName, blindCast(data));
6559
- const values = this.#updateValues(blindCast(data));
6560
- return consumeFirstRow(queryGraph(updateFirstGraph(this.#descriptionOptions(), values), this.#on(queryable), this.#descriptionOptions()));
6703
+ const input = blindCast(data);
6704
+ const parsed = parseMutationInput(this.contract, this.namespaceId, this.modelName, input);
6705
+ if (parsed.relationMutations.length > 0) assertRelationUpdateIgnoresNothing(this.state, this.modelName);
6706
+ assertModelFieldNames(this.contract, this.namespaceId, this.modelName, parsed.scalarData);
6707
+ return consumeFirstRow(queryGraph(updateFirstGraph(this.#descriptionOptions(), parsed.scalarData, parsed.relationMutations), this.#on(queryable), this.#descriptionOptions()));
6561
6708
  }
6562
6709
  updateAll(data, configure) {
6563
6710
  assertBulkWriteIgnoresNothing(this.state, this.modelName, "updateAll");
6564
6711
  assertLockCompatible(this.state, "mutation");
6565
6712
  const annotations = this.#collectAnnotationsFromMeta(configure, "write", "updateAll");
6566
- const graph = updateAllGraph(this.#descriptionOptions(), this.#updateValues(data), "rows");
6713
+ const graph = updateAllGraph(this.#descriptionOptions(), updateValuesOf(this.#descriptionOptions(), data), "rows");
6567
6714
  return this.#rowsCall("updateAll", annotations, graph);
6568
6715
  }
6569
6716
  #rowsCall(method, annotations, graph) {
@@ -6575,8 +6722,8 @@ var CollectionBase = class CollectionBase {
6575
6722
  async updateAndCount(data, configure) {
6576
6723
  assertBulkWriteIgnoresNothing(this.state, this.modelName, "updateAndCount");
6577
6724
  assertLockCompatible(this.state, "mutation");
6578
- const values = this.#updateValues(data);
6579
- const graph = Object.keys(values).length === 0 ? new Graph() : updateAllGraph(this.#descriptionWithoutIncludes(), values, "count");
6725
+ const values = updateValuesOf(this.#descriptionOptions(), data);
6726
+ const graph = Object.keys(values).length === 0 ? new Graph(this.contract) : updateAllGraph(this.#descriptionWithoutIncludes(), values, "count");
6580
6727
  const annotations = this.#collectAnnotationsFromMeta(configure, "write", "updateAndCount");
6581
6728
  return this.#countCall(this.#writeCall("updateAndCount", annotations, ormResults.count), graph);
6582
6729
  }
@@ -6609,32 +6756,6 @@ var CollectionBase = class CollectionBase {
6609
6756
  }
6610
6757
  };
6611
6758
  }
6612
- #updateValues(data) {
6613
- const values = mapModelDataToStorageRow(this.contract, this.namespaceId, this.modelName, data);
6614
- if (Object.keys(values).length > 0) applyUpdateDefaults(this.ctx, this.namespaceId, this.tableName, values);
6615
- return values;
6616
- }
6617
- async #reloadMutationRowByIdentity(queryable, criterion) {
6618
- return this.#reloadMutationRowByCriterion(queryable, criterion, "row identity");
6619
- }
6620
- async #reloadMutationRowByCriterion(queryable, criterion, criterionLabel) {
6621
- const whereExpr = shorthandToWhereExpr(this.ctx.context, this.namespaceId, this.modelName, blindCast(criterion), this.state.tables.root);
6622
- if (!whereExpr) throw new InternalError(`Failed to build ${criterionLabel} filter for mutation result on model "${this.modelName}"`);
6623
- const resultState = {
6624
- ...emptyState(this.state.tables),
6625
- filters: [whereExpr],
6626
- includes: this.state.includes,
6627
- selectedFields: this.state.selectedFields,
6628
- limit: 1
6629
- };
6630
- return (await dispatchCollectionRows({
6631
- context: this.ctx.context,
6632
- runtime: queryable,
6633
- state: resultState,
6634
- modelName: this.modelName,
6635
- namespaceId: this.namespaceId
6636
- }))[0] ?? null;
6637
- }
6638
6759
  #assertIncludeRefinementMode(action) {
6639
6760
  if (this.includeRefinementMode) return;
6640
6761
  throw ormError("ORM.INCLUDE_INVALID", `${action} is only available inside include() refinement callbacks`, { meta: { action } });