@prisma/orm-family-sql 8.0.0-rc.23-dev.13 → 8.0.0-rc.24-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/{ast-CrnvUofJ.d.mts → ast-DGfphK4T.d.mts} +2 -2
  2. package/dist/{ast-CrnvUofJ.d.mts.map → ast-DGfphK4T.d.mts.map} +1 -1
  3. package/dist/builder.d.mts +3 -3
  4. package/dist/builder__runtime.d.mts +7 -7
  5. package/dist/builder__types.d.mts +5 -5
  6. package/dist/{collection-methods-p_bnn5LM-B8bdfRNR.d.mts → collection-methods-CvUwcmzf-BW0NhiB_.d.mts} +3 -3
  7. package/dist/{collection-methods-p_bnn5LM-B8bdfRNR.d.mts.map → collection-methods-CvUwcmzf-BW0NhiB_.d.mts.map} +1 -1
  8. package/dist/collection-methods-TTQfofph.d.mts +1 -0
  9. package/dist/{control-C0Jp0muh.d.mts → control-Bp3csZwm.d.mts} +5 -5
  10. package/dist/{control-C0Jp0muh.d.mts.map → control-Bp3csZwm.d.mts.map} +1 -1
  11. package/dist/{control-adapter-BfyLe7rh-0LQGA2VV.d.mts → control-adapter-BfyLe7rh-BzDhqiKl.d.mts} +3 -3
  12. package/dist/{control-adapter-BfyLe7rh-0LQGA2VV.d.mts.map → control-adapter-BfyLe7rh-BzDhqiKl.d.mts.map} +1 -1
  13. package/dist/{control-adapter-DMrjnUFj.d.mts → control-adapter-ltsPDa2r.d.mts} +2 -2
  14. package/dist/{control-adapter-DMrjnUFj.d.mts.map → control-adapter-ltsPDa2r.d.mts.map} +1 -1
  15. package/dist/{db-DfYeGVcu-NRittTYE.d.mts → db-DfYeGVcu-o1Z8rm-W.d.mts} +7 -7
  16. package/dist/{db-DfYeGVcu-NRittTYE.d.mts.map → db-DfYeGVcu-o1Z8rm-W.d.mts.map} +1 -1
  17. package/dist/{diff-BBEq2-E2.d.mts → diff-Br8rXGsH.d.mts} +2 -2
  18. package/dist/{diff-BBEq2-E2.d.mts.map → diff-Br8rXGsH.d.mts.map} +1 -1
  19. package/dist/{driver-types-Bobm0hWv-B9rTP8XQ.d.mts → driver-types-BpWfDb-T-DlmIXaYA.d.mts} +7 -4
  20. package/dist/driver-types-BpWfDb-T-DlmIXaYA.d.mts.map +1 -0
  21. package/dist/{exports-WNaGWaJR-C6wltYlN.mjs → exports-cGSgYmrd-BADpxA8G.mjs} +130 -47
  22. package/dist/exports-cGSgYmrd-BADpxA8G.mjs.map +1 -0
  23. package/dist/{expression-DmvKA8dE-D29cLTJG.d.mts → expression-67JiCQFK-DaVAG7yC.d.mts} +3 -3
  24. package/dist/{expression-DmvKA8dE-D29cLTJG.d.mts.map → expression-67JiCQFK-DaVAG7yC.d.mts.map} +1 -1
  25. package/dist/{expression-DSAx-7Ri-C4W_nQ6T.d.mts → expression-Ba92rPKp-DtfV_Whm.d.mts} +3 -3
  26. package/dist/expression-Ba92rPKp-DtfV_Whm.d.mts.map +1 -0
  27. package/dist/expression-D_ZePY3d.d.mts +2 -0
  28. package/dist/family.d.mts +6 -6
  29. package/dist/family__control-adapter.d.mts +2 -2
  30. package/dist/family__control.d.mts +2 -2
  31. package/dist/family__diff.d.mts +1 -1
  32. package/dist/family__migration.d.mts +1 -1
  33. package/dist/functions-D8u9_Jq4.d.mts +1 -0
  34. package/dist/{index-reference-2EXdtnBp-BxO97DG1.d.mts → index-reference-BG-nULu_-DqCWjexx.d.mts} +3 -3
  35. package/dist/{index-reference-2EXdtnBp-BxO97DG1.d.mts.map → index-reference-BG-nULu_-DqCWjexx.d.mts.map} +1 -1
  36. package/dist/index-reference-WLPSKxp9.d.mts +1 -0
  37. package/dist/{index-rlHk9lB3.d.mts → index-vuHRWh8m.d.mts} +23 -19
  38. package/dist/index-vuHRWh8m.d.mts.map +1 -0
  39. package/dist/{migration-CkdSQ8g8.d.mts → migration-BoLlkc9N.d.mts} +2 -2
  40. package/dist/{migration-CkdSQ8g8.d.mts.map → migration-BoLlkc9N.d.mts.map} +1 -1
  41. package/dist/orm-client.d.mts +60 -25
  42. package/dist/orm-client.d.mts.map +1 -1
  43. package/dist/orm-client.mjs +1148 -730
  44. package/dist/orm-client.mjs.map +1 -1
  45. package/dist/query-lane-context-Bku0eZ9n.d.mts +1 -0
  46. package/dist/{query-lane-context-DRO74vm5-BbGhhycI.d.mts → query-lane-context-sTTORN1t-BShwHBX6.d.mts} +4 -4
  47. package/dist/{query-lane-context-DRO74vm5-BbGhhycI.d.mts.map → query-lane-context-sTTORN1t-BShwHBX6.d.mts.map} +1 -1
  48. package/dist/relational-core.d.mts +8 -8
  49. package/dist/relational-core__aggregate-descriptor-registry.d.mts +1 -1
  50. package/dist/relational-core__ast.d.mts +3 -3
  51. package/dist/relational-core__codec-descriptor-registry.d.mts +1 -1
  52. package/dist/relational-core__collection-methods.d.mts +2 -2
  53. package/dist/relational-core__expression.d.mts +3 -3
  54. package/dist/relational-core__functions.d.mts +2 -2
  55. package/dist/relational-core__index-reference.d.mts +2 -2
  56. package/dist/relational-core__query-lane-context.d.mts +2 -2
  57. package/dist/relational-core__types.d.mts +2 -2
  58. package/dist/runtime.d.mts +5 -5
  59. package/dist/runtime.mjs +1 -1
  60. package/dist/runtime__internal__prepared-query.d.mts +2 -2
  61. package/dist/runtime__internal__prepared-query.mjs +2 -2
  62. package/dist/{transaction-state-DR3nKTmH-DO1YOoZJ.d.mts → transaction-state-CEe4TlC1-BGIdTh1r.d.mts} +10 -9
  63. package/dist/{transaction-state-DR3nKTmH-DO1YOoZJ.d.mts.map → transaction-state-CEe4TlC1-BGIdTh1r.d.mts.map} +1 -1
  64. package/dist/{types-COXfSNOP-CA6F1reR.d.mts → types-COXfSNOP-DIsV7kxg.d.mts} +2 -2
  65. package/dist/{types-COXfSNOP-CA6F1reR.d.mts.map → types-COXfSNOP-DIsV7kxg.d.mts.map} +1 -1
  66. package/dist/{types-DpgxiOSn-DrRvhBfy.d.mts → types-QoMfRyfh-Cg6Cam8W.d.mts} +4 -4
  67. package/dist/{types-DpgxiOSn-DrRvhBfy.d.mts.map → types-QoMfRyfh-Cg6Cam8W.d.mts.map} +1 -1
  68. package/dist/types-f_lF2HSL.d.mts +1 -0
  69. package/package.json +18 -18
  70. package/dist/collection-methods-B6AtdlXI.d.mts +0 -1
  71. package/dist/driver-types-Bobm0hWv-B9rTP8XQ.d.mts.map +0 -1
  72. package/dist/exports-WNaGWaJR-C6wltYlN.mjs.map +0 -1
  73. package/dist/expression-CMV-f0HM.d.mts +0 -2
  74. package/dist/expression-DSAx-7Ri-C4W_nQ6T.d.mts.map +0 -1
  75. package/dist/functions-CLrZo2Gj.d.mts +0 -1
  76. package/dist/index-reference-C4a-sIjK.d.mts +0 -1
  77. package/dist/index-rlHk9lB3.d.mts.map +0 -1
  78. package/dist/query-lane-context-CNY3sTaF.d.mts +0 -1
  79. package/dist/types-CSORxTRT.d.mts +0 -1
@@ -1,5 +1,5 @@
1
1
  import { t as resolveStorageTable } from "./resolve-storage-table-BHLQsOza.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";
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, 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";
3
3
  import { t as collectOrderedParamRefs } from "./util-DixeJBri-Cad7x5ec.mjs";
4
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
5
  import { a as isExpression, s as toExpr, t as ExpressionImpl } from "./expression-impl-DHdjzqE3-Cd9gP7oC.mjs";
@@ -7,7 +7,7 @@ import { n as codecRefForStorageColumn } from "./codec-descriptor-registry-UiFDv
7
7
  import { t as createFunctions } from "./functions-Cl_egJ2w.mjs";
8
8
  import { t as createIndexReferences } from "./index-reference-BQSrkRfT.mjs";
9
9
  import { o as settlementOf } from "./transaction-state-BfXhs7D7-DhmbySW9.mjs";
10
- import { h as findActivitySource } from "./exports-WNaGWaJR-C6wltYlN.mjs";
10
+ import { h as findActivitySource } from "./exports-cGSgYmrd-BADpxA8G.mjs";
11
11
  import { isStructuredError, structuredError } from "@prisma/orm-framework/utils/structured-error";
12
12
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
13
13
  import { domainModelsAtDefaultNamespace } from "@prisma/orm-framework/contract/types";
