@prisma/orm-family-sql 8.0.0-rc.24-dev.33 → 8.0.0-rc.24-dev.34

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.
@@ -16,6 +16,7 @@ import { InternalError, isInternalError } from "@prisma/orm-framework/utils/inte
16
16
  import { canonicalStringify } from "@prisma/orm-framework/utils/canonical-stringify";
17
17
  import { AsyncIterableResult, createMetaBuilder, isRuntimeError, runtimeError } from "@prisma/orm-framework/components/runtime";
18
18
  import { hashContent } from "@prisma/orm-framework/utils/hash-content";
19
+ import { isRecord } from "@prisma/orm-framework/utils/guards";
19
20
  //#region ../../../3-extensions/sql-orm-client/dist/index.mjs
20
21
  const operationNamesByRegistry = /* @__PURE__ */ new WeakMap();
21
22
  /**
@@ -942,9 +943,6 @@ function modelHashInput(namespaceId, modelName) {
942
943
  model: modelName
943
944
  });
944
945
  }
945
- function isRecord(value) {
946
- return typeof value === "object" && value !== null && !Array.isArray(value);
947
- }
948
946
  const ormResults = {
949
947
  rows: (value) => Array.isArray(value),
950
948
  row: (value) => isRecord(value),
@@ -3165,12 +3163,9 @@ async function decodeCombineIncludePayload(contract, context, include, branches,
3165
3163
  function parseCombineEnvelope(include, raw) {
3166
3164
  if (raw === null || raw === void 0) throw new InternalError(`combine() envelope for include "${include.relationName}" is missing (got ${raw === null ? "null" : "undefined"}); the correlated subquery should always produce a JSON object — this indicates a planner or decoder bug.`);
3167
3165
  const parsed = parseIncludePayload(raw);
3168
- if (!isPlainObjectEnvelope(parsed)) throw new InternalError(`combine() envelope for include "${include.relationName}" has unexpected shape (expected object, got ${describeEnvelopeShape(parsed)}); this indicates a planner or decoder bug.`);
3166
+ if (!isRecord(parsed)) throw new InternalError(`combine() envelope for include "${include.relationName}" has unexpected shape (expected object, got ${describeEnvelopeShape(parsed)}); this indicates a planner or decoder bug.`);
3169
3167
  return parsed;
3170
3168
  }
3171
- function isPlainObjectEnvelope(value) {
3172
- return typeof value === "object" && value !== null && !Array.isArray(value);
3173
- }
3174
3169
  function describeEnvelopeShape(value) {
3175
3170
  if (value === null) return "null";
3176
3171
  if (Array.isArray(value)) return "array";
@@ -3220,7 +3215,7 @@ function resolveScalarIncludeMetadata(contract, context, include, scalar) {
3220
3215
  async function consumeScalarInclude(include, resolved, codec, raw) {
3221
3216
  if (raw === null || raw === void 0) return emptyAggregateResult(resolved, codec);
3222
3217
  const parsed = parseIncludePayload(raw);
3223
- if (!isPlainObjectEnvelope(parsed)) throw new InternalError(`scalar() envelope for include "${include.relationName}" has unexpected shape (expected object, got ${describeEnvelopeShape(parsed)}); this indicates a planner or decoder bug.`);
3218
+ if (!isRecord(parsed)) throw new InternalError(`scalar() envelope for include "${include.relationName}" has unexpected shape (expected object, got ${describeEnvelopeShape(parsed)}); this indicates a planner or decoder bug.`);
3224
3219
  const value = parsed["value"];
3225
3220
  if (value === null || value === void 0) return emptyAggregateResult(resolved, codec);
3226
3221
  return decodeIncludedJsonValue({
@@ -3239,7 +3234,7 @@ function parseIncludedRows(include, value) {
3239
3234
  if (!Array.isArray(parsed)) return [];
3240
3235
  const rows = [];
3241
3236
  for (const item of parsed) {
3242
- if (!isPlainObjectEnvelope(item)) throw new InternalError(`Include row envelope for relation "${include.relationName}" has unexpected shape (expected object, got ${describeEnvelopeShape(item)}); this indicates a planner or decoder bug.`);
3237
+ if (!isRecord(item)) throw new InternalError(`Include row envelope for relation "${include.relationName}" has unexpected shape (expected object, got ${describeEnvelopeShape(item)}); this indicates a planner or decoder bug.`);
3243
3238
  rows.push({ ...item });
3244
3239
  }
3245
3240
  return rows;
@@ -4435,6 +4430,19 @@ function createFilteredRelationMutator(related) {
4435
4430
  kind: "deleteAll",
4436
4431
  state: related.state
4437
4432
  };
4433
+ },
4434
+ update(data) {
4435
+ return {
4436
+ kind: "update",
4437
+ state: related.state,
4438
+ data: { ...data }
4439
+ };
4440
+ },
4441
+ delete() {
4442
+ return {
4443
+ kind: "delete",
4444
+ state: related.state
4445
+ };
4438
4446
  }
4439
4447
  };
4440
4448
  }
@@ -4487,8 +4495,13 @@ function createRelationMutator(related) {
4487
4495
  function isRelationMutationDescriptor(value) {
4488
4496
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
4489
4497
  const candidate = value;
4498
+ if (candidate.kind === "update") return hasFilters(candidate.state) && isRecord(candidate.data);
4499
+ if (candidate.kind === "delete") return hasFilters(candidate.state);
4490
4500
  return candidate.kind === "create" || candidate.kind === "connect" || candidate.kind === "disconnect" || candidate.kind === "updateAll" || candidate.kind === "deleteAll";
4491
4501
  }
4502
+ function hasFilters(state) {
4503
+ return isRecord(state) && Array.isArray(state["filters"]);
4504
+ }
4492
4505
  function isRelationMutationCallback(value) {
4493
4506
  return typeof value === "function";
4494
4507
  }
@@ -4850,6 +4863,41 @@ var CrossJoin = class extends Node {
4850
4863
  }]);
4851
4864
  }
4852
4865
  };
4866
+ var Edge = class {
4867
+ from;
4868
+ constructor(from) {
4869
+ this.from = from;
4870
+ }
4871
+ };
4872
+ var DataEdge = class extends Edge {
4873
+ columns;
4874
+ constructor(from, columns) {
4875
+ super(from);
4876
+ this.columns = Object.freeze([...columns]);
4877
+ }
4878
+ };
4879
+ /** The condition that matches the row whose source columns hold the values in `sourceRow`. */
4880
+ function keyCondition(columns, sourceRow) {
4881
+ const conditions = columns.map(([source, target]) => BinaryExpr.eq(target.expr, ParamRef.of(sourceRow[source.alias], {
4882
+ name: target.alias,
4883
+ ...ifDefined("codec", target.codec)
4884
+ })));
4885
+ const [first, ...others] = conditions;
4886
+ return first !== void 0 && others.length === 0 ? first : AndExpr.of(conditions);
4887
+ }
4888
+ /** Matches each source row's row in the reading statement: the condition that selects it, and its key by target column. */
4889
+ var FilterData = class extends DataEdge {
4890
+ constructor(from, columns) {
4891
+ super(from, columns);
4892
+ Object.freeze(this);
4893
+ }
4894
+ output(sourceRow) {
4895
+ return {
4896
+ condition: keyCondition(this.columns, sourceRow),
4897
+ key: Object.fromEntries(this.columns.map(([source, target]) => [target.alias, sourceRow[source.alias]]))
4898
+ };
4899
+ }
4900
+ };
4853
4901
  function storageOf(source) {
4854
4902
  return {
4855
4903
  namespaceId: blindCast(source.namespaceId),
@@ -4918,19 +4966,6 @@ function stepKey(step) {
4918
4966
  step.table.tableName
4919
4967
  ]);
4920
4968
  }