@@ -4301,42 +4301,35 @@ function updateAst(contract, tables, setValues, where) {
4301
4301
  function deleteAst(contract, tables, where) {
4302
4302
  return DeleteAst.from(tables.root.tableSource(contract)).withWhere(where);
4303
4303
  }
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
4316
- };
4304
+ function generatedKeyColumn(options) {
4305
+ const { context, namespaceId, tableName, modelName, rows, method, columns } = options;
4306
+ const [column, ...others] = columns.filter((key) => !rows.every((row) => row[key] !== void 0));
4307
+ if (column === void 0) return;
4317
4308
  const refused = (problem) => ormError("ORM.CAPABILITY_MISSING", `${method} on model "${modelName}" ${problem}`, { meta: {
4318
4309
  capability: "returning",
4319
4310
  action: method
4320
4311
  } });
4321
4312
  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
4313
  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.`);
4314
+ return column;
4315
+ }
4316
+ function generatedKey(options) {
4317
+ const column = generatedKeyColumn(options);
4318
+ if (column === void 0) return;
4319
+ const { context, namespaceId, tableName } = options;
4323
4320
  const codec = context.contractCodecs.forColumn(namespaceId, tableName, column);
4324
4321
  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
- }
4322
+ column,
4323
+ decode: async (insertId) => codec === void 0 ? insertId : codec.fromWire(insertId, { column: {
4324
+ table: tableName,
4325
+ name: column
4326
+ } })
4333
4327
  };
4334
4328
  }
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) {
4329
+ function rowIdentity(contract, namespaceId, tableName, modelName, method) {
4337
4330
  const identity = resolveRowIdentityColumns(contract, namespaceId, tableName);
4338
4331
  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: {
4332
+ throw ormError("ORM.ROW_IDENTITY_MISSING", `${method} on model "${modelName}" requires the table to have a primary key or unique constraint`, { meta: {
4340
4333
  model: modelName,
4341
4334
  table: tableName
4342
4335
  } });
@@ -4352,7 +4345,9 @@ function reportedInsertId(stats, generated, owner) {
4352
4345
  affectedRows: stats.affectedRows
4353
4346
  } });
4354
4347
  }
4355
- var Node = class {};
4348
+ var Node = class {
4349
+ checkIfCanRun(_graph, _id, _context) {}
4350
+ };
4356
4351
  function executeStatement$1(ast, run) {
4357
4352
  return ast.kind === "select" || ast.returning !== void 0 ? run.query(ast) : run.execute(ast);
4358
4353
  }
@@ -4381,6 +4376,74 @@ var CrossJoin = class extends Node {
4381
4376
  }]);
4382
4377
  }
4383
4378
  };
4379
+ function storageOf(source) {
4380
+ return {
4381
+ namespaceId: blindCast(source.namespaceId),
4382
+ tableName: source.name
4383
+ };
4384
+ }
4385
+ function tableKey(table) {
4386
+ return JSON.stringify([table.namespaceId, table.tableName]);
4387
+ }
4388
+ function changedBy(contract, write, table) {
4389
+ if (write === "insert") return [table];
4390
+ return cachedFor(contract, [
4391
+ "changedBy",
4392
+ write,
4393
+ table.namespaceId,
4394
+ table.tableName
4395
+ ], () => {
4396
+ const changed = /* @__PURE__ */ new Map([[tableKey(table), table]]);
4397
+ const visited = /* @__PURE__ */ new Set([stepKey({
4398
+ table,
4399
+ kind: write
4400
+ })]);
4401
+ const pending = [{
4402
+ table,
4403
+ kind: write
4404
+ }];
4405
+ for (let step = pending.shift(); step !== void 0; step = pending.shift()) for (const reference of referencesTo(contract, step.table)) {
4406
+ const next = nextStep(step.kind, reference);
4407
+ if (next !== void 0 && !visited.has(stepKey(next))) {
4408
+ visited.add(stepKey(next));
4409
+ changed.set(tableKey(next.table), next.table);
4410
+ pending.push(next);
4411
+ }
4412
+ }
4413
+ return Object.freeze([...changed.values()]);
4414
+ });
4415
+ }
4416
+ function referencesTo(contract, target) {
4417
+ 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) => ({
4418
+ table: {
4419
+ namespaceId,
4420
+ tableName
4421
+ },
4422
+ onDelete: foreignKey.onDelete,
4423
+ onUpdate: foreignKey.onUpdate
4424
+ }))));
4425
+ }
4426
+ function nextStep(kind, reference) {
4427
+ switch (kind === "delete" ? reference.onDelete : reference.onUpdate) {
4428
+ case "cascade": return {
4429
+ table: reference.table,
4430
+ kind
4431
+ };
4432
+ case "setNull":
4433
+ case "setDefault": return {
4434
+ table: reference.table,
4435
+ kind: "update"
4436
+ };
4437
+ default: return;
4438
+ }
4439
+ }
4440
+ function stepKey(step) {
4441
+ return JSON.stringify([
4442
+ step.kind,
4443
+ step.table.namespaceId,
4444
+ step.table.tableName
4445
+ ]);
4446
+ }
4384
4447
  var Edge = class {
4385
4448
  from;
4386
4449
  constructor(from) {
@@ -4409,13 +4472,26 @@ const filteredSlots = {
4409
4472
  state: "list",
4410
4473
  requires: "list"
4411
4474
  };
4475
+ const linkedSlots = {
4476
+ filter: "list",
4477
+ link: "list",
4478
+ state: "list",
4479
+ requires: "list"
4480
+ };
4412
4481
  function executeFiltered(ast, inputs, run) {
4413
- const { filter } = inputs;
4482
+ const filter = inputs.filter ?? [];
4483
+ const link = inputs.link ?? [];
4414
4484
  if (requirementUnmet(inputs.requires)) return rowsResult([]);
4415
- if (filter === null) return executeStatement$1(ast, run);
4416
- if (filter.some((conditions) => conditions.length === 0)) return rowsResult([]);
4417
- const where = combineWhereExprs([...ast.where === void 0 ? [] : [ast.where], ...filter.map(anyOf)]);
4418
- return executeStatement$1(ast.withWhere(where), run);
4485
+ if (filter.length === 0 && link.length === 0) return executeStatement$1(ast, run);
4486
+ if ([...filter, ...link].some((rows) => rows.length === 0)) return rowsResult([]);
4487
+ return executeStatement$1(ast.withWhere(filteredWhere(ast, filter, link)), run);
4488
+ }
4489
+ function filteredWhere(ast, filter, link) {
4490
+ return combineWhereExprs([
4491
+ ...ast.where === void 0 ? [] : [ast.where],
4492
+ ...filter.map((matches) => anyOf(matches.map(({ condition }) => condition))),
4493
+ ...link.map(anyOf)
4494
+ ]);
4419
4495
  }
4420
4496
  /** Any of the conditions: an `IN` list when each compares the same column with a parameter, else an `OR`. */
4421
4497
  function anyOf(conditions) {
@@ -4468,27 +4544,24 @@ function keyCondition(columns, sourceRow) {
4468
4544
  const [first, ...others] = conditions;
4469
4545
  return first !== void 0 && others.length === 0 ? first : AndExpr.of(conditions);
4470
4546
  }
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. */
4547
+ /** Matches each source row's row in the reading statement: the condition that selects it, and its key by target column. */
4472
4548
  var FilterData = class extends DataEdge {
4473
- changed;
4474
- constructor(from, columns, changed = {}) {
4549
+ constructor(from, columns) {
4475
4550
  super(from, columns);
4476
- this.changed = changed;
4477
4551
  Object.freeze(this);
4478
4552
  }
4479
4553
  output(sourceRow) {
4480
- return keyCondition(this.columns, {
4481
- ...sourceRow,
4482
- ...this.changed
4483
- });
4554
+ return {
4555
+ condition: keyCondition(this.columns, sourceRow),
4556
+ key: Object.fromEntries(this.columns.map(([source, target]) => [target.alias, sourceRow[source.alias]]))
4557
+ };
4484
4558
  }
4485
4559
  };
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
4560
  const KEYS_PER_STATEMENT = 500;
4488
4561
  /**
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.
4562
+ * Reads the rows a write wrote back by their keys, for a database without `RETURNING`, in no particular order, and fails when it finds fewer rows than keys, so the transaction rolls back. It reads at most 500 keys per statement.
4490
4563
  *
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.
4564
+ * A `Find` with a `FilterData` edge reads the same rows, but it neither checks that every key was found nor splits the keys across statements.
4492
4565
  */
4493
4566
  var FindByKeys = class FindByKeys extends StatementNode {
4494
4567
  slots = {
@@ -4534,97 +4607,31 @@ var FindByKeys = class FindByKeys extends StatementNode {
4534
4607
  #statementFor(keys) {
4535
4608
  const conditions = keys.map((key) => keyCondition(this.keyColumns, key));
4536
4609
  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
- }))))]);
4610
+ return this.ast.withWhere(combineWhereExprs([...existing, anyOf(conditions)]));
4542
4611
  }
4543
4612
  withReturning(columns) {
4544
4613
  return new FindByKeys(this.ast.withProjection(withColumns(this.returns, columns)), this.keyColumns, this.owner);
4545
4614
  }
4546
4615
  };
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);
4616
+ var Delete = class Delete extends StatementNode {
4617
+ slots = linkedSlots;
4618
+ ast;
4619
+ constructor(ast) {
4620
+ super();
4621
+ this.ast = ast;
4612
4622
  Object.freeze(this);
4613
4623
  }
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
- })]));
4624
+ get statements() {
4625
+ return [this.ast];
4619
4626
  }
4620
- };
4621
- var Rows = class extends DataEdge {
4622
- constructor(from, columns) {
4623
- super(from, columns);
4624
- Object.freeze(this);
4627
+ get returns() {
4628
+ return this.ast.returning ?? [];
4625
4629
  }
4626
- output(sourceRow) {
4627
- return Object.fromEntries(this.columns.map(([source]) => [source.alias, sourceRow[source.alias]]));
4630
+ execute(inputs, run) {
4631
+ return executeFiltered(this.ast, inputs, run);
4632
+ }
4633
+ withReturning(columns) {
4634
+ return new Delete(this.ast.withReturning(withColumns(this.returns, columns)));
4628
4635
  }
4629
4636
  };
4630
4637
  var StateEdge = class extends Edge {
@@ -4648,147 +4655,244 @@ var State = class extends Node {
4648
4655
  return rowsResult([]);
4649
4656
  }
4650
4657
  };
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);
4658
+ function stateEdgeOf(edges, table) {
4659
+ return edges.find((edge) => edge instanceof StateEdge && edge.table.tableName === table.name && edge.table.namespaceId === table.namespaceId);
4660
+ }
4661
+ function keyEdgeFromFind(graph, contract, table, inputs) {
4662
+ const [edge, ...others] = [inputs["filter"] ?? []].flat();
4663
+ if (!(edge instanceof FilterData) || others.length > 0) return;
4664
+ const find = graph.nodeAt(edge.from);
4665
+ return find instanceof Find && readsByKey(contract, table, edge.columns) ? {
4666
+ id: edge.from,
4667
+ find
4668
+ } : void 0;
4669
+ }
4670
+ function readsTableAsFound(graph, inputs, { id, find }, table) {
4671
+ const read = oneTableReadOf(find.ast);
4672
+ const own = stateEdgeOf([inputs["state"] ?? []].flat(), table);
4673
+ const found = stateEdgeOf([graph.inputsOf(id)["state"] ?? []].flat(), table);
4674
+ return read !== void 0 && sameTable(read, table) && own !== void 0 && own.from === found?.from;
4675
+ }
4676
+ function foldsIntoCondition(graph, { id, find }, where) {
4677
+ const { filter, requires } = graph.inputsOf(id);
4678
+ return find.ast.where === where && rowsOfConditionReadOf(find.ast) !== void 0 && [filter ?? [], requires ?? []].flat().length === 0;
4679
+ }
4680
+ function oneTableReadOf(ast) {
4681
+ const { from } = ast;
4682
+ return from?.kind === "table-source" && ast.joins === void 0 && ast.projection.every((item) => item.expr.kind === "column-ref") ? from : void 0;
4683
+ }
4684
+ function conditionOnlyReadOf(ast) {
4685
+ return ast.orderBy === void 0 ? rowsOfConditionReadOf(ast) : void 0;
4686
+ }
4687
+ function rowsOfConditionReadOf(ast) {
4688
+ const from = oneTableReadOf(ast);
4689
+ return [
4690
+ ast.distinct,
4691
+ ast.distinctOn,
4692
+ ast.groupBy,
4693
+ ast.having,
4694
+ ast.limit,
4695
+ ast.offset,
4696
+ ast.locking
4697
+ ].every((clause) => clause === void 0) ? from : void 0;
4698
+ }
4699
+ function sameTable(a, b) {
4700
+ return a.name === b.name && a.namespaceId === b.namespaceId;
4701
+ }
4702
+ function readsByKey(contract, table, columns) {
4703
+ const read = new Set(columns.flatMap(([source, target]) => source.alias === target.alias && source.expr.kind === "column-ref" && target.expr.kind === "column-ref" && source.expr.column === target.expr.column ? [target.expr.column] : []));
4704
+ if (read.size !== columns.length) return false;
4705
+ const { namespaceId, tableName } = storageOf(table);
4706
+ return resolveUniqueKeyColumnSets(contract, namespaceId, tableName).some((key) => key.every((column) => read.has(column)));
4707
+ }
4708
+ /**
4709
+ * `deleteAll()` returning rows reads the rows before deleting them, because on a database without `RETURNING` they cannot be read afterwards.
4710
+ *
4711
+ * With `RETURNING` the delete reports the rows it removed, so it takes the place of that read and the call is a single statement.
4712
+ */
4713
+ const deleteRule = (graph, node, inputs) => {
4714
+ if (!(node instanceof Delete) || node.returns.length > 0 || [inputs["filter"] ?? [], inputs["link"] ?? []].flat().length > 0) return;
4715
+ const { table, where } = node.ast;
4716
+ const read = findOfSameCondition(graph, inputs, table, where);
4717
+ if (read === void 0 || graph.readersOf(read.id).length > 0 || !readsTableAsFound(graph, inputs, read, table)) return;
4718
+ return {
4719
+ node: node.withReturning(read.find.returns),
4720
+ inputs,
4721
+ standsFor: read.id
4722
+ };
4723
+ };
4724
+ function findOfSameCondition(graph, inputs, table, where) {
4725
+ const state = stateEdgeOf([inputs["state"] ?? []].flat(), table);
4726
+ if (state === void 0) return;
4727
+ return graph.readersOf(state.from).flatMap(({ reader }) => {
4728
+ const find = graph.nodeAt(reader);
4729
+ return find instanceof Find && foldsIntoCondition(graph, {
4730
+ id: reader,
4731
+ find
4732
+ }, where) ? [{
4733
+ id: reader,
4734
+ find
4735
+ }] : [];
4736
+ }).at(-1);
4737
+ }
4738
+ function givesOwnValues(context, returns) {
4739
+ return returns.length > 0 && !hasContractCapability(context.contract, "returning");
4740
+ }
4741
+ function checkOwnValues(graph, id, context, asts, returns, owner) {
4742
+ if (!givesOwnValues(context, returns)) return;
4743
+ const [first] = asts;
4744
+ if (first === void 0) return;
4745
+ const { namespaceId, tableName } = storageOf(first.table);
4746
+ const method = `${owner.operation}()`;
4747
+ if (asts.some((ast) => ast.onConflict?.action.kind === "do-nothing")) throw ormError("ORM.CAPABILITY_MISSING", `${method} with onConflict "skip" on model "${owner.modelName}" requires contract capability "returning": without it the rows are read back by key, which finds a skipped row's existing match. Use createAndCount() to skip conflicting rows.`, { meta: {
4748
+ capability: "returning",
4749
+ action: method
4750
+ } });
4751
+ rowIdentity(context.contract, namespaceId, tableName, owner.modelName, method);
4752
+ const given = [graph.inputsOf(id)["payload"] ?? []].flat().flatMap((edge) => edge instanceof DataEdge ? edge.columns.map(([, target]) => target) : []);
4753
+ for (const ast of asts) refuseUpsertOfColumnsReadBack(ast, returns, owner);
4754
+ generatedKeyColumn(insertedRowsOf(context, first.table, asts, returns, owner, given));
4755
+ }
4756
+ function refuseUpsertOfColumnsReadBack(ast, returns, owner) {
4757
+ const action = ast.onConflict?.action;
4758
+ if (action?.kind !== "do-update-set") return;
4759
+ const method = `${owner.operation}()`;
4760
+ const refused = (problem) => ormError("ORM.CAPABILITY_MISSING", `${method} on model "${owner.modelName}" ${problem}; without capability "returning" the row is read back by the create's values for the conflict columns.`, { meta: {
4761
+ capability: "returning",
4762
+ action: method
4763
+ } });
4764
+ const read = returns.map((column) => column.alias);
4765
+ const updated = read.filter((column) => {
4766
+ const value = action.set[column];
4767
+ return value !== void 0 && !(value.kind === "column-ref" && value.table === "excluded" && value.column === column);
4768
+ });
4769
+ if (updated.length > 0) throw refused(`updates conflict column "${updated.join("\", \"")}"`);
4770
+ const absent = read.filter((column) => ast.rows.some((row) => row[column]?.kind !== "param-ref"));
4771
+ if (absent.length > 0) throw refused(`gives conflict column "${absent.join("\", \"")}" no create value`);
4772
+ }
4773
+ function insertGivingOwnValues(asts, returns, owner, run) {
4774
+ const [first] = asts;
4775
+ const generated = first === void 0 ? void 0 : generatedKey(insertedRowsOf(run.context, first.table, asts, returns, owner, []));
4776
+ const generator = async function* () {
4777
+ for (const ast of asts) {
4778
+ const stats = await run.execute(ast.withReturning(void 0));
4779
+ const generatedValues = generated === void 0 ? {} : { [generated.column]: await generated.decode(reportedInsertId(stats, generated, owner)) };
4780
+ for (const row of ast.rows) yield columnsOf(returns, {
4781
+ ...valuesOf(row),
4782
+ ...generatedValues
4783
+ });
4677
4784
  }
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));
4785
+ };
4786
+ return new AsyncIterableResult(generator());
4787
+ }
4788
+ function insertedRowsOf(context, table, asts, returns, owner, given) {
4789
+ const givenValues = Object.fromEntries(given.map((column) => [column.alias, true]));
4790
+ return {
4791
+ context,
4792
+ ...storageOf(table),
4793
+ modelName: owner.modelName,
4794
+ method: `${owner.operation}()`,
4795
+ rows: asts.flatMap((ast) => ast.rows.map((row) => ({
4796
+ ...valuesOf(row),
4797
+ ...givenValues
4798
+ }))),
4799
+ columns: returns.map((column) => column.alias)
4800
+ };
4801
+ }
4802
+ function columnsOf(returns, values) {
4803
+ return Object.fromEntries(returns.map((column) => [column.alias, values[column.alias]]));
4804
+ }
4805
+ function valuesOf(row) {
4806
+ return Object.fromEntries(Object.entries(row).flatMap(([column, value]) => value.kind === "param-ref" ? [[column, value.value]] : []));
4807
+ }
4808
+ var Update = class Update extends StatementNode {
4809
+ slots = {
4810
+ filter: "list",
4811
+ link: "list",
4812
+ payload: "list",
4813
+ state: "list",
4814
+ requires: "list"
4815
+ };
4816
+ ast;
4817
+ owner;
4818
+ constructor(ast, owner) {
4819
+ super();
4820
+ this.ast = ast;
4821
+ this.owner = owner;
4822
+ Object.freeze(this);
4691
4823
  }
4692
- addRequiresEdge(from, to) {
4693
- this.#connect(to, "requires", new Requires(from));
4824
+ get statements() {
4825
+ return [this.ast];
4694
4826
  }
4695
- sameState(a, b, table) {
4696
- const stateA = this.#stateEdgeOf(a, table);
4697
- return stateA !== void 0 && stateA.from === this.#stateEdgeOf(b, table)?.from;
4827
+ get returns() {
4828
+ return this.ast.returning ?? [];
4698
4829
  }
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] ?? [];
4830
+ execute(inputs, run) {
4831
+ if (inputs.payload === null) return this.#run(this.ast, inputs, run);
4832
+ if (requirementUnmet(inputs.requires) || inputs.payload.some((records) => records.length === 0)) return rowsResult([]);
4833
+ const payload = Object.assign({}, ...inputs.payload.map(([record]) => record));
4834
+ return this.#run(this.ast.withSet({
4835
+ ...this.ast.set,
4836
+ ...payload
4837
+ }), inputs, run);
4723
4838
  }
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;
4839
+ checkIfCanRun(graph, id, context) {
4840
+ if (hasContractCapability(context.contract, "returning")) return;
4841
+ const action = `${this.owner.operation}()`;
4842
+ if (this.returns.length > 0 && [graph.inputsOf(id)["filter"] ?? []].flat().length === 0) {
4843
+ const { namespaceId, tableName } = storageOf(this.ast.table);
4844
+ rowIdentity(context.contract, namespaceId, tableName, this.owner.modelName, action);
4845
+ }
4846
+ const read = new Set(graph.columnsReadFrom(id).map((column) => column.alias));
4847
+ const [column] = Object.entries(this.ast.set).filter(([name, value]) => read.has(name) && value.kind !== "param-ref").map(([name]) => name);
4848
+ if (column === void 0) return;
4849
+ throw ormError("ORM.CAPABILITY_MISSING", `${action} on model "${this.owner.modelName}" cannot read back the rows it updates: it sets key column "${column}" by an expression, and without capability "returning" the database does not report the value it wrote.`, { meta: {
4850
+ capability: "returning",
4851
+ action
4852
+ } });
4731
4853
  }
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
4854
+ withReturning(columns) {
4855
+ return new Update(this.ast.withReturning(withColumns(this.returns, columns)), this.owner);
4856
+ }
4857
+ #run(ast, inputs, run) {
4858
+ if (!givesOwnValues(run.context, this.returns)) return executeFiltered(ast, inputs, run);
4859
+ const filter = inputs.filter ?? [];
4860
+ const link = inputs.link ?? [];
4861
+ if (requirementUnmet(inputs.requires) || [...filter, ...link].some((matches) => matches.length === 0)) return rowsResult([]);
4862
+ const statement = ast.withWhere(filteredWhere(ast, filter, link)).withReturning(void 0);
4863
+ const set = valuesOf(ast.set);
4864
+ const keys = filter.flat().map(({ key }) => key);
4865
+ const { returns } = this;
4866
+ const generator = async function* () {
4867
+ await run.execute(statement);
4868
+ for (const key of keys) yield columnsOf(returns, {
4869
+ ...key,
4870
+ ...set
4871
+ });
4737
4872
  };
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
- }));
4873
+ return new AsyncIterableResult(generator());
4762
4874
  }
4763
4875
  };
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
4876
+ /**
4877
+ * `updateAll()` and `deleteAll()` returning rows first find the rows matching the caller's condition and then limit the write to their keys, so that on a database without `RETURNING` the write changes exactly the rows the call reports.
4878
+ *
4879
+ * With `RETURNING` the write reports the rows it changed itself, so the keys are not needed: the write runs on the caller's condition alone.
4880
+ */
4881
+ function foldRule(contract) {
4882
+ return (graph, node, inputs) => {
4883
+ if (!(node instanceof Update || node instanceof Delete)) return;
4884
+ const { table, where } = node.ast;
4885
+ const read = keyEdgeFromFind(graph, contract, table, inputs);
4886
+ if (read === void 0 || !foldsIntoCondition(graph, read, where) || !readsTableAsFound(graph, inputs, read, table)) return;
4887
+ return {
4888
+ node,
4889
+ inputs: {
4890
+ ...inputs,
4891
+ filter: []
4892
+ },
4893
+ standsFor: void 0
4789
4894
  };
4790
- case "select": return;
4791
- }
4895
+ };
4792
4896
  }
4793
4897
  function assertOneValuePerColumn(values, { relation, junction }) {
4794
4898
  const seen = /* @__PURE__ */ new Map();
@@ -4807,31 +4911,48 @@ var Insert = class Insert extends StatementNode {
4807
4911
  state: "list",
4808
4912
  requires: "list"
4809
4913
  };
4810
- ast;
4914
+ asts;
4915
+ owner;
4811
4916
  junction;
4812
- constructor(ast, junction) {
4917
+ constructor(asts, owner, junction) {
4813
4918
  super();
4814
- this.ast = ast;
4919
+ this.asts = Object.freeze([...asts]);
4920
+ this.owner = owner;
4815
4921
  this.junction = junction;
4816
4922
  Object.freeze(this);
4817
4923
  }
4818
4924
  get statements() {
4819
- return [this.ast];
4925
+ return this.asts;
4820
4926
  }
4821
4927
  get returns() {
4822
- return this.ast.returning ?? [];
4928
+ return this.asts[0]?.returning ?? [];
4823
4929
  }
4824
4930
  execute(inputs, run) {
4825
4931
  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);
4932
+ if (inputs.payload?.some((records) => records.length === 0)) return rowsResult([]);
4933
+ const payload = inputs.payload === null ? void 0 : payloadOf(inputs.payload, this.junction);
4934
+ const asts = payload === void 0 ? this.asts : this.asts.map((ast) => withPayload(ast, payload));
4935
+ const [only, ...others] = asts;
4936
+ if (givesOwnValues(run.context, this.returns)) return insertGivingOwnValues(asts, this.returns, this.owner, run);
4937
+ if (only !== void 0 && others.length === 0) return executeStatement$1(only, run);
4938
+ if (this.returns.length === 0) return sumOfCounts(asts, run);
4939
+ const generator = async function* () {
4940
+ for (const ast of asts) yield* run.query(ast);
4941
+ };
4942
+ return new AsyncIterableResult(generator());
4943
+ }
4944
+ checkIfCanRun(graph, id, context) {
4945
+ checkOwnValues(graph, id, context, this.asts, this.returns, this.owner);
4829
4946
  }
4830
4947
  withReturning(columns) {
4831
- return new Insert(this.ast.withReturning(withColumns(this.returns, columns)), this.junction);
4948
+ return new Insert(this.asts.map((ast) => ast.withReturning(withColumns(ast.returning ?? [], columns))), this.owner, this.junction);
4832
4949
  }
4833
4950
  };
4834
- /** The values the `PayloadData` edges give every row, each edge's first record. */
4951
+ async function sumOfCounts(asts, run) {
4952
+ let affectedRows = 0;
4953
+ for (const ast of asts) affectedRows += (await run.execute(ast)).affectedRows;
4954
+ return { affectedRows };
4955
+ }
4835
4956
  function payloadOf(payload, junction) {
4836
4957
  const records = payload.map(([record]) => record ?? {});
4837
4958
  if (junction !== void 0) assertOneValuePerColumn(records.flatMap((record) => Object.entries(record).map(([column, param]) => [column, param.value])), junction);
@@ -4843,160 +4964,350 @@ function withPayload(ast, payload) {
4843
4964
  ...payload
4844
4965
  })));
4845
4966
  }
4967
+ var Rows = class extends DataEdge {
4968
+ constructor(from, columns) {
4969
+ super(from, columns);
4970
+ Object.freeze(this);
4971
+ }
4972
+ output(sourceRow) {
4973
+ return Object.fromEntries(this.columns.map(([source]) => [source.alias, sourceRow[source.alias]]));
4974
+ }
4975
+ };
4846
4976
  /**
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.
4977
+ * Writes that return rows (`create()`, `createAll()`, `update()`, `updateAll()`, `upsert()`) read the rows back after writing them, because on a database without `RETURNING` a write does not report what it wrote.
4978
+ *
4979
+ * With `RETURNING` the write reports those rows itself, so the read-back is not needed. A read-back that loads includes stays, since `RETURNING` cannot load related rows.
4848
4980
  */