4921
- var Edge = class {
4922
- from;
4923
- constructor(from) {
4924
- this.from = from;
4925
- }
4926
- };
4927
- var DataEdge = class extends Edge {
4928
- columns;
4929
- constructor(from, columns) {
4930
- super(from);
4931
- this.columns = Object.freeze([...columns]);
4932
- }
4933
- };
4934
4969
  var Requires = class extends Edge {
4935
4970
  constructor(from) {
4936
4971
  super(from);
@@ -4941,11 +4976,6 @@ var Requires = class extends Edge {
4941
4976
  function requirementUnmet(requires) {
4942
4977
  return requires?.some((rows) => rows.length === 0) === true;
4943
4978
  }
4944
- const filteredSlots = {
4945
- filter: "list",
4946
- state: "list",
4947
- requires: "list"
4948
- };
4949
4979
  const linkedSlots = {
4950
4980
  filter: "list",
4951
4981
  link: "list",
@@ -4989,7 +5019,7 @@ function withColumns(returned, columns) {
4989
5019
  }
4990
5020
  var StatementNode = class extends Node {};
4991
5021
  var Find = class Find extends StatementNode {
4992
- slots = filteredSlots;
5022
+ slots = linkedSlots;
4993
5023
  ast;
4994
5024
  constructor(ast) {
4995
5025
  super();
@@ -5009,28 +5039,6 @@ var Find = class Find extends StatementNode {
5009
5039
  return new Find(this.ast.withProjection(withColumns(this.returns, columns)));
5010
5040
  }
5011
5041
  };
5012
- /** The condition that matches the row whose source columns hold the values in `sourceRow`. */
5013
- function keyCondition(columns, sourceRow) {
5014
- const conditions = columns.map(([source, target]) => BinaryExpr.eq(target.expr, ParamRef.of(sourceRow[source.alias], {
5015
- name: target.alias,
5016
- ...ifDefined("codec", target.codec)
5017
- })));
5018
- const [first, ...others] = conditions;
5019
- return first !== void 0 && others.length === 0 ? first : AndExpr.of(conditions);
5020
- }
5021
- /** Matches each source row's row in the reading statement: the condition that selects it, and its key by target column. */
5022
- var FilterData = class extends DataEdge {
5023
- constructor(from, columns) {
5024
- super(from, columns);
5025
- Object.freeze(this);
5026
- }
5027
- output(sourceRow) {
5028
- return {
5029
- condition: keyCondition(this.columns, sourceRow),
5030
- key: Object.fromEntries(this.columns.map(([source, target]) => [target.alias, sourceRow[source.alias]]))
5031
- };
5032
- }
5033
- };
5034
5042
  const encoder = new TextEncoder();
5035
5043
  /** Splits keys, in order, into the fewest chunks that each stay within the limits. A key that alone exceeds a limit gets a chunk of its own. */
5036
5044
  function chunkKeys(keys, limits) {
@@ -5183,8 +5191,12 @@ function readsTableAsFound(graph, inputs, { id, find }, table) {
5183
5191
  return read !== void 0 && sameTable(read, table) && own !== void 0 && own.from === found?.from;
5184
5192
  }
5185
5193
  function foldsIntoCondition(graph, { id, find }, where) {
5186
- const { filter, requires } = graph.inputsOf(id);
5187
- return find.ast.where === where && rowsOfConditionReadOf(find.ast) !== void 0 && [filter ?? [], requires ?? []].flat().length === 0;
5194
+ const { filter, link, requires } = graph.inputsOf(id);
5195
+ return find.ast.where === where && rowsOfConditionReadOf(find.ast) !== void 0 && [
5196
+ filter ?? [],
5197
+ link ?? [],
5198
+ requires ?? []
5199
+ ].flat().length === 0;
5188
5200
  }
5189
5201
  function oneTableReadOf(ast) {
5190
5202
  const { from } = ast;
@@ -5996,11 +6008,13 @@ function deleteRows({ graph, context }, tables, { where, filters, links }) {
5996
6008
  function linkEdge({ from, columns, junction, targets }) {
5997
6009
  return new JunctionFilterData(from, columns, junction, targets);
5998
6010
  }
5999
- function findRows({ graph }, ast, { filter, requires }) {
6011
+ function findRows({ graph }, ast, { filter, requires, links = [] }) {
6000
6012
  const find = new Find(ast);
6013
+ const link = links.map(linkEdge);
6001
6014
  return graph.add(find, {
6002
6015
  filter,
6003
- state: graph.stateEdgesFor(find),
6016
+ link,
6017
+ state: graph.stateEdgesFor(find, link),
6004
6018
  requires
6005
6019
  });
6006
6020
  }
@@ -6205,33 +6219,36 @@ function updateDefaultsOf(context, model, written) {
6205
6219
  values: written
6206
6220
  }).map((applied) => [applied.field, applied.value]));
6207
6221
  }
6208
- function addCreateWithRelations(t, model, parsed, createOf) {
6209
- return insertWithRelations(t, model, parsed, createOf, void 0, void 0);
6222
+ function addCreateWithRelations(b, model, parent, parsed, createOf) {
6223
+ return insertWithRelations(b, model, parent, parsed, createOf, void 0, void 0);
6210
6224
  }
6211
- function insertWithRelations(t, model, parsed, { keysFromParent, returns, shape, variantValue }, storageRow, nested) {
6225
+ function insertWithRelations(b, model, parent, parsed, { keysFromParent, returns, shape, variantValue }, storageRow, nested) {
6212
6226
  for (const relationMutation of parsed.relationMutations) rejectUpdateOnly(relationMutation);
6213
- const before = addBeforeWrite(t, model, parsed.relationMutations);
6214
- return insertRows(t, model, [storageRow ?? createRowOf(t.context, model, variantValue, parsed.scalarData, void 0)], {
6227
+ const before = addBeforeWrite(b, model, parent, parsed.relationMutations);
6228
+ return insertRows(b, model, [storageRow ?? createRowOf(b.context, model, variantValue, parsed.scalarData, void 0)], {
6215
6229
  conflict: nested?.conflict,
6216
6230
  keys: [...keysFromParent, ...before.keys],
6217
- requires: keysFromParent.length === 0 ? parentRowRequired(t) : [],
6231
+ requires: keysFromParent.length === 0 ? parentRowRequired(parent) : [],
6218
6232
  owner: {
6219
6233
  operation: "create",
6220
6234
  modelName: model.modelName
6221
6235
  },
6222
6236
  returns,
6223
6237
  shape,
6224
- afterWrite: afterWriteOf(t, model, parsed.relationMutations, nested)
6238
+ afterWrite: afterWriteOf(b, model, parent, parsed.relationMutations, nested)
6225
6239
  });
6226
6240
  }
6227
- function afterWriteOf(t, model, relationMutations, nested) {
6241
+ function afterWriteOf(b, model, parent, relationMutations, nested) {
6228
6242
  const { childOwned, junctionOwned } = partitionByOwnership(relationMutations);
6229
6243
  const readsRow = childOwned.length > 0 || junctionOwned.length > 0;
6230
6244
  const guard = nested !== void 0 && "link" in nested.conflict ? nested.conflict.guard : void 0;
6231
6245
  if (!readsRow && guard === void 0) return;
6232
6246
  return (written) => {
6233
- if (guard !== void 0 && nested !== void 0) addVariantCheck(t, model, written, nested.relation, guard);
6234
- if (readsRow) addAfterWrite(t, model, written, relationMutations);
6247
+ if (guard !== void 0 && nested !== void 0) addVariantCheck(b, model, written, nested.relation, guard);
6248
+ if (readsRow) addAfterWrite(b, model, {
6249
+ ...parent,
6250
+ node: written
6251
+ }, relationMutations);
6235
6252
  };
6236
6253
  }
6237
6254
  function addVariantCheck({ graph, context }, model, written, relation, { column, value }) {
@@ -6245,12 +6262,12 @@ function addVariantCheck({ graph, context }, model, written, relation, { column,
6245
6262
  requires: []
6246
6263
  });
6247
6264
  }
6248
- function addLinkedCreates(t, related, name, relatedCollection, mutation, resolved, data, link) {
6249
- const rows = data.map((row) => parseCreateInput(t, related, row, relatedCollection));
6250
- const values = rows.map((row) => createRowOf(t.context, related, mutation.variant, row.scalarData, void 0));
6251
- const nested = conflictOf(t, related, name, [], resolved, rows, values, mutation.variant);
6265
+ function addLinkedCreates(b, related, parent, name, relatedCollection, mutation, resolved, data, link) {
6266
+ const rows = data.map((row) => parseCreateInput(b, related, row, relatedCollection));
6267
+ const values = rows.map((row) => createRowOf(b.context, related, mutation.variant, row.scalarData, void 0));
6268
+ const nested = conflictOf(b, related, name, [], resolved, rows, values, mutation.variant);
6252
6269
  rows.forEach((row, index) => {
6253
- link(insertWithRelations(t, related, row, {
6270
+ link(insertWithRelations(b, related, parent, row, {
6254
6271
  keysFromParent: [],
6255
6272
  returns: "rows",
6256
6273
  shape: allColumns,
@@ -6258,27 +6275,27 @@ function addLinkedCreates(t, related, name, relatedCollection, mutation, resolve
6258
6275
  }, values[index], nested));
6259
6276
  });
6260
6277
  }
6261
- function addVariantInOwnTable(t, { relation, relatedCollection }, { data, variant }, keys, added) {
6278
+ function addVariantInOwnTable(b, parent, { relation, relatedCollection }, { data, variant }, keys, added) {
6262
6279
  if (variant === void 0) return false;
6263
6280
  const collection = {
6264
- context: t.context,
6281
+ context: b.context,
6265
6282
  state: relatedCollection(relation).variant(variant).state,
6266
6283
  modelName: relation.to,
6267
6284
  namespaceId: relation.toNamespace
6268
6285
  };
6269
6286
  const mti = mtiCreateContextOf(collection);
6270
6287
  if (mti === void 0) return false;
6271
- for (const row of data) parseCreateInput(t, modelOf(collection), row, relatedCollection);
6272
- assertReturningCapability(t.context.contract, "create()");
6288
+ for (const row of data) parseCreateInput(b, modelOf(collection), row, relatedCollection);
6289
+ assertReturningCapability(b.context.contract, "create()");
6273
6290
  createAllVariantGraph(collection, requireVariantTable(collection.state.tables, mti.variant.value), mti, data, {
6274
- graph: t.graph,
6291
+ graph: b.graph,
6275
6292
  keys,
6276
- requires: keys.length === 0 ? parentRowRequired(t) : [],
6293
+ requires: keys.length === 0 ? parentRowRequired(parent) : [],
6277
6294
  added
6278
6295
  });
6279
6296
  return true;
6280
6297
  }
6281
- function addBeforeWrite(t, model, relationMutations) {
6298
+ function addBeforeWrite(b, model, parent, relationMutations) {
6282
6299
  const { parentOwned, junctionOwned } = partitionByOwnership(relationMutations);
6283
6300
  for (const relationMutation of junctionOwned) {
6284
6301
  assertJunctionMetadataShape(relationMutation);
@@ -6287,18 +6304,26 @@ function addBeforeWrite(t, model, relationMutations) {
6287
6304
  const keys = [];
6288
6305
  const nullColumns = {};
6289
6306
  let unlinksAfterWrite = false;
6290
- for (const relationMutation of relationMutations) rejectFilteredWriteOnToOne(relationMutation);
6307
+ for (const relationMutation of relationMutations) {
6308
+ rejectFilteredWriteOnToOne(relationMutation);
6309
+ rejectSingleRowWrite(relationMutation);
6310
+ }
6291
6311
  for (const relationMutation of parentOwned) for (const mutation of relationMutation.mutations) {
6312
+ if (mutation.kind === "delete") {
6313
+ rejectNullOnRequiredKey(b.context.contract, mutation.kind, relationMutation.name, model, relationMutation.relation.on.localFields);
6314
+ unlinksAfterWrite = true;
6315
+ continue;
6316
+ }
6292
6317
  if (isFilteredWrite(mutation)) continue;
6293
6318
  if (mutation.kind === "disconnect") {
6294
- rejectNullOnRequiredKey(t.context.contract, mutation.kind, relationMutation.name, model, relationMutation.relation.on.localFields);
6319
+ rejectNullOnRequiredKey(b.context.contract, mutation.kind, relationMutation.name, model, relationMutation.relation.on.localFields);
6295
6320
  if (disconnectsNothing(mutation)) continue;
6296
6321
  if (isConditionalUnlink(mutation)) {
6297
6322
  unlinksAfterWrite = true;
6298
6323
  continue;
6299
6324
  }
6300
- for (const column of localColumnsOf(t.context.contract, model, relationMutation.relation)) nullColumns[column] = null;
6301
- } else keys.push(...addParentOwned(t, model, relationMutation, mutation));
6325
+ for (const column of localColumnsOf(b.context.contract, model, relationMutation.relation)) nullColumns[column] = null;
6326
+ } else keys.push(...addParentOwned(b, model, parent, relationMutation, mutation));
6302
6327
  }
6303
6328
  return {
6304
6329
  keys,
@@ -6306,14 +6331,25 @@ function addBeforeWrite(t, model, relationMutations) {
6306
6331
  unlinksAfterWrite
6307
6332
  };
6308
6333
  }
6309
- function addAfterWrite(t, model, parent, relationMutations) {
6334
+ function addAfterWrite(b, model, parent, relationMutations) {
6310
6335
  const { parentOwned, childOwned, junctionOwned } = partitionByOwnership(relationMutations);
6311
- for (const relationMutation of parentOwned) for (const mutation of relationMutation.mutations) if (mutation.kind === "disconnect" && !disconnectsNothing(mutation) && isConditionalUnlink(mutation)) addConditionalUnlink(t, model, parent, relationMutation, mutation);
6312
- for (const relationMutation of childOwned) for (const mutation of relationMutation.mutations) addChildOwned(t, model, parent, relationMutation, mutation);
6313
- for (const relationMutation of junctionOwned) for (const mutation of relationMutation.mutations) addJunctionOwned(t, model, parent, relationMutation, mutation);
6336
+ for (const relationMutation of parentOwned) for (const mutation of relationMutation.mutations) if (mutation.kind === "disconnect" && !disconnectsNothing(mutation) && isConditionalUnlink(mutation)) addConditionalUnlink(b, model, parent, relationMutation, mutation);
6337
+ else if (mutation.kind === "update" || mutation.kind === "delete") addLinkedRowWrite(b, model, parent, relationMutation, mutation);
6338
+ for (const relationMutation of childOwned) for (const mutation of relationMutation.mutations) addChildOwned(b, model, parent, relationMutation, mutation);
6339
+ for (const relationMutation of junctionOwned) for (const mutation of relationMutation.mutations) addJunctionOwned(b, model, parent, relationMutation, mutation);
6340
+ }
6341
+ function rejectForeignKeyWithRelationMutation(data, relationMutations) {
6342
+ for (const { name, relation } of partitionByOwnership(relationMutations).parentOwned) {
6343
+ const fields = relation.on.localFields.filter((field) => Object.hasOwn(data, field) && data[field] !== void 0);
6344
+ if (fields.length > 0) throw ormError("ORM.ARGUMENT_INVALID", `update() data sets ${fields.map((field) => `"${field}"`).join(", ")}, the foreign key of relation "${name}", and also has a callback on "${name}"; set the foreign key or use the callback`, { meta: {
6345
+ relation: name,
6346
+ problem: "foreign-key-with-relation-mutation",
6347
+ fields
6348
+ } });
6349
+ }
6314
6350
  }
6315
6351
  function rejectUpdateOnly({ name, mutations }) {
6316
- for (const { kind } of mutations) if (kind === "disconnect" || kind === "updateAll" || kind === "deleteAll") throw ormError("ORM.OPERATION_UNSUPPORTED", `${kind}() is only supported in update() nested mutations`, { meta: {
6352
+ for (const { kind } of mutations) if (kind !== "create" && kind !== "connect") throw ormError("ORM.OPERATION_UNSUPPORTED", `${kind}() is only supported in update() nested mutations`, { meta: {
6317
6353
  kind,
6318
6354
  relation: name
6319
6355
  } });
@@ -6324,8 +6360,8 @@ function isConditionalUnlink(mutation) {
6324
6360
  function disconnectsNothing(mutation) {
6325
6361
  return mutation.criteria !== void 0 && mutation.criteria.length === 0;
6326
6362
  }
6327
- function addConditionalUnlink(t, model, parent, { name, relation }, mutation) {
6328
- const { context } = t;
6363
+ function addConditionalUnlink(b, model, parent, { name, relation }, mutation) {
6364
+ const { context } = b;
6329
6365
  const { contract } = context;
6330
6366
  const related = relatedModel(contract, relation, mutation.state);
6331
6367
  const localColumns = localColumnsOf(contract, model, relation);
@@ -6339,16 +6375,16 @@ function addConditionalUnlink(t, model, parent, { name, relation }, mutation) {
6339
6375
  const unlink = {
6340
6376
  ...nulls,
6341
6377
  ...updateDefaultsOf(context, model, {
6342
- ...t.parentValues,
6378
+ ...parent.setValues,
6343
6379
  ...nulls
6344
6380
  })
6345
6381
  };
6346
6382
  for (const where of wheres) {
6347
6383
  const target = SelectAst.from(related.tables.root.tableSource(contract)).withProjection(targets);
6348
- updateRows(t, model, unlink, {
6384
+ updateRows(b, model, unlink, {
6349
6385
  where: BinaryExpr.in(linked, SubqueryExpr.of(where === void 0 ? target : target.withWhere(where))),
6350
6386
  filters: [{
6351
- from: parent,
6387
+ from: parent.node,
6352
6388
  columns: sameRowColumnsOf(contract, model.tables.root)
6353
6389
  }],
6354
6390
  links: [],
@@ -6379,18 +6415,98 @@ function rejectNullOnRequiredKey(contract, kind, name, holder, keyFields) {
6379
6415
  } });
6380
6416
  }
6381
6417
  function isFilteredWrite(mutation) {
6382
- return mutation.kind === "updateAll" || mutation.kind === "deleteAll";
6418
+ return mutation.kind === "updateAll" || mutation.kind === "deleteAll" || mutation.kind === "update" || mutation.kind === "delete";
6419
+ }
6420
+ function isSingleRowWrite(mutation) {
6421
+ return mutation.kind === "update" || mutation.kind === "delete";
6422
+ }
6423
+ function rejectSingleRowWrite({ name, relation, relatedCollection, mutations }) {
6424
+ for (const mutation of mutations.filter(isSingleRowWrite)) {
6425
+ const { kind } = mutation;
6426
+ const { filters, variantValue } = mutation.state;
6427
+ const related = relatedCollection(relation);
6428
+ const unfiltered = variantValue === void 0 ? related : related.variant(variantValue);
6429
+ if (!isToOneCardinality(relation.cardinality) && filters.length <= unfiltered.state.filters.length) throw ormError("ORM.ARGUMENT_INVALID", `${kind}() nested mutation for relation "${name}" requires where() on a to-many relation`, { meta: {
6430
+ kind,
6431
+ relation: name,
6432
+ problem: "missing-where"
6433
+ } });
6434
+ }
6435
+ }
6436
+ function addLinkedRowWrite(b, model, parent, { relation }, mutation) {
6437
+ const { context } = b;
6438
+ const { contract } = context;
6439
+ const related = {
6440
+ context,
6441
+ state: mutation.state,
6442
+ modelName: relation.to,
6443
+ namespaceId: relation.toNamespace
6444
+ };
6445
+ const localColumns = localColumnsOf(contract, model, relation);
6446
+ const targetColumns = resolveRelationTargetColumns(contract, relation);
6447
+ const target = mutation.state.tables.root;
6448
+ if (mutation.kind === "delete") {
6449
+ addDeleteFirst(b, related, throughUpdatedParent(contract, model, parent, relation, mutation.state.tables), (found) => {
6450
+ const nulls = Object.fromEntries(localColumns.map((column) => [column, null]));
6451
+ updateRows(b, model, {
6452
+ ...nulls,
6453
+ ...updateDefaultsOf(context, model, {
6454
+ ...parent.setValues,
6455
+ ...nulls
6456
+ })
6457
+ }, {
6458
+ where: void 0,
6459
+ filters: [{
6460
+ from: parent.node,
6461
+ columns: sameRowColumnsOf(contract, model.tables.root)
6462
+ }, {
6463
+ from: found,
6464
+ columns: columnMappings(contract, target, targetColumns, model.tables.root, localColumns)
6465
+ }],
6466
+ links: [],
6467
+ payloads: [],
6468
+ owner: {
6469
+ operation: "update",
6470
+ modelName: model.modelName
6471
+ },
6472
+ returns: "count",
6473
+ shape: allColumns,
6474
+ afterWrite: void 0
6475
+ });
6476
+ });
6477
+ return;
6478
+ }
6479
+ const set = updateValuesOf(related, mutation.data);
6480
+ if (Object.keys(set).length > 0) addUpdateFirst(b, related, set, throughUpdatedParent(contract, model, parent, relation, mutation.state.tables));
6481
+ }
6482
+ function throughUpdatedParent(contract, model, parent, relation, { root, scope }) {
6483
+ const parentTable = model.tables.root;
6484
+ const { namespaceId, tableName } = parentTable.storage;
6485
+ const keyColumns = resolveRowIdentityColumns(contract, namespaceId, tableName);
6486
+ const updated = scope.aliasTable({
6487
+ namespaceId,
6488
+ tableName
6489
+ });
6490
+ return {
6491
+ filters: [],
6492
+ links: [{
6493
+ from: parent.node,
6494
+ columns: columnMappings(contract, parentTable, keyColumns, updated, keyColumns),
6495
+ junction: updated.tableSource(contract),
6496
+ targets: columnMappings(contract, updated, localColumnsOf(contract, model, relation), root, resolveRelationTargetColumns(contract, relation))
6497
+ }]
6498
+ };
6383
6499
  }
6384
6500
  function rejectFilteredWriteOnToOne({ name, relation, mutations }) {
6385
- const filtered = mutations.find(isFilteredWrite);
6501
+ const filtered = mutations.find((mutation) => mutation.kind === "updateAll" || mutation.kind === "deleteAll");
6386
6502
  if (filtered !== void 0 && (relation.cardinality === "N:1" || relation.cardinality === "1:1")) throw ormError("ORM.OPERATION_UNSUPPORTED", `${filtered.kind}() nested mutation for relation "${name}" is only supported on to-many relations`, { meta: {
6387
6503
  kind: filtered.kind,
6388
6504
  relation: name,
6389
6505
  reason: "to-one-relation"
6390
6506
  } });
6391
6507
  }
6392
- function addParentOwned(t, model, { name, relation, relatedCollection }, mutation) {
6393
- const { contract } = t.context;
6508
+ function addParentOwned(b, model, parent, { name, relation, relatedCollection }, mutation) {
6509
+ const { contract } = b.context;
6394
6510
  const related = relatedModel(contract, relation, variantOf(mutation));
6395
6511
  const columns = columnMappings(contract, related.tables.root, resolveRelationTargetColumns(contract, relation), model.tables.root, localColumnsOf(contract, model, relation));
6396
6512
  if (mutation.kind === "create") {
@@ -6400,20 +6516,20 @@ function addParentOwned(t, model, { name, relation, relatedCollection }, mutatio
6400
6516
  relation: name,
6401
6517
  problem: "missing-data"
6402
6518
  } });
6403
- const resolved = nestedConflictOf(t, name, relation, mutation);
6519
+ const resolved = nestedConflictOf(b, name, relation, mutation);
6404
6520
  const keys = [];
6405
6521
  const added = (from) => keys.push({
6406
6522
  from,
6407
6523
  columns
6408
6524
  });
6409
- if (addVariantInOwnTable(t, {
6525
+ if (addVariantInOwnTable(b, parent, {
6410
6526
  relation,
6411
6527
  relatedCollection
6412
6528
  }, {
6413
6529
  ...mutation,
6414
6530
  data: [row]
6415
6531
  }, [], added)) return keys;
6416
- addLinkedCreates(t, related, name, relatedCollection, mutation, resolved, [row], added);
6532
+ addLinkedCreates(b, related, parent, name, relatedCollection, mutation, resolved, [row], added);
6417
6533
  return keys;
6418
6534
  }
6419
6535
  const [criterion] = mutation.criteria;
@@ -6423,40 +6539,40 @@ function addParentOwned(t, model, { name, relation, relatedCollection }, mutatio
6423
6539
  problem: "missing-criterion"
6424
6540
  } });
6425
6541
  return [{
6426
- from: addFindAndAssert(t, {
6542
+ from: addFindAndAssert(b, parent, {
6427
6543
  name,
6428
6544
  relation
6429
6545
  }, mutation, criterion, columns),
6430
6546
  columns
6431
6547
  }];
6432
6548
  }
6433
- function addChildOwned(t, model, parent, { name, relation, relatedCollection }, mutation) {
6434
- const { context } = t;
6549
+ function addChildOwned(b, model, parent, { name, relation, relatedCollection }, mutation) {
6550
+ const { context } = b;
6435
6551
  const { contract } = context;
6436
6552
  const related = relatedModel(contract, relation, variantOf(mutation));
6437
6553
  const targetColumns = resolveRelationTargetColumns(contract, relation);
6438
6554
  const fromParent = columnMappings(contract, model.tables.root, localColumnsOf(contract, model, relation), related.tables.root, targetColumns);
6439
6555
  if (isFilteredWrite(mutation)) {
6440
- addFilteredWrite(t, model, parent, name, relation, mutation);
6556
+ addFilteredWrite(b, model, parent, name, relation, mutation);
6441
6557
  return;
6442
6558
  }
6443
6559
  if (mutation.kind === "create") {
6444
6560
  const keys = [{
6445
- from: parent,
6561
+ from: parent.node,
6446
6562
  columns: fromParent
6447
6563
  }];
6448
- const resolved = nestedConflictOf(t, name, relation, mutation);
6449
- if (addVariantInOwnTable(t, {
6564
+ const resolved = nestedConflictOf(b, name, relation, mutation);
6565
+ if (addVariantInOwnTable(b, parent, {
6450
6566
  relation,
6451
6567
  relatedCollection
6452
6568
  }, mutation, keys, () => void 0)) return;
6453
6569
  const variantValue = mutation.variant;
6454
- const rows = mutation.data.map((row) => parseCreateInput(t, related, row, relatedCollection));
6570
+ const rows = mutation.data.map((row) => parseCreateInput(b, related, row, relatedCollection));
6455
6571
  const values = rows.map((row) => createRowOf(context, related, variantValue, row.scalarData, void 0));
6456
- const nested = conflictOf(t, related, name, targetColumns, resolved, rows, values, variantValue);
6572
+ const nested = conflictOf(b, related, name, targetColumns, resolved, rows, values, variantValue);
6457
6573
  if (nested !== void 0 && "link" in nested.conflict || rows.some((row) => row.relationMutations.length > 0)) {
6458
6574
  rows.forEach((row, index) => {
6459
- insertWithRelations(t, related, row, {
6575
+ insertWithRelations(b, related, parent, row, {
6460
6576
  keysFromParent: keys,
6461
6577
  returns: "count",
6462
6578
  shape: allColumns,
@@ -6465,7 +6581,7 @@ function addChildOwned(t, model, parent, { name, relation, relatedCollection },
6465
6581
  });
6466
6582
  return;
6467
6583
  }
6468
- insertRows(t, related, values, {
6584
+ insertRows(b, related, values, {
6469
6585
  conflict: nested?.conflict,
6470
6586
  keys,
6471
6587
  requires: [],
@@ -6480,12 +6596,12 @@ function addChildOwned(t, model, parent, { name, relation, relatedCollection },
6480
6596
  return;
6481
6597
  }
6482
6598
  if (mutation.kind === "connect") {
6483
- for (const criterion of mutation.criteria) updateRows(t, related, {}, {
6599
+ for (const criterion of mutation.criteria) updateRows(b, related, {}, {
6484
6600
  where: requiredCriterion(context, related, name, mutation, criterion),
6485
6601
  filters: [],
6486
6602
  links: [],
6487
6603
  payloads: [{
6488
- from: parent,
6604
+ from: parent.node,
6489
6605
  columns: fromParent
6490
6606
  }],
6491
6607
  owner: {
@@ -6505,10 +6621,10 @@ function addChildOwned(t, model, parent, { name, relation, relatedCollection },
6505
6621
  const unlink = Object.fromEntries(targetColumns.map((column) => [column, null]));
6506
6622
  const { criteria } = mutation;
6507
6623
  const wheres = criteria === void 0 ? [variantWhere(contract, mutation.state, void 0)] : criteria.map((criterion) => requiredCriterion(context, related, name, mutation, criterion));
6508
- for (const where of wheres) updateRows(t, related, unlink, {
6624
+ for (const where of wheres) updateRows(b, related, unlink, {
6509
6625
  where,
6510
6626
  filters: [{
6511
- from: parent,
6627
+ from: parent.node,
6512
6628
  columns: fromParent
6513
6629
  }],
6514
6630
  links: [],
@@ -6522,8 +6638,8 @@ function addChildOwned(t, model, parent, { name, relation, relatedCollection },
6522
6638
  afterWrite: void 0
6523
6639
  });
6524
6640
  }
6525
- function addJunctionOwned(t, model, parent, { name, relation, relatedCollection }, mutation) {
6526
- const { context } = t;
6641
+ function addJunctionOwned(b, model, parent, { name, relation, relatedCollection }, mutation) {
6642
+ const { context } = b;
6527
6643
  const { contract } = context;
6528
6644
  const { through } = relation;
6529
6645
  const related = relatedModel(contract, relation, variantOf(mutation));
@@ -6534,15 +6650,15 @@ function addJunctionOwned(t, model, parent, { name, relation, relatedCollection
6534
6650
  const fromParent = columnMappings(contract, model.tables.root, localColumnsOf(contract, model, relation), junction.root, through.parentColumns);
6535
6651
  const fromTarget = columnMappings(contract, related.tables.root, through.targetColumns, junction.root, through.childColumns);
6536
6652
  if (isFilteredWrite(mutation)) {
6537
- addFilteredWrite(t, model, parent, name, relation, mutation);
6653
+ addFilteredWrite(b, model, parent, name, relation, mutation);
6538
6654
  return;
6539
6655
  }
6540
6656
  const addLink = (target, conflict) => {
6541
6657
  const values = withCreateDefaults(context, through.namespaceId, through.table, {}, void 0);
6542
- addInsert(t, junction.root, [values], {
6658
+ addInsert(b, junction.root, [values], {
6543
6659
  conflict,
6544
6660
  keys: [{
6545
- from: parent,
6661
+ from: parent.node,
6546
6662
  columns: fromParent
6547
6663
  }, {
6548
6664
  from: target,
@@ -6560,18 +6676,18 @@ function addJunctionOwned(t, model, parent, { name, relation, relatedCollection
6560
6676
  });
6561
6677
  };
6562
6678
  if (mutation.kind === "create") {
6563
- const resolved = nestedConflictOf(t, name, relation, mutation);
6564
- if (addVariantInOwnTable(t, {
6679
+ const resolved = nestedConflictOf(b, name, relation, mutation);
6680
+ if (addVariantInOwnTable(b, parent, {
6565
6681
  relation,
6566
6682
  relatedCollection
6567
6683
  }, mutation, [], (base) => addLink(base, void 0))) return;
6568
6684
  const conflict = resolved === void 0 ? void 0 : linkKeyConflict(contract, relation);
6569
- addLinkedCreates(t, related, name, relatedCollection, mutation, resolved, mutation.data, (created) => addLink(created, conflict));
6685
+ addLinkedCreates(b, related, parent, name, relatedCollection, mutation, resolved, mutation.data, (created) => addLink(created, conflict));
6570
6686
  return;
6571
6687
  }
6572
6688
  if (mutation.kind === "connect") {
6573
6689
  const conflict = linkKeyConflict(contract, relation);
6574
- for (const criterion of mutation.criteria) addLink(addFindAndAssert(t, {
6690
+ for (const criterion of mutation.criteria) addLink(addFindAndAssert(b, parent, {
6575
6691
  name,
6576
6692
  relation
6577
6693
  }, mutation, criterion, fromTarget), conflict);
@@ -6584,14 +6700,14 @@ function addJunctionOwned(t, model, parent, { name, relation, relatedCollection
6584
6700
  problem: "missing-criterion"
6585
6701
  } });
6586
6702
  for (const criterion of criteria) {
6587
- const target = addFindAndAssert(t, {
6703
+ const target = addFindAndAssert(b, parent, {
6588
6704
  name,
6589
6705
  relation
6590
6706
  }, mutation, criterion, fromTarget);
6591
- deleteRows(t, junction, {
6707
+ deleteRows(b, junction, {
6592
6708
  where: void 0,
6593
6709
  filters: [{
6594
- from: parent,
6710
+ from: parent.node,
6595
6711
  columns: fromParent
6596
6712
  }, {
6597
6713
  from: target,
@@ -6601,29 +6717,38 @@ function addJunctionOwned(t, model, parent, { name, relation, relatedCollection
6601
6717
  });
6602
6718
  }
6603
6719
  }
6604
- function addFilteredWrite(t, model, parent, name, relation, mutation) {
6720
+ function addFilteredWrite(b, model, parent, name, relation, mutation) {
6605
6721
  const related = {
6606
- context: t.context,
6722
+ context: b.context,
6607
6723
  state: mutation.state,
6608
6724
  modelName: relation.to,
6609
6725
  namespaceId: relation.toNamespace
6610
6726
  };
6611
- const sources = sourcesOf(t.context.contract, model, relation, related.state.tables, parent);
6727
+ const keyFilters = keyFiltersOf(b.context.contract, model, relation, related.state.tables, parent.node);
6612
6728
  if (mutation.kind === "deleteAll") {
6613
- addDeleteAll(t, related, sources);
6729
+ addDeleteAll(b, related, keyFilters);
6730
+ return;
6731
+ }
6732
+ if (mutation.kind === "delete") {
6733
+ addDeleteFirst(b, related, keyFilters);
6614
6734
  return;
6615
6735
  }
6616
6736
  const set = updateValuesOf(related, mutation.data);
6617
- const linking = (relation.through === void 0 ? relation.on.targetFields : []).filter((field) => Object.hasOwn(set, columnOfContractField(t.context.contract, relation.toNamespace, relation.to, field)));
6618
- if (linking.length > 0) throw ormError("ORM.ARGUMENT_INVALID", `updateAll() nested mutation for relation "${name}" cannot set ${linking.map((field) => `"${field}"`).join(", ")}, which links the related rows to their parent`, { meta: {
6619
- kind: "updateAll",
6737
+ const linking = (relation.through === void 0 ? relation.on.targetFields : []).filter((field) => Object.hasOwn(set, columnOfContractField(b.context.contract, relation.toNamespace, relation.to, field)));
6738
+ if (linking.length > 0) throw ormError("ORM.ARGUMENT_INVALID", `${mutation.kind}() nested mutation for relation "${name}" cannot set ${linking.map((field) => `"${field}"`).join(", ")}, which links the related rows to their parent`, { meta: {
6739
+ kind: mutation.kind,
6620
6740
  relation: name,
6621
6741
  problem: "parent-link-column",
6622
6742
  fields: linking
6623
6743
  } });
6624
- if (Object.keys(set).length > 0) addUpdateAll(t, related, set, sources, "count");
6744
+ if (Object.keys(set).length === 0) return;
6745
+ if (mutation.kind === "update") {
6746
+ addUpdateFirst(b, related, set, keyFilters);
6747
+ return;
6748
+ }
6749
+ addUpdateAll(b, related, set, keyFilters, "count");
6625
6750
  }
6626
- function sourcesOf(contract, model, relation, { root, scope }, parent) {
6751
+ function keyFiltersOf(contract, model, relation, { root, scope }, parent) {
6627
6752
  const localColumns = localColumnsOf(contract, model, relation);
6628
6753
  const { through } = relation;
6629
6754
  if (through === void 0) return {
@@ -6670,9 +6795,9 @@ function nestedCall(name, modelName) {
6670
6795
  }
6671
6796
  };
6672
6797
  }
6673
- function nestedConflictOf(t, name, relation, { options, variant }) {
6798
+ function nestedConflictOf(b, name, relation, { options, variant }) {
6674
6799
  if (options === void 0) return;
6675
- const { contract } = t.context;
6800
+ const { contract } = b.context;
6676
6801
  const resolved = resolveConflict(contract, nestedCall(name, relation.to), relation.toNamespace, options, ["skip", "connect"], variantTargetOf(contract, relation, variant));
6677
6802
  if (resolved.onConflict === "skip") {
6678
6803
  const reason = hasThrough(relation) ? "many-to-many-relation" : relation.cardinality === "N:1" || relation.cardinality === "1:1" ? "to-one-relation" : void 0;
@@ -6691,9 +6816,9 @@ function variantTargetOf(contract, relation, variantValue) {
6691
6816
  const value = [...resolvePolymorphismInfo(contract, base.namespace, base.model)?.variants.values() ?? []].find((variant) => variant.modelName === relation.to && variant.namespaceId === relation.toNamespace)?.value;
6692
6817
  return variantInOwnTableOf(contract, base.namespace, base.model, value);
6693
6818
  }
6694
- function conflictOf(t, model, name, parentLinkColumns, resolved, rows, values, variantValue) {
6819
+ function conflictOf(b, model, name, parentLinkColumns, resolved, rows, values, variantValue) {
6695
6820
  if (resolved === void 0) return;
6696
- const { context } = t;
6821
+ const { context } = b;
6697
6822
  const { contract } = context;
6698
6823
  const call = nestedCall(name, model.modelName);
6699
6824
  for (const row of rows) rejectParentHeldInConflictRow(name, resolved.onConflict, row);
@@ -6721,8 +6846,8 @@ function variantGuardOf(contract, { namespaceId, modelName }, variantValue) {
6721
6846
  value: variantValue
6722
6847
  };
6723
6848
  }
6724
- function addFindAndAssert(t, { name, relation }, mutation, criterion, columns) {
6725
- const { graph, context } = t;
6849
+ function addFindAndAssert(b, parent, { name, relation }, mutation, criterion, columns) {
6850
+ const { graph, context } = b;
6726
6851
  const { kind } = mutation;
6727
6852
  const related = relatedModel(context.contract, relation, mutation.state);
6728
6853
  const where = requiredCriterion(context, related, name, mutation, criterion);
@@ -6730,20 +6855,20 @@ function addFindAndAssert(t, { name, relation }, mutation, criterion, columns) {
6730
6855
  ...related,
6731
6856
  tables: createCollectionTables(context.contract, related.namespaceId, related.modelName)
6732
6857
  } : related;
6733
- const find = findRows(t, selectAstOf(context, withVariants, {
6858
+ const find = findRows(b, selectAstOf(context, withVariants, {
6734
6859
  ...emptyState(withVariants.tables),
6735
6860
  filters: [where],
6736
6861
  limit: 1
6737
6862
  }, "selection"), {
6738
6863
  filter: [],
6739
- requires: parentRowRequired(t)
6864
+ requires: parentRowRequired(parent)
6740
6865
  });
6741
6866
  graph.add(new Assert(ormError("ORM.RELATION_ROW_MISSING", `${kind}() nested mutation for relation "${name}" did not find a matching row`, { meta: {
6742
6867
  kind,
6743
6868
  relation: name
6744
6869
  } })), {
6745
6870
  rows: new Rows(find, columns.map(([source]) => [source, source])),
6746
- requires: parentRowRequired(t)
6871
+ requires: parentRowRequired(parent)
6747
6872
  });
6748
6873
  return find;
6749
6874
  }
@@ -6764,8 +6889,8 @@ function variantWhere(contract, variant, where) {
6764
6889
  const { tables, filters, variantValue } = variant;
6765
6890
  return countMutationWhere(contract, tables, where === void 0 ? filters : [...filters, where], variantValue);
6766
6891
  }
6767
- function parentRowRequired(t) {
6768
- return t.parentRow === void 0 ? [] : [new Requires(t.parentRow)];
6892
+ function parentRowRequired({ rowBeforeWrite }) {
6893
+ return rowBeforeWrite === void 0 ? [] : [new Requires(rowBeforeWrite)];
6769
6894
  }
6770
6895
  function criterionWhere(context, model, criterion) {
6771
6896
  return shorthandToWhereExpr(context, model.namespaceId, model.modelName, castAs(criterion), model.tables.root);
@@ -6795,8 +6920,8 @@ function relatedModel(contract, relation, variant) {
6795
6920
  function localColumnsOf(contract, model, relation) {
6796
6921
  return relation.on.localFields.map((field) => columnOfContractField(contract, model.namespaceId, model.modelName, field));
6797
6922
  }
6798
- function parseCreateInput(t, model, row, relatedCollection) {
6799
- return parseMutationInput(t.context.contract, model.namespaceId, model.modelName, row, relatedCollection);
6923
+ function parseCreateInput(b, model, row, relatedCollection) {
6924
+ return parseMutationInput(b.context.contract, model.namespaceId, model.modelName, row, relatedCollection);
6800
6925
  }
6801
6926
  function columnMappings(contract, from, fromColumns, to, toColumns) {
6802
6927
  return fromColumns.map((column, index) => [projectTableColumn(contract, from, column), projectTableColumn(contract, to, blindCast(toColumns[index]))]);
@@ -6882,13 +7007,61 @@ function deleteAllGraph(collection, returns) {
6882
7007
  });
6883
7008
  return b.graph;
6884
7009
  }
6885
- function addDeleteAll(b, collection, sources) {
7010
+ function addDeleteAll(b, collection, keyFilters) {
6886
7011
  return deleteRows(b, collection.state.tables, {
6887
7012
  where: whereOf(collection),
6888
- ...sources
7013
+ ...keyFilters
7014
+ });
7015
+ }
7016
+ function addUpdateFirst(b, collection, set, keyFilters) {
7017
+ const find = addFindOfFirstRelated(b, collection, "update()", keyFilters);
7018
+ updateRows(b, modelOf(collection), set, {
7019
+ where: whereOf(collection),
7020
+ filters: [{
7021
+ from: find,
7022
+ columns: sameRowColumns(collection)
7023
+ }, ...keyFilters.filters],
7024
+ links: keyFilters.links,
7025
+ payloads: [],
7026
+ owner: {
7027
+ operation: "update",
7028
+ modelName: collection.modelName
7029
+ },
7030
+ returns: "count",
7031
+ shape: shapeOf(collection),
7032
+ afterWrite: void 0
7033
+ });
7034
+ }
7035
+ function addDeleteFirst(b, collection, keyFilters, unlinkFound) {
7036
+ const find = addFindOfFirstRelated(b, collection, "delete()", keyFilters);
7037
+ unlinkFound?.(find);
7038
+ const byFoundKey = [{
7039
+ from: find,
7040
+ columns: sameRowColumns(collection)
7041
+ }];
7042
+ deleteRows(b, collection.state.tables, unlinkFound === void 0 ? {
7043
+ where: whereOf(collection),
7044
+ filters: [...byFoundKey, ...keyFilters.filters],
7045
+ links: keyFilters.links
7046
+ } : {
7047
+ where: void 0,
7048
+ filters: byFoundKey,
7049
+ links: []
7050
+ });
7051
+ }
7052
+ function addFindOfFirstRelated(b, collection, method, { filters, links }) {
7053
+ requireIdentityColumns(collection, method);
7054
+ return findRows(b, selectIdentityAst(collection, {
7055
+ ...collection.state,
7056
+ limit: 1
7057
+ }), {
7058
+ filter: filters.map(({ from, columns }) => new FilterData(from, columns)),
7059
+ requires: [],
7060
+ links
6889
7061
  });
6890
7062
  }
6891
7063
  function updateFirstGraph(collection, data, relationMutations = []) {
7064
+ rejectForeignKeyWithRelationMutation(data, relationMutations);
6892
7065
  const { state } = collection;
6893
7066
  const b = builderOf(collection);
6894
7067
  const set = mappedUpdateRow(collection, data);
@@ -6905,19 +7078,21 @@ function updateFirstGraph(collection, data, relationMutations = []) {
6905
7078
  return b.graph;
6906
7079
  }
6907
7080
  const model = modelOf(collection);
6908
- const t = {
6909
- ...b,
6910
- parentRow: find,
6911
- parentValues: set
7081
+ const parent = {
7082
+ rowBeforeWrite: find,
7083
+ setValues: set
6912
7084
  };
6913
- const before = addBeforeWrite(t, model, relationMutations);
7085
+ const before = addBeforeWrite(b, model, parent, relationMutations);
6914
7086
  const values = withUpdateDefaults(collection, set, before);
6915
7087
  const owner = {
6916
7088
  operation: "update",
6917
7089
  modelName: collection.modelName
6918
7090
  };
6919
7091
  if (Object.keys(values).length === 0 && before.keys.length === 0) {
6920
- addAfterWrite(t, model, find, relationMutations);
7092
+ addAfterWrite(b, model, {
7093
+ ...parent,
7094
+ node: find
7095
+ }, relationMutations);
6921
7096
  b.graph.setResult(state.includes.length === 0 && !before.unlinksAfterWrite ? find : readBack(b, model, find, identityColumnsOf(collection), {
6922
7097
  shape: shapeOf(collection),
6923
7098
  by: "filter",
@@ -6936,7 +7111,10 @@ function updateFirstGraph(collection, data, relationMutations = []) {
6936
7111
  owner,
6937
7112
  returns: "rows",
6938
7113
  shape: shapeOf(collection),
6939
- afterWrite: (updated) => addAfterWrite(t, model, updated, relationMutations)
7114
+ afterWrite: (updated) => addAfterWrite(b, model, {
7115
+ ...parent,
7116
+ node: updated
7117
+ }, relationMutations)
6940
7118
  }));
6941
7119
  return b.graph;
6942
7120
  }
@@ -6995,11 +7173,10 @@ function createAllGraph(collection, data, conflict, returns) {
6995
7173
  function createGraph(collection, parsed) {
6996
7174
  const b = builderOf(collection);
6997
7175
  requireIdentityColumnsForIncludes(collection);
6998
- b.graph.setResult(addCreateWithRelations({
6999
- ...b,
7000
- parentRow: void 0,
7001
- parentValues: {}
7002
- }, modelOf(collection), parsed, {
7176
+ b.graph.setResult(addCreateWithRelations(b, modelOf(collection), {
7177
+ rowBeforeWrite: void 0,
7178
+ setValues: {}
7179
+ }, parsed, {
7003
7180
  keysFromParent: [],
7004
7181
  returns: "rows",
7005
7182
  shape: shapeOf(collection),