4849
- var InsertReportingKeys = class extends StatementNode {
4850
- slots = {
4851
- payload: "list",
4852
- state: "list",
4853
- requires: "list"
4981
+ function readBackRule(contract) {
4982
+ return (graph, node, inputs) => {
4983
+ if (!(node instanceof Find || node instanceof FindByKeys)) return;
4984
+ const table = node.ast.where === void 0 ? conditionOnlyReadOf(node.ast) : void 0;
4985
+ const { state, ...data } = inputs;
4986
+ const [edge, ...others] = Object.values(data).flatMap((slot) => [slot ?? []].flat());
4987
+ if (table === void 0 || others.length > 0 || !(edge instanceof FilterData || edge instanceof Rows) || !readsStateWrittenBy(graph, [state ?? []].flat(), table, edge.from)) return;
4988
+ const write = graph.nodeAt(edge.from);
4989
+ if (!isWriteTo(write, table) || !readsByKey(contract, table, edge.columns)) return;
4990
+ graph.replace(edge.from, write.withReturning(node.returns));
4991
+ return edge.from;
4854
4992
  };
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;
4993
+ }
4994
+ function readsStateWrittenBy(graph, state, table, write) {
4995
+ const read = stateEdgeOf(state, table);
4996
+ return read !== void 0 && [graph.inputsOf(read.from)["write"] ?? []].flat().some((edge) => edge.from === write);
4997
+ }
4998
+ function isWriteTo(node, table) {
4999
+ return (node instanceof Insert || node instanceof Update || node instanceof Delete) && node.statements.every((ast) => ast.kind !== "select" && sameTable(ast.table, table));
5000
+ }
5001
+ function rulesFor(contract) {
5002
+ return hasContractCapability(contract, "returning") ? [
5003
+ foldRule(contract),
5004
+ deleteRule,
5005
+ readBackRule(contract)
5006
+ ] : [];
5007
+ }
5008
+ var Graph = class {
5009
+ #contract;
5010
+ #rules;
5011
+ #nodes = [];
5012
+ #inputs = [];
5013
+ #readers = [];
5014
+ #states = /* @__PURE__ */ new Map();
5015
+ #result = void 0;
5016
+ constructor(contract) {
5017
+ this.#contract = contract;
5018
+ this.#rules = rulesFor(contract);
4869
5019
  }
4870
- get returns() {
4871
- return [];
5020
+ get result() {
5021
+ return this.#result;
4872
5022
  }
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;
5023
+ setResult(node) {
5024
+ this.#result = this.#present(node);
5025
+ }
5026
+ add(node, inputs) {
5027
+ for (const slot of Object.values(inputs)) for (const edge of [slot ?? []].flat()) this.#present(edge.from);
5028
+ let current = {
5029
+ node,
5030
+ inputs,
5031
+ standsFor: void 0
4896
5032
  };
4897
- return new AsyncIterableResult(generator());
5033
+ const replaced = [];
5034
+ let standing = this.#applyRules(current);
5035
+ while (typeof standing !== "number" && standing !== void 0) {
5036
+ current = standing;
5037
+ if (standing.standsFor !== void 0) replaced.push(standing.standsFor);
5038
+ standing = this.#applyRules(current);
5039
+ }
5040
+ const id = standing ?? this.#addWithInputs(current.node, current.inputs);
5041
+ for (const node of replaced) this.#takeOver(node, id);
5042
+ return id;
4898
5043
  }
4899
- withReturning(_columns) {
4900
- return this;
5044
+ #takeOver(replaced, by) {
5045
+ if (this.#readersAt(replaced).length > 0) throw new InternalError(`node ${replaced} is replaced while a node still reads it`);
5046
+ if (this.#result === replaced) this.#result = by;
5047
+ this.#removeAt(replaced);
4901
5048
  }
4902
- };
4903
- var Delete = class Delete extends StatementNode {
4904
- slots = filteredSlots;
4905
- ast;
4906
- constructor(ast) {
4907
- super();
4908
- this.ast = ast;
4909
- Object.freeze(this);
5049
+ #applyRules({ node, inputs }) {
5050
+ for (const rule of this.#rules) {
5051
+ const standing = rule(this, node, inputs);
5052
+ if (standing !== void 0) return standing;
5053
+ }
4910
5054
  }
4911
- get statements() {
4912
- return [this.ast];
5055
+ #addWithInputs(node, inputs) {
5056
+ const id = this.#addNode(node);
5057
+ for (const [slot, edges] of Object.entries(inputs)) for (const edge of [edges ?? []].flat()) this.#addEdge(id, slot, edge);
5058
+ return id;
4913
5059
  }
4914
- get returns() {
4915
- return this.ast.returning ?? [];
5060
+ stateEdgesFor(node, links = []) {
5061
+ return uniqueTables([...tablesReadBy(node.statements), ...links.map(({ junction }) => storageOf(junction))]).map((table) => new StateEdge(this.#stateOf(table), table));
4916
5062
  }
4917
- execute(inputs, run) {
4918
- return executeFiltered(this.ast, inputs, run);
5063
+ nodeAt(id) {
5064
+ return this.#nodes[this.#present(id)];
4919
5065
  }
4920
- withReturning(columns) {
4921
- return new Delete(this.ast.withReturning(withColumns(this.returns, columns)));
5066
+ columnsReadFrom(id) {
5067
+ return this.#readersAt(this.#present(id)).flatMap(({ edge }) => edge instanceof DataEdge ? edge.columns.map(([source]) => source) : []);
4922
5068
  }
4923
- };
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) {
4933
- super();
4934
- this.asts = Object.freeze([...asts]);
4935
- this.junction = junction;
4936
- Object.freeze(this);
5069
+ replace(id, next) {
5070
+ this.#nodes[this.#present(id)] = next;
4937
5071
  }
4938
- get statements() {
4939
- return this.asts;
5072
+ removeUnreadFinds() {
5073
+ const unread = this.nodes().filter(([id, node]) => (node instanceof Find || node instanceof FindByKeys) && id !== this.#result && this.#readersAt(id).length === 0);
5074
+ for (const [id] of unread) this.#removeAt(id);
5075
+ if (unread.length > 0) this.removeUnreadFinds();
4940
5076
  }
4941
- get returns() {
4942
- return this.asts[0]?.returning ?? [];
5077
+ nodes() {
5078
+ return this.#nodes.flatMap((node, position) => node === void 0 ? [] : [[idAt(position), node]]);
4943
5079
  }
4944
- execute(inputs, run) {
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);
4950
- const generator = async function* () {
4951
- for (const ast of asts) yield* run.query(ast);
5080
+ entries() {
5081
+ return this.nodes().map(([id, node]) => ({
5082
+ id,
5083
+ node,
5084
+ inputs: this.#inputsAt(id)
5085
+ }));
5086
+ }
5087
+ inputsOf(id) {
5088
+ return this.#inputsAt(this.#present(id));
5089
+ }
5090
+ readersOf(id) {
5091
+ return this.#readersAt(this.#present(id));
5092
+ }
5093
+ #present(id) {
5094
+ if (this.#nodes[id] === void 0) throw new InternalError(`node ${id} is not in the graph`);
5095
+ return id;
5096
+ }
5097
+ #inputsAt(id) {
5098
+ return this.#inputs[id] ?? {};
5099
+ }
5100
+ #readersAt(id) {
5101
+ return this.#readers[id] ?? [];
5102
+ }
5103
+ #removeAt(id) {
5104
+ for (const edge of edgesIn(this.#inputsAt(id))) this.#readers[edge.from] = this.#readersAt(edge.from).filter((entry) => entry.edge !== edge);
5105
+ this.#nodes[id] = void 0;
5106
+ this.#inputs[id] = {};
5107
+ this.#readers[id] = [];
5108
+ }
5109
+ #addNode(node) {
5110
+ const id = this.#append(node);
5111
+ if (!(node instanceof StatementNode)) return id;
5112
+ for (const table of this.#tablesWrittenBy(node.statements)) {
5113
+ const state = this.#append(new State(table));
5114
+ this.#connect(state, "write", new StateEdge(id, table));
5115
+ this.#states.set(tableKey(table), state);
5116
+ }
5117
+ return id;
5118
+ }
5119
+ #append(node) {
5120
+ const id = idAt(this.#nodes.length);
5121
+ this.#nodes.push(node);
5122
+ this.#inputs.push(Object.fromEntries(Object.entries(node.slots).filter(([, kind]) => kind === "list").map(([name]) => [name, []])));
5123
+ this.#readers.push([]);
5124
+ return id;
5125
+ }
5126
+ #addEdge(to, slot, edge) {
5127
+ if (edge instanceof DataEdge) this.#read(edge.from, edge.columns);
5128
+ this.#connect(to, slot, edge);
5129
+ }
5130
+ #connect(to, slot, edge) {
5131
+ const current = this.#inputsAt(to)[slot];
5132
+ this.#inputs[to] = {
5133
+ ...this.#inputsAt(to),
5134
+ [slot]: Array.isArray(current) ? [...current, edge] : edge
4952
5135
  };
4953
- return new AsyncIterableResult(generator());
5136
+ this.#readers[edge.from]?.push({
5137
+ reader: to,
5138
+ edge
5139
+ });
4954
5140
  }
4955
- withReturning(columns) {
4956
- return new InsertChunked(this.asts.map((ast) => ast.withReturning(withColumns(ast.returning ?? [], columns))), this.junction);
5141
+ #read(from, columns) {
5142
+ const source = this.#nodes[from];
5143
+ if (source instanceof StatementNode) this.#nodes[from] = source.withReturning(columns.map(([column]) => column));
5144
+ }
5145
+ #stateOf(table) {
5146
+ const current = this.#states.get(tableKey(table));
5147
+ if (current !== void 0) return current;
5148
+ const initial = this.#append(new State(table));
5149
+ this.#states.set(tableKey(table), initial);
5150
+ return initial;
4957
5151
  }
4958
- async #sumOfCounts(asts, run) {
4959
- let affectedRows = 0;
4960
- for (const ast of asts) affectedRows += (await run.execute(ast)).affectedRows;
4961
- return { affectedRows };
5152
+ #tablesWrittenBy(statements) {
5153
+ return uniqueTables(statements.flatMap((ast) => {
5154
+ const write = writeOf(ast);
5155
+ return write === void 0 ? [] : changedBy(this.#contract, write.kind, storageOf(write.target));
5156
+ }));
4962
5157
  }
4963
5158
  };
4964
- var Update = class Update extends StatementNode {
4965
- slots = {
4966
- filter: "list",
4967
- payload: "list",
4968
- state: "list",
4969
- requires: "list"
4970
- };
4971
- ast;
4972
- constructor(ast) {
4973
- super();
4974
- this.ast = ast;
4975
- Object.freeze(this);
5159
+ function idAt(position) {
5160
+ return blindCast(position);
5161
+ }
5162
+ function edgesIn(slots) {
5163
+ return Object.values(slots).flat();
5164
+ }
5165
+ function tablesReadBy(statements) {
5166
+ return uniqueTables(statements.flatMap((ast) => collectTableSources(ast).map(storageOf)));
5167
+ }
5168
+ function uniqueTables(tables) {
5169
+ return [...new Map(tables.map((table) => [tableKey(table), table])).values()];
5170
+ }
5171
+ function writeOf(ast) {
5172
+ switch (ast.kind) {
5173
+ case "insert": return {
5174
+ kind: ast.onConflict?.action.kind === "do-update-set" ? "update" : "insert",
5175
+ target: ast.table
5176
+ };
5177
+ case "update":
5178
+ case "delete": return {
5179
+ kind: ast.kind,
5180
+ target: ast.table
5181
+ };
5182
+ case "select": return;
4976
5183
  }
4977
- get statements() {
4978
- return [this.ast];
5184
+ }
5185
+ var JunctionFilterData = class extends DataEdge {
5186
+ junction;
5187
+ targets;
5188
+ constructor(from, columns, junction, targets) {
5189
+ super(from, columns);
5190
+ this.junction = junction;
5191
+ this.targets = Object.freeze([...targets]);
5192
+ Object.freeze(this);
4979
5193
  }
4980
- get returns() {
4981
- return this.ast.returning ?? [];
5194
+ output(sourceRow) {
5195
+ const keys = this.targets.map(([, target]) => target.expr);
5196
+ const [only, ...others] = keys;
5197
+ return BinaryExpr.in(only !== void 0 && others.length === 0 ? only : ListExpression.of(keys), SubqueryExpr.of(SelectAst.from(this.junction).withProjection(this.targets.map(([child]) => child)).withWhere(keyCondition(this.columns, sourceRow))));
4982
5198
  }
4983
- execute(inputs, run) {
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([]);
4986
- const payload = Object.assign({}, ...inputs.payload.map(([record]) => record));
4987
- return executeFiltered(this.ast.withSet({
4988
- ...this.ast.set,
4989
- ...payload
4990
- }), inputs, run);
5199
+ };
5200
+ var PayloadData = class extends DataEdge {
5201
+ constructor(from, columns) {
5202
+ super(from, columns);
5203
+ Object.freeze(this);
4991
5204
  }
4992
- withReturning(columns) {
4993
- return new Update(this.ast.withReturning(withColumns(this.returns, columns)));
5205
+ output(sourceRow) {
5206
+ return Object.fromEntries(this.columns.map(([source, target]) => [target.alias, ParamRef.of(sourceRow[source.alias], {
5207
+ name: target.alias,
5208
+ ...ifDefined("codec", target.codec)
5209
+ })]));
4994
5210
  }
4995
5211
  };
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;
5212
+ const allColumns = {
5213
+ selectedFields: void 0,
5214
+ includes: [],
5215
+ variantValue: void 0
5216
+ };
5217
+ function addInsert({ graph, context }, table, rows, { conflict, keys, junction, requires, owner }) {
5218
+ const { contract } = context;
5219
+ const inserted = new Insert((supportsDefaultInInsert(contract) ? [rows] : groupRowsByColumnSignature(rows)).map((group) => insertAst(contract, table, group, conflict)), owner, junction);
5220
+ return graph.add(inserted, {
5221
+ payload: keys.map(({ from, columns }) => new PayloadData(from, columns)),
5222
+ state: graph.stateEdgesFor(inserted),
5223
+ requires: [...requires]
5224
+ });
5225
+ }
5226
+ function insertRows(b, model, rows, { conflict, keys, requires, owner, returns, shape, afterWrite }) {
5227
+ const inserted = addInsert(b, model.tables.root, rows, {
5228
+ conflict,
5229
+ keys,
5230
+ junction: void 0,
5231
+ requires,
5232
+ owner
5233
+ });
5234
+ afterWrite?.(inserted);
5235
+ return readBackRows(b, model, inserted, {
5236
+ returns,
5237
+ shape,
5238
+ by: "keys",
5239
+ owner
5240
+ });
5241
+ }
5242
+ function updateRows(b, model, values, { where, filters, links, payloads, owner, returns, shape, afterWrite }) {
5243
+ const { graph, context } = b;
5244
+ const update = new Update(updateAst(context.contract, model.tables, values, where), owner);
5245
+ const link = links.map(linkEdge);
5246
+ const updated = graph.add(update, {
5247
+ filter: filters.map(({ from, columns }) => new FilterData(from, columns)),
5248
+ link,
5249
+ payload: payloads.map(({ from, columns }) => new PayloadData(from, columns)),
5250
+ state: graph.stateEdgesFor(update, link)
5251
+ });
5252
+ afterWrite?.(updated);
5253
+ return readBackRows(b, model, updated, {
5254
+ returns,
5255
+ shape,
5256
+ by: "filter",
5257
+ owner
5258
+ });
5259
+ }
5260
+ function deleteRows({ graph, context }, tables, { where, filters, links }) {
5261
+ const deleted = new Delete(deleteAst(context.contract, tables, where));
5262
+ const link = links.map(linkEdge);
5263
+ return graph.add(deleted, {
5264
+ filter: filters.map(({ from, columns }) => new FilterData(from, columns)),
5265
+ link,
5266
+ state: graph.stateEdgesFor(deleted, link)
5267
+ });
5268
+ }
5269
+ function linkEdge({ from, columns, junction, targets }) {
5270
+ return new JunctionFilterData(from, columns, junction, targets);
5271
+ }
5272
+ function findRows({ graph }, ast, { filter, requires }) {
5273
+ const find = new Find(ast);
5274
+ return graph.add(find, {
5275
+ filter,
5276
+ state: graph.stateEdgesFor(find),
5277
+ requires
5278
+ });
5279
+ }
5280
+ function readBack(b, model, written, keyColumns, { shape, by, owner }) {
5281
+ const { graph, context } = b;
5282
+ const { contract } = context;
5283
+ const { root, variants } = model.tables;
5284
+ const { selectedFields, includes, variantValue } = shape;
5285
+ const variantJoins = variantValue === void 0 ? variants.size > 0 : variants.has(variantValue);
5286
+ const ast = includes.length === 0 && !variantJoins ? SelectAst.from(root.tableSource(contract)).withProjection(returningProjection(contract, model.modelName, root, selectedFields)) : selectAstOf(context, model, {
5287
+ ...emptyState(model.tables),
5288
+ selectedFields,
5289
+ includes,
5290
+ variantValue
5291
+ }, "selection");
5292
+ const mappings = projectTableColumns(contract, root, keyColumns).map((column) => [column, column]);
5293
+ if (by === "filter") return findRows(b, ast, {
5294
+ filter: [new FilterData(written, mappings)],
5295
+ requires: []
5296
+ });
5297
+ const found = new FindByKeys(ast, mappings, owner);
5298
+ return graph.add(found, {
5299
+ keys: new Rows(written, mappings),
5300
+ state: graph.stateEdgesFor(found)
5301
+ });
5302
+ }
5303
+ function readBackRows(b, model, written, { returns, shape, by, owner }) {
5304
+ const { namespaceId, tableName } = model.tables.root.storage;
5305
+ const identity = resolveRowIdentityColumns(b.context.contract, namespaceId, tableName);
5306
+ return returns === "count" || identity.length === 0 ? written : readBack(b, model, written, identity, {
5307
+ shape,
5308
+ by,
5309
+ owner
5310
+ });
5000
5311
  }
5001
5312
  function selectAstOf(context, model, state, columns) {
5002
5313
  const { contract } = context;
@@ -5012,19 +5323,29 @@ function selectAstOf(context, model, state, columns) {
5012
5323
  if (state.includes.length === 0) return collectionSelectAst(contract, modelName, state);
5013
5324
  return collectionSelectWithIncludesAst(contract, context.aggregateDescriptors, modelName, state);
5014
5325
  }
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;
5326
+ function createFilteredRelationMutator(related) {
5327
+ return {
5328
+ where(input) {
5329
+ return createFilteredRelationMutator(related.where(input));
5330
+ },
5331
+ updateAll(data) {
5332
+ return {
5333
+ kind: "updateAll",
5334
+ state: related.state,
5335
+ data: { ...data }
5336
+ };
5337
+ },
5338
+ deleteAll() {
5339
+ return {
5340
+ kind: "deleteAll",
5341
+ state: related.state
5342
+ };
5343
+ }
5344
+ };
5025
5345
  }
5026
- function createRelationMutator() {
5346
+ function createRelationMutator(related) {
5027
5347
  return {
5348
+ ...createFilteredRelationMutator(related),
5028
5349
  create(data) {
5029
5350
  return {
5030
5351
  kind: "create",
@@ -5047,10 +5368,9 @@ function createRelationMutator() {
5047
5368
  };
5048
5369
  }
5049
5370
  function isRelationMutationDescriptor(value) {
5050
- if (!value || typeof value !== "object") return false;
5371
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
5051
5372
  const candidate = value;
5052
- if (candidate.kind !== "create" && candidate.kind !== "connect" && candidate.kind !== "disconnect") return false;
5053
- return true;
5373
+ return candidate.kind === "create" || candidate.kind === "connect" || candidate.kind === "disconnect" || candidate.kind === "updateAll" || candidate.kind === "deleteAll";
5054
5374
  }
5055
5375
  function isRelationMutationCallback(value) {
5056
5376
  return typeof value === "function";
@@ -5058,7 +5378,7 @@ function isRelationMutationCallback(value) {
5058
5378
  function hasThrough(relation) {
5059
5379
  return relation.through !== void 0;
5060
5380
  }
5061
- function parseMutationInput(contract, namespaceId, modelName, input) {
5381
+ function parseMutationInput(contract, namespaceId, modelName, input, relatedCollection) {
5062
5382
  const scalarData = {};
5063
5383
  const relations = resolveModelRelations(contract, namespaceId, modelName);
5064
5384
  const relationMutations = [];
@@ -5074,16 +5394,23 @@ function parseMutationInput(contract, namespaceId, modelName, input) {
5074
5394
  model: modelName,
5075
5395
  problem: "missing-callback"
5076
5396
  } });
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: {
5397
+ const result = value(createRelationMutator(relatedCollection(relation)));
5398
+ const mutations = (Array.isArray(result) ? result : [result]).map((element, index) => {
5399
+ const at = Array.isArray(result) ? index : void 0;
5400
+ if (Array.isArray(element) || !isRelationMutationDescriptor(element)) throw invalidRelationField(fieldName, modelName, Array.isArray(element), at);
5401
+ return element;
5402
+ });
5403
+ if (mutations.length > 1 && (relation.cardinality === "N:1" || relation.cardinality === "1:1")) throw ormError("ORM.RELATION_MUTATION_UNSUPPORTED", `Relation "${fieldName}" on model "${modelName}" is a to-one relation and takes one operation, not ${mutations.length}`, { meta: {
5079
5404
  relation: fieldName,
5080
5405
  model: modelName,
5081
- problem: "invalid-descriptor"
5406
+ reason: "to-one-relation",
5407
+ operations: mutations.length
5082
5408
  } });
5083
- relationMutations.push({
5409
+ if (mutations.length > 0) relationMutations.push({
5084
5410
  name: fieldName,
5085
5411
  relation,
5086
- mutation
5412
+ mutations,
5413
+ relatedCollection
5087
5414
  });
5088
5415
  }
5089
5416
  return {
@@ -5091,6 +5418,15 @@ function parseMutationInput(contract, namespaceId, modelName, input) {
5091
5418
  relationMutations
5092
5419
  };
5093
5420
  }
5421
+ function invalidRelationField(fieldName, modelName, nested, index) {
5422
+ const at = index === void 0 ? "" : ` at index ${index}`;
5423
+ return ormError("ORM.RELATION_MUTATION_INVALID", `Relation field "${fieldName}" on model "${modelName}" ${nested ? `returned a nested array${at}; return one flat array of mutations` : `returned an invalid mutation descriptor${at}`}`, { meta: {
5424
+ relation: fieldName,
5425
+ model: modelName,
5426
+ problem: nested ? "nested-array" : "invalid-descriptor",
5427
+ ...ifDefined("index", index)
5428
+ } });
5429
+ }
5094
5430
  function partitionByOwnership(relationMutations) {
5095
5431
  const parentOwned = [];
5096
5432
  const childOwned = [];
@@ -5115,9 +5451,10 @@ function partitionByOwnership(relationMutations) {
5115
5451
  junctionOwned
5116
5452
  };
5117
5453
  }
5118
- function assertJunctionPayloadWritable({ name, relation, mutation }) {
5454
+ function assertJunctionPayloadWritable({ name, relation, mutations }) {
5119
5455
  const { through } = relation;
5120
- if (mutation.kind !== "create" && mutation.kind !== "connect" || through.requiredPayloadColumns.length === 0) return;
5456
+ const mutation = mutations.find(({ kind }) => kind === "create" || kind === "connect");
5457
+ if (mutation === void 0 || through.requiredPayloadColumns.length === 0) return;
5121
5458
  const cols = through.requiredPayloadColumns.map((c) => `\`${c}\``).join(", ");
5122
5459
  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
5460
  kind: mutation.kind,
@@ -5271,55 +5608,28 @@ function withUpdateDefaults(collection, set, before) {
5271
5608
  })) values[applied.field] = applied.value;
5272
5609
  return values;
5273
5610
  }
5274
- function addCreateWithRelations(t, model, parsed, keysFromParent, requiresParentRow = false) {
5275
- for (const relationMutation of parsed.relationMutations) rejectDisconnect(relationMutation);
5611
+ function addCreateWithRelations(t, model, parsed, { keysFromParent, returns, shape, variantValue }) {
5612
+ for (const relationMutation of parsed.relationMutations) rejectUpdateOnly(relationMutation);
5276
5613
  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], {
5614
+ return insertRows(t, model, [createRowOf(t.context, model, variantValue, parsed.scalarData, void 0)], {
5285
5615
  conflict: void 0,
5286
- keys,
5287
- junction: void 0
5616
+ keys: [...keysFromParent, ...before.keys],
5617
+ requires: keysFromParent.length === 0 ? parentRowRequired(t) : [],
5618
+ owner: {
5619
+ operation: "create",
5620
+ modelName: model.modelName
5621
+ },
5622
+ returns,
5623
+ shape,
5624
+ afterWrite: (inserted) => addAfterWrite(t, model, inserted, parsed.relationMutations)
5288
5625
  });
5289
- if (requiresParentRow) requireParentRow(t, insert);
5290
- return insert;
5291
5626
  }
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()"
5627
+ function nestedCreate(t, model, parsed, keysFromParent, returns) {
5628
+ return addCreateWithRelations(t, model, parsed, {
5629
+ keysFromParent,
5630
+ returns,
5631
+ shape: allColumns,
5632
+ variantValue: void 0
5323
5633
  });
5324
5634
  }
5325
5635
  function addBeforeWrite(t, model, relationMutations) {
@@ -5330,9 +5640,10 @@ function addBeforeWrite(t, model, relationMutations) {
5330
5640
  }
5331
5641
  const keys = [];
5332
5642
  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;
5643
+ for (const relationMutation of relationMutations) rejectFilteredWriteOnToOne(relationMutation);
5644
+ for (const relationMutation of parentOwned) for (const mutation of relationMutation.mutations) {
5645
+ if (isFilteredWrite(mutation)) continue;
5646
+ if (mutation.kind === "disconnect") for (const column of localColumnsOf(t.context.contract, model, relationMutation.relation)) nullColumns[column] = null;
5336
5647
  else keys.push(addParentOwned(t, model, relationMutation, mutation));
5337
5648
  }
5338
5649
  return {
@@ -5342,16 +5653,27 @@ function addBeforeWrite(t, model, relationMutations) {
5342
5653
  }
5343
5654
  function addAfterWrite(t, model, parent, relationMutations) {
5344
5655
  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);
5656
+ for (const relationMutation of childOwned) for (const mutation of relationMutation.mutations) addChildOwned(t, model, parent, relationMutation, mutation);
5657
+ for (const relationMutation of junctionOwned) for (const mutation of relationMutation.mutations) addJunctionOwned(t, model, parent, relationMutation, mutation);
5347
5658
  }
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",
5659
+ function rejectUpdateOnly({ name, mutations }) {
5660
+ for (const { kind } of mutations) if (kind === "disconnect" || kind === "updateAll" || kind === "deleteAll") throw ormError("ORM.RELATION_MUTATION_UNSUPPORTED", `${kind}() is only supported in update() nested mutations`, { meta: {
5661
+ kind,
5351
5662
  relation: name
5352
5663
  } });
5353
5664
  }
5354
- function addParentOwned(t, model, { name, relation }, mutation) {
5665
+ function isFilteredWrite(mutation) {
5666
+ return mutation.kind === "updateAll" || mutation.kind === "deleteAll";
5667
+ }
5668
+ function rejectFilteredWriteOnToOne({ name, relation, mutations }) {
5669
+ const filtered = mutations.find(isFilteredWrite);
5670
+ if (filtered !== void 0 && (relation.cardinality === "N:1" || relation.cardinality === "1:1")) throw ormError("ORM.RELATION_MUTATION_UNSUPPORTED", `${filtered.kind}() nested mutation for relation "${name}" is only supported on to-many relations`, { meta: {
5671
+ kind: filtered.kind,
5672
+ relation: name,
5673
+ reason: "to-one-relation"
5674
+ } });
5675
+ }
5676
+ function addParentOwned(t, model, { name, relation, relatedCollection }, mutation) {
5355
5677
  const { contract } = t.context;
5356
5678
  const related = relatedModel(contract, relation);
5357
5679
  const columns = columnMappings(contract, related.tables.root, resolveRelationTargetColumns(contract, relation), model.tables.root, localColumnsOf(contract, model, relation));
@@ -5363,7 +5685,7 @@ function addParentOwned(t, model, { name, relation }, mutation) {
5363
5685
  problem: "missing-data"
5364
5686
  } });
5365
5687
  return {
5366
- from: addCreateWithRelations(t, related, parseCreateInput(t, related, row), [], true),
5688
+ from: nestedCreate(t, related, parseCreateInput(t, related, row, relatedCollection), [], "rows"),
5367
5689
  columns
5368
5690
  };
5369
5691
  }
@@ -5378,50 +5700,70 @@ function addParentOwned(t, model, { name, relation }, mutation) {
5378
5700
  columns
5379
5701
  };
5380
5702
  }
5381
- function addChildOwned(t, model, parent, { name, relation, mutation }) {
5382
- const { graph, context } = t;
5703
+ function addChildOwned(t, model, parent, { name, relation, relatedCollection }, mutation) {
5704
+ const { context } = t;
5383
5705
  const { contract } = context;
5384
5706
  const related = relatedModel(contract, relation);
5385
5707
  const targetColumns = resolveRelationTargetColumns(contract, relation);
5386
5708
  const fromParent = columnMappings(contract, model.tables.root, localColumnsOf(contract, model, relation), related.tables.root, targetColumns);
5709
+ if (isFilteredWrite(mutation)) {
5710
+ addFilteredWrite(t, model, parent, name, relation, mutation);
5711
+ return;
5712
+ }
5387
5713
  if (mutation.kind === "create") {
5388
5714
  const keys = [{
5389
5715
  from: parent,
5390
5716
  columns: fromParent
5391
5717
  }];
5392
- const rows = mutation.data.map((row) => parseCreateInput(t, related, row));
5718
+ const rows = mutation.data.map((row) => parseCreateInput(t, related, row, relatedCollection));
5393
5719
  if (rows.some((row) => row.relationMutations.length > 0)) {
5394
- for (const row of rows) addCreateWithRelations(t, related, row, keys);
5720
+ for (const row of rows) nestedCreate(t, related, row, keys, "count");
5395
5721
  return;
5396
5722
  }
5397
5723
  addChildInserts(t, related, rows.map((row) => row.scalarData), keys);
5398
5724
  return;
5399
5725
  }
5400
5726
  if (mutation.kind === "connect") {
5401
- for (const criterion of mutation.criteria) addUpdateRows(graph, context.contract, related.tables, {}, {
5727
+ for (const criterion of mutation.criteria) updateRows(t, related, {}, {
5402
5728
  where: requiredCriterion(context, related, name, "connect", criterion),
5403
5729
  filters: [],
5730
+ links: [],
5404
5731
  payloads: [{
5405
5732
  from: parent,
5406
5733
  columns: fromParent
5407
- }]
5734
+ }],
5735
+ owner: {
5736
+ operation: "update",
5737
+ modelName: related.modelName
5738
+ },
5739
+ returns: "count",
5740
+ shape: allColumns,
5741
+ afterWrite: void 0
5408
5742
  });
5409
5743
  return;
5410
5744
  }
5411
5745
  const unlink = Object.fromEntries(targetColumns.map((column) => [column, null]));
5412
5746
  const criteria = mutation.criteria ?? [];
5413
5747
  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, {
5748
+ for (const where of wheres) updateRows(t, related, unlink, {
5415
5749
  where,
5416
5750
  filters: [{
5417
5751
  from: parent,
5418
5752
  columns: fromParent
5419
5753
  }],
5420
- payloads: []
5754
+ links: [],
5755
+ payloads: [],
5756
+ owner: {
5757
+ operation: "update",
5758
+ modelName: related.modelName
5759
+ },
5760
+ returns: "count",
5761
+ shape: allColumns,
5762
+ afterWrite: void 0
5421
5763
  });
5422
5764
  }
5423
- function addJunctionOwned(t, model, parent, { name, relation, mutation }) {
5424
- const { graph, context } = t;
5765
+ function addJunctionOwned(t, model, parent, { name, relation, relatedCollection }, mutation) {
5766
+ const { context } = t;
5425
5767
  const { contract } = context;
5426
5768
  const { through } = relation;
5427
5769
  const related = relatedModel(contract, relation);
@@ -5431,9 +5773,13 @@ function addJunctionOwned(t, model, parent, { name, relation, mutation }) {
5431
5773
  });
5432
5774
  const fromParent = columnMappings(contract, model.tables.root, localColumnsOf(contract, model, relation), junction.root, through.parentColumns);
5433
5775
  const fromTarget = columnMappings(contract, related.tables.root, through.targetColumns, junction.root, through.childColumns);
5776
+ if (isFilteredWrite(mutation)) {
5777
+ addFilteredWrite(t, model, parent, name, relation, mutation);
5778
+ return;
5779
+ }
5434
5780
  const addLink = (target, conflict) => {
5435
5781
  const values = withCreateDefaults(context, through.namespaceId, through.table, {}, void 0);
5436
- addInsertRows(graph, contract, junction.root, [values], {
5782
+ addInsert(t, junction.root, [values], {
5437
5783
  conflict,
5438
5784
  keys: [{
5439
5785
  from: parent,
@@ -5445,11 +5791,16 @@ function addJunctionOwned(t, model, parent, { name, relation, mutation }) {
5445
5791
  junction: {
5446
5792
  relation: name,
5447
5793
  junction: through.table
5794
+ },
5795
+ requires: [],
5796
+ owner: {
5797
+ operation: "create",
5798
+ modelName: model.modelName
5448
5799
  }
5449
5800
  });
5450
5801
  };
5451
5802
  if (mutation.kind === "create") {
5452
- for (const row of mutation.data) addLink(addCreateWithRelations(t, related, parseCreateInput(t, related, row), [], true), void 0);
5803
+ for (const row of mutation.data) addLink(nestedCreate(t, related, parseCreateInput(t, related, row, relatedCollection), [], "rows"), void 0);
5453
5804
  return;
5454
5805
  }
5455
5806
  if (mutation.kind === "connect") {
@@ -5465,7 +5816,7 @@ function addJunctionOwned(t, model, parent, { name, relation, mutation }) {
5465
5816
  } });
5466
5817
  for (const criterion of criteria) {
5467
5818
  const target = addFindAndAssert(t, related, name, "disconnect", criterion, fromTarget);
5468
- addDeleteRows(graph, contract, junction, {
5819
+ deleteRows(t, junction, {
5469
5820
  where: void 0,
5470
5821
  filters: [{
5471
5822
  from: parent,
@@ -5473,34 +5824,89 @@ function addJunctionOwned(t, model, parent, { name, relation, mutation }) {
5473
5824
  }, {
5474
5825
  from: target,
5475
5826
  columns: fromTarget
5476
- }]
5827
+ }],
5828
+ links: []
5477
5829
  });
5478
5830
  }
5479
5831
  }
5832
+ function addFilteredWrite(t, model, parent, name, relation, mutation) {
5833
+ const related = {
5834
+ context: t.context,
5835
+ state: mutation.state,
5836
+ modelName: relation.to,
5837
+ namespaceId: relation.toNamespace
5838
+ };
5839
+ const sources = sourcesOf(t.context.contract, model, relation, related.state.tables, parent);
5840
+ if (mutation.kind === "deleteAll") {
5841
+ addDeleteAll(t, related, sources);
5842
+ return;
5843
+ }
5844
+ const set = updateValuesOf(related, mutation.data);
5845
+ const linking = (relation.through === void 0 ? relation.on.targetFields : []).filter((field) => Object.hasOwn(set, columnOfContractField(t.context.contract, relation.toNamespace, relation.to, field)));
5846
+ if (linking.length > 0) throw ormError("ORM.RELATION_MUTATION_INVALID", `updateAll() nested mutation for relation "${name}" cannot set ${linking.map((field) => `"${field}"`).join(", ")}, which links the related rows to their parent`, { meta: {
5847
+ kind: "updateAll",
5848
+ relation: name,
5849
+ problem: "parent-link-column",
5850
+ fields: linking
5851
+ } });
5852
+ if (Object.keys(set).length > 0) addUpdateAll(t, related, set, sources, "count");
5853
+ }
5854
+ function sourcesOf(contract, model, relation, { root, scope }, parent) {
5855
+ const localColumns = localColumnsOf(contract, model, relation);
5856
+ const { through } = relation;
5857
+ if (through === void 0) return {
5858
+ filters: [{
5859
+ from: parent,
5860
+ columns: columnMappings(contract, model.tables.root, localColumns, root, resolveRelationTargetColumns(contract, relation))
5861
+ }],
5862
+ links: []
5863
+ };
5864
+ const links = scope.aliasTable({
5865
+ namespaceId: through.namespaceId,
5866
+ tableName: through.table
5867
+ });
5868
+ return {
5869
+ filters: [],
5870
+ links: [{
5871
+ from: parent,
5872
+ columns: columnMappings(contract, model.tables.root, localColumns, links, through.parentColumns),
5873
+ junction: links.tableSource(contract),
5874
+ targets: columnMappings(contract, links, through.childColumns, root, through.targetColumns)
5875
+ }]
5876
+ };
5877
+ }
5480
5878
  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, {
5879
+ insertRows(t, model, rows.map((row) => createRowOf(t.context, model, void 0, row, void 0)), {
5484
5880
  conflict: void 0,
5485
5881
  keys,
5486
- junction: void 0
5882
+ requires: [],
5883
+ owner: {
5884
+ operation: "create",
5885
+ modelName: model.modelName
5886
+ },
5887
+ returns: "count",
5888
+ shape: allColumns,
5889
+ afterWrite: void 0
5487
5890
  });
5488
5891
  }
5489
5892
  function addFindAndAssert(t, related, name, kind, criterion, columns) {
5490
5893
  const { graph, context } = t;
5491
5894
  const where = requiredCriterion(context, related, name, kind, criterion);
5492
- const find = graph.add(new Find(selectAstOf(context, related, {
5895
+ const find = findRows(t, selectAstOf(context, related, {
5493
5896
  ...emptyState(related.tables),
5494
5897
  filters: [where],
5495
5898
  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: {
5899
+ }, "selection"), {
5900
+ filter: [],
5901
+ requires: parentRowRequired(t)
5902
+ });
5903
+ graph.add(new Assert(ormError("ORM.RELATION_ROW_MISSING", `${kind}() nested mutation for relation "${name}" did not find a matching row`, { meta: {
5499
5904
  kind,
5500
5905
  relation: name
5501
- } })));
5502
- graph.addRowsEdge(find, assert, "rows", columns.map(([source]) => [source, source]));
5503
- requireParentRow(t, assert);
5906
+ } })), {
5907
+ rows: new Rows(find, columns.map(([source]) => [source, source])),
5908
+ requires: parentRowRequired(t)
5909
+ });
5504
5910
  return find;
5505
5911
  }
5506
5912
  function requiredCriterion(context, model, name, kind, criterion) {
@@ -5512,8 +5918,8 @@ function requiredCriterion(context, model, name, kind, criterion) {
5512
5918
  } });
5513
5919
  return where;
5514
5920
  }
5515
- function requireParentRow(t, node) {
5516
- if (t.parentRow !== void 0) t.graph.addRequiresEdge(t.parentRow, node);
5921
+ function parentRowRequired(t) {
5922
+ return t.parentRow === void 0 ? [] : [new Requires(t.parentRow)];
5517
5923
  }
5518
5924
  function criterionWhere(context, model, criterion) {
5519
5925
  return shorthandToWhereExpr(context, model.namespaceId, model.modelName, castAs(criterion), model.tables.root);
@@ -5538,8 +5944,8 @@ function relatedModel(contract, relation) {
5538
5944
  function localColumnsOf(contract, model, relation) {
5539
5945
  return relation.on.localFields.map((field) => columnOfContractField(contract, model.namespaceId, model.modelName, field));
5540
5946
  }
5541
- function parseCreateInput(t, model, row) {
5542
- return parseMutationInput(t.context.contract, model.namespaceId, model.modelName, row);
5947
+ function parseCreateInput(t, model, row, relatedCollection) {
5948
+ return parseMutationInput(t.context.contract, model.namespaceId, model.modelName, row, relatedCollection);
5543
5949
  }
5544
5950
  function columnMappings(contract, from, fromColumns, to, toColumns) {
5545
5951
  return fromColumns.map((column, index) => [projectTableColumn(contract, from, column), projectTableColumn(contract, to, blindCast(toColumns[index]))]);
@@ -5554,163 +5960,184 @@ var UnionAll = class extends Node {
5554
5960
  return rowsResult((inputs.rows ?? []).flat());
5555
5961
  }
5556
5962
  };
5963
+ function pinsUniqueKey(contract, table, where) {
5964
+ const pinned = new Set(conjunctsOf(where).flatMap((expr) => pinnedColumns(table.alias, expr)));
5965
+ const { namespaceId, tableName } = table.storage;
5966
+ return resolveUniqueKeyColumnSets(contract, namespaceId, tableName).some((key) => key.every((column) => pinned.has(column)));
5967
+ }
5968
+ function conjunctsOf(where) {
5969
+ if (where === void 0) return [];
5970
+ return where.kind === "and" ? where.exprs.flatMap(conjunctsOf) : [where];
5971
+ }
5972
+ function pinnedColumns(alias, expr) {
5973
+ if (expr.kind !== "binary" || expr.op !== "eq") return [];
5974
+ return [[expr.left, expr.right], [expr.right, expr.left]].flatMap(([column, value]) => column?.kind === "column-ref" && column.table === alias && isValue(value) ? [column.column] : []);
5975
+ }
5976
+ function isValue(expr) {
5977
+ return expr?.kind === "param-ref" || expr?.kind === "literal" && expr.value !== null;
5978
+ }
5557
5979
  function updateAllGraph(collection, set, returns) {
5558
5980
  const { context, state } = collection;
5559
- const graph = new Graph(context.contract);
5981
+ const b = builderOf(collection);
5560
5982
  if (Object.keys(set).length === 0) {
5561
- graph.setResult(graph.add(new Find(selectRowsAst(collection, state))));
5562
- return graph;
5563
- }
5564
- requireIdentityColumnsForIncludes(collection);
5565
- const update = {
5983
+ b.graph.setResult(findRows(b, selectRowsAst(collection, state), noInputs));
5984
+ return b.graph;
5985
+ }
5986
+ if (returns === "rows") requireIdentityColumnsForIncludes(collection);
5987
+ const where = whereOf(collection);
5988
+ const keys = returns === "rows" && identityColumnsOf(collection).length > 0 ? [{
5989
+ from: findRows(b, SelectAst.from(state.tables.root.tableSource(context.contract)).withProjection(identityProjection(collection)).withWhere(where), noInputs),
5990
+ columns: sameRowColumns(collection)
5991
+ }] : [];
5992
+ b.graph.setResult(addUpdateAll(b, collection, set, {
5993
+ filters: keys,
5994
+ links: []
5995
+ }, returns));
5996
+ return b.graph;
5997
+ }
5998
+ function addUpdateAll(b, collection, set, { filters, links }, returns) {
5999
+ return updateRows(b, modelOf(collection), set, {
5566
6000
  where: whereOf(collection),
5567
- filters: [],
5568
- payloads: []
5569
- };
5570
- if (readsBack(collection, returns)) {
5571
- const { namespaceId, tableName } = state.tables.root.storage;
5572
- readBackIdentity(context.contract, namespaceId, tableName, collection.modelName, "updateAll()");
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));
5576
- return graph;
5577
- }
5578
- const updated = addUpdateRows(graph, context.contract, state.tables, set, update);
5579
- graph.setResult(addWithIncludes(graph, collection, updated));
5580
- return graph;
6001
+ filters,
6002
+ links,
6003
+ payloads: [],
6004
+ owner: {
6005
+ operation: "updateAll",
6006
+ modelName: collection.modelName
6007
+ },
6008
+ returns,
6009
+ shape: shapeOf(collection),
6010
+ afterWrite: void 0
6011
+ });
5581
6012
  }
5582
6013
  function deleteAllGraph(collection, returns) {
5583
- const { context, state } = collection;
5584
- const graph = new Graph(context.contract);
5585
- const del = {
5586
- where: whereOf(collection),
5587
- filters: []
5588
- };
5589
- if (state.includes.length === 0 && !readsBack(collection, returns)) {
5590
- graph.setResult(addDeleteRows(graph, context.contract, state.tables, del));
5591
- return graph;
6014
+ const { state } = collection;
6015
+ const b = builderOf(collection);
6016
+ if (returns === "count") {
6017
+ b.graph.setResult(addDeleteAll(b, collection, {
6018
+ filters: [],
6019
+ links: []
6020
+ }));
6021
+ return b.graph;
5592
6022
  }
5593
- graph.setResult(graph.add(new Find(selectRowsAst(collection, state))));
5594
- addDeleteRows(graph, context.contract, state.tables, del);
5595
- return graph;
6023
+ const find = findRows(b, selectRowsAst(collection, state).withWhere(whereOf(collection)), noInputs);
6024
+ b.graph.setResult(find);
6025
+ addDeleteAll(b, collection, {
6026
+ filters: identityColumnsOf(collection).length > 0 ? [{
6027
+ from: find,
6028
+ columns: sameRowColumns(collection)
6029
+ }] : [],
6030
+ links: []
6031
+ });
6032
+ return b.graph;
6033
+ }
6034
+ function addDeleteAll(b, collection, sources) {
6035
+ return deleteRows(b, collection.state.tables, {
6036
+ where: whereOf(collection),
6037
+ ...sources
6038
+ });
5596
6039
  }
5597
6040
  function updateFirstGraph(collection, data, relationMutations = []) {
5598
- const { context, state } = collection;
5599
- const graph = new Graph(context.contract);
6041
+ const { state } = collection;
6042
+ const b = builderOf(collection);
5600
6043
  const set = mappedUpdateRow(collection, data);
5601
6044
  const bare = Object.keys(set).length === 0 && relationMutations.length === 0;
5602
6045
  if (!bare) {
5603
- requireIdentityColumns(collection);
6046
+ requireIdentityColumns(collection, "update()");
5604
6047
  requireIdentityColumnsForIncludes(collection);
5605
6048
  }
5606
- const find = addFindOfFirstRow(graph, collection, bare ? selectRowsAst : selectIdentityAst);
5607
- if (find === void 0) return graph;
6049
+ const first = addFindOfFirstRow(b, collection, bare ? selectRowsAst : selectIdentityAst);
6050
+ if (first === void 0) return b.graph;
6051
+ const { find, where } = first;
5608
6052
  if (bare) {
5609
- graph.setResult(find);
5610
- return graph;
6053
+ b.graph.setResult(find);
6054
+ return b.graph;
5611
6055
  }
5612
6056
  const model = modelOf(collection);
5613
6057
  const t = {
5614
- graph,
5615
- context,
5616
- parentRow: find,
5617
- readsBack: readsBack(collection, "rows")
6058
+ ...b,
6059
+ parentRow: find
5618
6060
  };
5619
6061
  const before = addBeforeWrite(t, model, relationMutations);
5620
6062
  const values = withUpdateDefaults(collection, set, before);
6063
+ const owner = {
6064
+ operation: "update",
6065
+ modelName: collection.modelName
6066
+ };
5621
6067
  if (Object.keys(values).length === 0 && before.keys.length === 0) {
5622
6068
  addAfterWrite(t, model, find, relationMutations);
5623
- graph.setResult(addWithIncludes(graph, collection, find));
5624
- return graph;
6069
+ b.graph.setResult(state.includes.length === 0 ? find : readBack(b, model, find, identityColumnsOf(collection), {
6070
+ shape: shapeOf(collection),
6071
+ by: "filter",
6072
+ owner
6073
+ }));
6074
+ return b.graph;
5625
6075
  }
5626
- const updated = addUpdateRows(graph, context.contract, state.tables, values, {
5627
- where: void 0,
6076
+ b.graph.setResult(updateRows(b, model, values, {
6077
+ where,
5628
6078
  filters: [{
5629
6079
  from: find,
5630
6080
  columns: sameRowColumns(collection)
5631
6081
  }],
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));
5647
- return graph;
6082
+ links: [],
6083
+ payloads: before.keys,
6084
+ owner,
6085
+ returns: "rows",
6086
+ shape: shapeOf(collection),
6087
+ afterWrite: (updated) => addAfterWrite(t, model, updated, relationMutations)
6088
+ }));
6089
+ return b.graph;
5648
6090
  }
5649
6091
  function deleteFirstGraph(collection) {
5650
- const { context, state } = collection;
5651
- const readsRowsFirst = state.includes.length > 0 || readsBack(collection, "rows");
5652
- const graph = new Graph(context.contract);
5653
- requireIdentityColumns(collection);
5654
- const find = addFindOfFirstRow(graph, collection, readsRowsFirst ? selectRowsAst : selectIdentityAst);
5655
- if (find === void 0) return graph;
5656
- const deleted = addDeleteRows(graph, context.contract, state.tables, {
5657
- where: void 0,
6092
+ const { state } = collection;
6093
+ const b = builderOf(collection);
6094
+ requireIdentityColumns(collection, "delete()");
6095
+ const first = addFindOfFirstRow(b, collection, selectRowsAst);
6096
+ if (first === void 0) return b.graph;
6097
+ const { find, where } = first;
6098
+ b.graph.setResult(find);
6099
+ deleteRows(b, state.tables, {
6100
+ where,
5658
6101
  filters: [{
5659
6102
  from: find,
5660
6103
  columns: sameRowColumns(collection)
5661
- }]
6104
+ }],
6105
+ links: []
5662
6106
  });
5663
- graph.setResult(readsRowsFirst ? find : deleted);
5664
- return graph;
6107
+ return b.graph;
5665
6108
  }
5666
6109
  function createAllGraph(collection, data, conflict, returns) {
5667
- const { context, state } = collection;
5668
- const graph = new Graph(context.contract);
5669
- if (data.length === 0) return graph;
6110
+ const b = builderOf(collection);
6111
+ if (data.length === 0) return b.graph;
5670
6112
  const rows = createRowsOf(collection, data);
5671
- requireIdentityColumnsForIncludes(collection);
5672
- const { contract } = context;
5673
- const { root } = state.tables;
5674
- if (readsBack(collection, returns)) {
5675
- const method = rows.length === 1 ? "create()" : "createAll()";
5676
- refuseSkipWithReadBack(collection, conflict, method);
5677
- const { keys, generated } = writtenKeys({
5678
- context,
5679
- namespaceId: root.storage.namespaceId,
5680
- tableName: root.storage.tableName,
5681
- modelName: collection.modelName,
5682
- rows,
5683
- method
5684
- });
5685
- const asts = supportsDefaultInInsert(contract) ? [insertAst(contract, root, rows, void 0)] : groupRowsByColumnSignature(rows).map((group) => insertAst(contract, root, group, void 0));
5686
- const owner = {
5687
- operation: rows.length === 1 ? "create" : "createAll",
5688
- modelName: collection.modelName
5689
- };
5690
- const inserted = graph.add(new InsertReportingKeys(asts, keys, generated, owner));
5691
- graph.setResult(addFindOfWrittenRows(graph, collection, inserted, identityProjection(collection), owner));
5692
- return graph;
5693
- }
5694
- const inserted = addInsertRows(graph, contract, root, rows, {
6113
+ if (returns === "rows") requireIdentityColumnsForIncludes(collection);
6114
+ b.graph.setResult(insertRows(b, modelOf(collection), rows, {
5695
6115
  conflict,
5696
6116
  keys: [],
5697
- junction: void 0
5698
- });
5699
- graph.setResult(addWithIncludes(graph, collection, inserted));
5700
- return graph;
6117
+ requires: [],
6118
+ owner: {
6119
+ operation: rows.length === 1 ? "create" : "createAll",
6120
+ modelName: collection.modelName
6121
+ },
6122
+ returns,
6123
+ shape: shapeOf(collection),
6124
+ afterWrite: void 0
6125
+ }));
6126
+ return b.graph;
5701
6127
  }
5702
6128
  function createGraph(collection, parsed) {
5703
- const { context } = collection;
5704
- const graph = new Graph(context.contract);
6129
+ const b = builderOf(collection);
5705
6130
  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;
6131
+ b.graph.setResult(addCreateWithRelations({
6132
+ ...b,
6133
+ parentRow: void 0
6134
+ }, modelOf(collection), parsed, {
6135
+ keysFromParent: [],
6136
+ returns: "rows",
6137
+ shape: shapeOf(collection),
6138
+ variantValue: collection.state.variantValue
6139
+ }));
6140
+ return b.graph;
5714
6141
  }
5715
6142
  function createAllVariantGraph(collection, variantTable, mti, data) {
5716
6143
  const { context, modelName, state } = collection;
@@ -5723,24 +6150,31 @@ function createAllVariantGraph(collection, variantTable, mti, data) {
5723
6150
  const keyMappings = keyColumns.map((column) => [projectTableColumn(contract, root, column), projectTableColumn(contract, variantTable, column)]);
5724
6151
  const baseColumns = returningProjection(contract, modelName, root, void 0);
5725
6152
  const variantColumns = variantReturning(contract, variantTable, variantModelName, keyColumns);
6153
+ const owner = {
6154
+ operation: "createAll",
6155
+ modelName
6156
+ };
5726
6157
  const joins = rows.map((row) => {
5727
- const baseInsert = insertAst(contract, root, [row.base], void 0).withReturning(baseColumns);
5728
- const base = graph.add(new Insert(baseInsert));
5729
- const variantInsert = insertAst(contract, variantTable, [row.variant], void 0).withReturning(variantColumns);
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;
6158
+ const baseInsert = new Insert([insertAst(contract, root, [row.base], void 0).withReturning(baseColumns)], owner);
6159
+ const base = graph.add(baseInsert, { state: graph.stateEdgesFor(baseInsert) });
6160
+ const variantInsert = new Insert([insertAst(contract, variantTable, [row.variant], void 0).withReturning(variantColumns)], {
6161
+ operation: "createAll",
6162
+ modelName: variantModelName
6163
+ });
6164
+ const variant = graph.add(variantInsert, {
6165
+ payload: [new PayloadData(base, keyMappings)],
6166
+ state: graph.stateEdgesFor(variantInsert)
6167
+ });
6168
+ return graph.add(new CrossJoin(), {
6169
+ left: new Rows(base, sameColumns(baseColumns)),
6170
+ right: new Rows(variant, sameColumns(variantColumns))
6171
+ });
5736
6172
  });
5737
6173
  const [only, ...others] = joins;
5738
6174
  if (only !== void 0 && others.length === 0) graph.setResult(only);
5739
6175
  else if (only !== void 0) {
5740
6176
  const joined = sameColumns([...baseColumns, ...variantColumns]);
5741
- const union = graph.add(new UnionAll());
5742
- for (const join of joins) graph.addRowsEdge(join, union, "rows", joined);
5743
- graph.setResult(union);
6177
+ graph.setResult(graph.add(new UnionAll(), { rows: joins.map((join) => new Rows(join, joined)) }));
5744
6178
  }
5745
6179
  return graph;
5746
6180
  }
@@ -5753,72 +6187,46 @@ function upsertGraph(collection, createData, updateData, conflictColumns) {
5753
6187
  const update = updateValuesOf(collection, updateData);
5754
6188
  const { contract } = context;
5755
6189
  const { root } = state.tables;
5756
- const graph = new Graph(context.contract);
6190
+ const b = builderOf(collection);
5757
6191
  requireIdentityColumnsForIncludes(collection);
5758
6192
  const targeted = hasContractCapability(contract, "insertOnConflictTarget");
5759
6193
  if (!targeted) requireOnlyCollidingKey(collection, create, conflictColumns);
5760
6194
  const updateSet = Object.keys(update).length > 0 ? updateAssignments(contract, root, update) : Object.fromEntries(conflictColumns.slice(0, 1).map((column) => [column, ColumnRef.of("excluded", column)]));
5761
- const upsert = upsertAst(contract, root, create, targeted ? conflictColumns : [], updateSet);
5762
- if (readsBack(collection, "rows")) {
5763
- const conflictValues = upsertConflictValues(collection, create, update, conflictColumns);
5764
- const upsertOwner = {
5765
- operation: "upsert",
5766
- modelName: collection.modelName
5767
- };
5768
- const upserted = graph.add(new InsertReportingKeys([upsert], [conflictValues], void 0, upsertOwner));
5769
- graph.setResult(addFindOfWrittenRows(graph, collection, upserted, projectTableColumns(contract, root, conflictColumns), upsertOwner));
5770
- return graph;
5771
- }
5772
- const upserted = graph.add(new Insert(upsert));
5773
- graph.setResult(addWithIncludes(graph, collection, upserted));
5774
- return graph;
5775
- }
5776
- function addWithIncludes(graph, collection, written) {
5777
- if (collection.state.includes.length === 0) return written;
5778
- const find = graph.add(new Find(readBackAst(collection, collection.state.includes)));
5779
- graph.addFilterDataEdge(written, find, sameRowColumns(collection));
5780
- return find;
5781
- }
5782
- function readBackAst(collection, includes) {
5783
- const { state } = collection;
5784
- return selectRowsAst(collection, {
5785
- ...emptyState(state.tables),
5786
- selectedFields: state.selectedFields,
5787
- includes
5788
- });
5789
- }
5790
- /**
5791
- * Without `RETURNING`, a write that returns rows runs as the write, then a select of the rows by key, chosen from the contract before anything runs.
5792
- */
5793
- function readsBack(collection, returns) {
5794
- return returns === "rows" && !hasContractCapability(collection.context.contract, "returning");
6195
+ const owner = {
6196
+ operation: "upsert",
6197
+ modelName: collection.modelName
6198
+ };
6199
+ const upsert = new Insert([upsertAst(contract, root, create, targeted ? conflictColumns : [], updateSet)], owner);
6200
+ const upserted = b.graph.add(upsert, { state: b.graph.stateEdgesFor(upsert) });
6201
+ b.graph.setResult(readBack(b, modelOf(collection), upserted, conflictColumns, {
6202
+ shape: shapeOf(collection),
6203
+ by: "keys",
6204
+ owner
6205
+ }));
6206
+ return b.graph;
5795
6207
  }
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. */
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;
6208
+ const noInputs = {
6209
+ filter: [],
6210
+ requires: []
6211
+ };
6212
+ function builderOf(collection) {
6213
+ return {
6214
+ graph: new Graph(collection.context.contract),
6215
+ context: collection.context
6216
+ };
5801
6217
  }
5802
- function addFindOfWrittenRows(graph, collection, inserted, keyColumns, owner) {
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;
6218
+ function shapeOf(collection) {
6219
+ const { selectedFields, includes, variantValue } = collection.state;
6220
+ return {
6221
+ selectedFields,
6222
+ includes,
6223
+ variantValue
6224
+ };
5807
6225
  }
5808
6226
  function identityProjection(collection) {
5809
6227
  const { context, state } = collection;
5810
6228
  return projectTableColumns(context.contract, state.tables.root, identityColumnsOf(collection));
5811
6229
  }
5812
- function keyOverrides(collection, set) {
5813
- return Object.fromEntries(identityColumnsOf(collection).filter((column) => Object.hasOwn(set, column)).map((column) => [column, set[column]]));
5814
- }
5815
- function refuseSkipWithReadBack(collection, conflict, method) {
5816
- if (conflict === void 0) return;
5817
- throw ormError("ORM.CAPABILITY_MISSING", `${method} with onConflict "skip" on model "${collection.modelName}" requires contract capability "returning": without it the rows are read back by key, which finds a skipped row's existing match. Use createAndCount() to skip conflicting rows.`, { meta: {
5818
- capability: "returning",
5819
- action: method
5820
- } });
5821
- }
5822
6230
  /**
5823
6231
  * Without capability `insertOnConflictTarget`, the database's conflict clause fires on any unique key, so the upsert is allowed only when the named columns are the only key the create values can collide on: every other primary key or unique constraint contains an auto-increment column the create values leave out.
5824
6232
  */
@@ -5833,19 +6241,6 @@ function requireOnlyCollidingKey(collection, create, conflictColumns) {
5833
6241
  action: "upsert()"
5834
6242
  } });
5835
6243
  }
5836
- /** The create's values for the conflict columns, by which an upsert without `RETURNING` reads its row back. */
5837
- function upsertConflictValues(collection, create, update, conflictColumns) {
5838
- const { modelName } = collection;
5839
- const refused = (problem) => ormError("ORM.CAPABILITY_MISSING", `upsert() on model "${modelName}" ${problem}; without capability "returning" the row is read back by the create's values for the conflict columns.`, { meta: {
5840
- capability: "returning",
5841
- action: "upsert()"
5842
- } });
5843
- const updated = conflictColumns.filter((column) => Object.hasOwn(update, column));
5844
- if (updated.length > 0) throw refused(`updates conflict column "${updated.join("\", \"")}"`);
5845
- const absent = conflictColumns.filter((column) => create[column] === void 0);
5846
- if (absent.length > 0) throw refused(`gives conflict column "${absent.join("\", \"")}" no create value`);
5847
- return Object.fromEntries(conflictColumns.map((column) => [column, create[column]]));
5848
- }
5849
6244
  function requireIdentityColumnsForIncludes(collection) {
5850
6245
  const { modelName, state } = collection;
5851
6246
  const { tableName } = state.tables.root.storage;
@@ -5854,22 +6249,31 @@ function requireIdentityColumnsForIncludes(collection) {
5854
6249
  table: tableName
5855
6250
  } });
5856
6251
  }
5857
- function addFindOfFirstRow(graph, collection, select) {
5858
- const { state } = collection;
6252
+ function addFindOfFirstRow(b, collection, select) {
6253
+ const { context, state } = collection;
5859
6254
  checkLimitOffset("limit", state.limit);
5860
6255
  if (state.limit === 0) return;
5861
- return graph.add(new Find(select(collection, {
5862
- ...state,
5863
- limit: 1
5864
- })));
6256
+ const where = whereOf(collection);
6257
+ if (state.offset === void 0 && state.cursor === void 0 && pinsUniqueKey(context.contract, state.tables.root, where)) return {
6258
+ find: findRows(b, select(collection, {
6259
+ ...state,
6260
+ limit: void 0,
6261
+ orderBy: void 0
6262
+ }).withWhere(where), noInputs),
6263
+ where
6264
+ };
6265
+ return {
6266
+ find: findRows(b, select(collection, {
6267
+ ...state,
6268
+ limit: 1
6269
+ }), noInputs),
6270
+ where: void 0
6271
+ };
5865
6272
  }
5866
- function requireIdentityColumns(collection) {
5867
- const { modelName, state } = collection;
5868
- const { tableName } = state.tables.root.storage;
5869
- if (identityColumnsOf(collection).length === 0) throw ormError("ORM.ROW_IDENTITY_MISSING", `update()/delete() on model "${modelName}" requires the table to have a primary key or unique constraint`, { meta: {
5870
- model: modelName,
5871
- table: tableName
5872
- } });
6273
+ function requireIdentityColumns(collection, method) {
6274
+ const { context, modelName, state } = collection;
6275
+ const { namespaceId, tableName } = state.tables.root.storage;
6276
+ rowIdentity(context.contract, namespaceId, tableName, modelName, method);
5873
6277
  }
5874
6278
  function selectIdentityAst(collection, state) {
5875
6279
  return selectAstOf(collection.context, modelOf(collection), state, "identity");
@@ -5889,12 +6293,13 @@ function whereOf(collection) {
5889
6293
  return countMutationWhere(context.contract, state.tables, state.filters, state.variantValue);
5890
6294
  }
5891
6295
  function queryGraph(graph, ctx, callerRows) {
6296
+ graph.removeUnreadFinds();
5892
6297
  returnCallerColumns(graph, callerRows);
5893
- const [only, ...others] = statementNodes(graph);
5894
- if (only !== void 0 && others.length === 0 && only[0] === graph.result) {
6298
+ const [only] = statementNodes(graph);
6299
+ if (only !== void 0 && statementCount(graph) === 1 && only[0] === graph.result) {
5895
6300
  const [id, node] = only;
5896
6301
  const run = runOn(ctx, ctx.runtime);
5897
- return shapeRows(graph, id, rowStream(node.execute(inputsOf(graph, id, []), run)), callerRows);
6302
+ return shapeRows(graph, id, afterChecks(graph, ctx, () => rowStream(node.execute(outputsOf(graph.inputsOf(id), []), run))), callerRows);
5898
6303
  }
5899
6304
  const generator = async function* () {
5900
6305
  yield* (await runAllNodes(graph, ctx, callerRows)).rows;
@@ -5902,6 +6307,7 @@ function queryGraph(graph, ctx, callerRows) {
5902
6307
  return new AsyncIterableResult(generator());
5903
6308
  }
5904
6309
  async function executeGraph(graph, ctx) {
6310
+ graph.removeUnreadFinds();
5905
6311
  return { affectedRows: (await runAllNodes(graph, ctx, void 0)).count };
5906
6312
  }
5907
6313
  function returnCallerColumns(graph, callerRows) {
@@ -5910,8 +6316,9 @@ function returnCallerColumns(graph, callerRows) {
5910
6316
  for (const [id, node] of graph.nodes()) if (id === graph.result && node instanceof StatementNode) graph.replace(id, node.withReturning(columns));
5911
6317
  }
5912
6318
  async function runAllNodes(graph, ctx, callerRows) {
6319
+ checkNodes(graph, ctx);
5913
6320
  const { runtime } = ctx;
5914
- if (statementNodes(graph).length > 1 && runtime.transaction !== void 0) return runInTransaction(await runtime.transaction(), (scope) => runNodesInOrder(graph, ctx, scope, callerRows));
6321
+ if (statementCount(graph) > 1 && runtime.transaction !== void 0) return runInTransaction(await runtime.transaction(ctx.implicitTransactionOptions), (scope) => runNodesInOrder(graph, ctx, scope, callerRows));
5915
6322
  return runNodesInOrder(graph, ctx, runtime, callerRows);
5916
6323
  }
5917
6324
  async function runInTransaction(transaction, run) {
@@ -5935,8 +6342,8 @@ async function runNodesInOrder(graph, ctx, scope, callerRows) {
5935
6342
  const collected = [];
5936
6343
  let rows = [];
5937
6344
  let count = 0;
5938
- for (const [id, node] of graph.nodes()) {
5939
- const executed = await node.execute(inputsOf(graph, id, collected), run);
6345
+ for (const { id, node, inputs } of graph.entries()) {
6346
+ const executed = await node.execute(outputsOf(inputs, collected), run);
5940
6347
  collected[id] = executed;
5941
6348
  if (id !== graph.result) continue;
5942
6349
  const storageRows = rowsOf(executed);
@@ -5948,17 +6355,28 @@ async function runNodesInOrder(graph, ctx, scope, callerRows) {
5948
6355
  count
5949
6356
  };
5950
6357
  }
5951
- function inputsOf(graph, id, collected) {
6358
+ function outputsOf(inputs, collected) {
5952
6359
  const outputs = {};
5953
6360
  const outputOf = (edge) => rowsOf(collected[edge.from]).map((row) => edge.output(row));
5954
- for (const [name, slot] of Object.entries(graph.inputsOf(id))) if (!Array.isArray(slot)) outputs[name] = outputOf(slot);
6361
+ for (const [name, slot] of Object.entries(inputs)) if (!Array.isArray(slot)) outputs[name] = outputOf(slot);
5955
6362
  else outputs[name] = slot.length === 0 ? null : slot.map(outputOf);
5956
6363
  return outputs;
5957
6364
  }
6365
+ function checkNodes(graph, ctx) {
6366
+ for (const [id, node] of graph.nodes()) node.checkIfCanRun(graph, id, ctx.context);
6367
+ }
6368
+ function afterChecks(graph, ctx, rows) {
6369
+ const generator = async function* () {
6370
+ checkNodes(graph, ctx);
6371
+ yield* rows();
6372
+ };
6373
+ return new AsyncIterableResult(generator());
6374
+ }
5958
6375
  function runOn(ctx, scope) {
5959
- const { contract } = ctx.context;
5960
- const planOf = (ast) => buildOrmQueryPlan(contract, ast, deriveParamsFromAst(ast).params);
6376
+ const { context } = ctx;
6377
+ const planOf = (ast) => buildOrmQueryPlan(context.contract, ast, deriveParamsFromAst(ast).params);
5961
6378
  return {
6379
+ context,
5962
6380
  query: (ast) => queryPlanRows(scope, planOf(ast)),
5963
6381
  execute: (ast) => scope.execute(planOf(ast))
5964
6382
  };
@@ -5977,6 +6395,9 @@ function shapeRows(graph, id, storageRows, callerRows) {
5977
6395
  function statementNodes(graph) {
5978
6396
  return graph.nodes().filter(([, node]) => node instanceof StatementNode);
5979
6397
  }
6398
+ function statementCount(graph) {
6399
+ return graph.nodes().reduce((count, [, node]) => count + (node instanceof StatementNode ? node.statements.length : 0), 0);
6400
+ }
5980
6401
  function rowsOf(executed) {
5981
6402
  return Array.isArray(executed) ? executed : [];
5982
6403
  }
@@ -6564,17 +6985,9 @@ var CollectionBase = class CollectionBase {
6564
6985
  return runOrmCall(this.ctx.runtime, this.#writeCall("create", annotations, ormResults.row), (queryable) => this.#create(queryable, data));
6565
6986
  }
6566
6987
  async #create(queryable, data) {
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: {
6571
- operation: "create",
6572
- model: this.modelName
6573
- } });
6574
- return created;
6575
- }
6576
- const created = (await this.#createAllRows([blindCast(data)])(queryable))[0];
6577
- if (created) return created;
6988
+ const parsed = parseMutationInput(this.contract, this.namespaceId, this.modelName, blindCast(data), this.#relatedCollection);
6989
+ const [created] = await (mtiCreateContextOf(this.#descriptionOptions()) === void 0 ? queryGraph(createGraph(this.#descriptionOptions(), parsed), this.#on(queryable), this.#descriptionOptions()).toArray() : this.#createAllRows([blindCast(data)])(queryable));
6990
+ if (created !== void 0) return created;
6578
6991
  throw ormError("ORM.MUTATION_ROW_MISSING", `create() for model "${this.modelName}" did not return a row`, { meta: {
6579
6992
  operation: "create",
6580
6993
  model: this.modelName
@@ -6701,7 +7114,7 @@ var CollectionBase = class CollectionBase {
6701
7114
  }
6702
7115
  async #update(queryable, data) {
6703
7116
  const input = blindCast(data);
6704
- const parsed = parseMutationInput(this.contract, this.namespaceId, this.modelName, input);
7117
+ const parsed = parseMutationInput(this.contract, this.namespaceId, this.modelName, input, this.#relatedCollection);
6705
7118
  if (parsed.relationMutations.length > 0) assertRelationUpdateIgnoresNothing(this.state, this.modelName);
6706
7119
  assertModelFieldNames(this.contract, this.namespaceId, this.modelName, parsed.scalarData);
6707
7120
  return consumeFirstRow(queryGraph(updateFirstGraph(this.#descriptionOptions(), parsed.scalarData, parsed.relationMutations), this.#on(queryable), this.#descriptionOptions()));
@@ -6793,6 +7206,10 @@ var CollectionBase = class CollectionBase {
6793
7206
  includeRefinementMode: this.includeRefinementMode
6794
7207
  }));
6795
7208
  }
7209
+ #relatedCollection = (relation) => this.#createCollection(relation.to, {
7210
+ namespaceId: relation.toNamespace,
7211
+ includeRefinementMode: false
7212
+ });
6796
7213
  #createCollection(modelName, options) {
6797
7214
  return blindCast(new ((this.registry.get(modelName)) ?? (blindCast(CollectionBase)))(this.ctx, modelName, {
6798
7215
  tableName: options.tableName,
@@ -6854,7 +7271,8 @@ function orm(options) {
6854
7271
  const contract = context.contract;
6855
7272
  const ctx = {
6856
7273
  runtime,
6857
- context
7274
+ context,
7275
+ implicitTransactionOptions: options.implicitTransactionOptions
6858
7276
  };
6859
7277
  const collectionRegistry = checkCollectionClasses(contract, collections);
6860
7278
  function buildCollection(namespaceId, modelName, tableName) {