@prisma/orm-family-sql 8.0.0-rc.25-dev.5 → 8.0.0-rc.25-dev.6

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.
@@ -4836,6 +4836,8 @@ function requireRowsThatCanConflict(contract, call, { namespaceId, tableName },
4836
4836
  return keys;
4837
4837
  }
4838
4838
  var Node = class {
4839
+ /** Set by `DeletedRows` only: the caller's hidden columns are computed from this slot's source, whose rows it returns a subset of. */
4840
+ passesRowsOf = void 0;
4839
4841
  checkIfCanRun(_graph, _id, _context) {}
4840
4842
  };
4841
4843
  function executeStatement$1(ast, run) {
@@ -4866,6 +4868,57 @@ var CrossJoin = class extends Node {
4866
4868
  }]);
4867
4869
  }
4868
4870
  };
4871
+ /** The string a `Map` keys a decoded row identity by: equal decoded keys give equal strings. */
4872
+ function stitchKey(parts) {
4873
+ const [only, ...others] = parts;
4874
+ if (others.length === 0) return partText(only);
4875
+ return JSON.stringify(parts.map(partText));
4876
+ }
4877
+ function partText(value) {
4878
+ if (typeof value === "string") return value;
4879
+ if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") return String(value);
4880
+ if (value instanceof Uint8Array) return Array.from(value, (byte) => byte.toString(16).padStart(2, "0")).join("");
4881
+ if (value instanceof Date) return value.toISOString();
4882
+ if (isTemporal(value)) return String(value);
4883
+ throw ormError("ORM.ROW_IDENTITY_MISSING", `An include matches child rows to their parents by key, and a key value of kind "${kindOf(value)}" cannot be matched. Key a relation by columns that decode to a number, string, bigint, boolean, byte array, date or Temporal value.`, { meta: { kind: kindOf(value) } });
4884
+ }
4885
+ function isTemporal(value) {
4886
+ return typeof value === "object" && value !== null && String(Reflect.get(value, Symbol.toStringTag)).startsWith("Temporal.");
4887
+ }
4888
+ function kindOf(value) {
4889
+ if (value === null) return "null";
4890
+ if (Array.isArray(value)) return "array";
4891
+ return typeof value;
4892
+ }
4893
+ /** The found rows that the delete removed, matched by `identity`, with the values the delete returned. */
4894
+ var DeletedRows = class extends Node {
4895
+ slots = {
4896
+ found: "one",
4897
+ deleted: "one"
4898
+ };
4899
+ passesRowsOf = "found";
4900
+ identity;
4901
+ constructor(identity) {
4902
+ super();
4903
+ this.identity = Object.freeze([...identity]);
4904
+ Object.freeze(this);
4905
+ }
4906
+ execute(inputs, _run) {
4907
+ const deleted = new Map(inputs.deleted.map((row) => [this.#keyOf(row), row]));
4908
+ return rowsResult(inputs.found.flatMap((row) => {
4909
+ const missing = this.identity.filter((column) => !Object.hasOwn(row, column));
4910
+ invariant(missing.length === 0, `a row read before a Delete lacks identity column(s) ${missing.join(", ")}; the Delete's key edge from the Find makes the Find return them`);
4911
+ const removed = deleted.get(this.#keyOf(row));
4912
+ return removed === void 0 ? [] : [{
4913
+ ...row,
4914
+ ...removed
4915
+ }];
4916
+ }));
4917
+ }
4918
+ #keyOf(row) {
4919
+ return stitchKey(this.identity.map((column) => row[column]));
4920
+ }
4921
+ };
4869
4922
  var Edge = class {
4870
4923
  from;
4871
4924
  constructor(from) {
@@ -4901,74 +4954,6 @@ var FilterData = class extends DataEdge {
4901
4954
  };
4902
4955
  }
4903
4956
  };
4904
- function storageOf(source) {
4905
- return {
4906
- namespaceId: blindCast(source.namespaceId),
4907
- tableName: source.name
4908
- };
4909
- }
4910
- function tableKey(table) {
4911
- return JSON.stringify([table.namespaceId, table.tableName]);
4912
- }
4913
- function changedBy(contract, write, table) {
4914
- if (write === "insert") return [table];
4915
- return cachedFor(contract, [
4916
- "changedBy",
4917
- write,
4918
- table.namespaceId,
4919
- table.tableName
4920
- ], () => {
4921
- const changed = /* @__PURE__ */ new Map([[tableKey(table), table]]);
4922
- const visited = /* @__PURE__ */ new Set([stepKey({
4923
- table,
4924
- kind: write
4925
- })]);
4926
- const pending = [{
4927
- table,
4928
- kind: write
4929
- }];
4930
- for (let step = pending.shift(); step !== void 0; step = pending.shift()) for (const reference of referencesTo(contract, step.table)) {
4931
- const next = nextStep(step.kind, reference);
4932
- if (next !== void 0 && !visited.has(stepKey(next))) {
4933
- visited.add(stepKey(next));
4934
- changed.set(tableKey(next.table), next.table);
4935
- pending.push(next);
4936
- }
4937
- }
4938
- return Object.freeze([...changed.values()]);
4939
- });
4940
- }
4941
- function referencesTo(contract, target) {
4942
- 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) => ({
4943
- table: {
4944
- namespaceId,
4945
- tableName
4946
- },
4947
- onDelete: foreignKey.onDelete,
4948
- onUpdate: foreignKey.onUpdate
4949
- }))));
4950
- }
4951
- function nextStep(kind, reference) {
4952
- switch (kind === "delete" ? reference.onDelete : reference.onUpdate) {
4953
- case "cascade": return {
4954
- table: reference.table,
4955
- kind
4956
- };
4957
- case "setNull":
4958
- case "setDefault": return {
4959
- table: reference.table,
4960
- kind: "update"
4961
- };
4962
- default: return;
4963
- }
4964
- }
4965
- function stepKey(step) {
4966
- return JSON.stringify([
4967
- step.kind,
4968
- step.table.namespaceId,
4969
- step.table.tableName
4970
- ]);
4971
- }
4972
4957
  var Requires = class extends Edge {
4973
4958
  constructor(from) {
4974
4959
  super(from);
@@ -5042,6 +5027,74 @@ var Find = class Find extends StatementNode {
5042
5027
  return new Find(this.ast.withProjection(withColumns(this.returns, columns)));
5043
5028
  }
5044
5029
  };
5030
+ function storageOf(source) {
5031
+ return {
5032
+ namespaceId: blindCast(source.namespaceId),
5033
+ tableName: source.name
5034
+ };
5035
+ }
5036
+ function tableKey(table) {
5037
+ return JSON.stringify([table.namespaceId, table.tableName]);
5038
+ }
5039
+ function changedBy(contract, write, table) {
5040
+ if (write === "insert") return [table];
5041
+ return cachedFor(contract, [
5042
+ "changedBy",
5043
+ write,
5044
+ table.namespaceId,
5045
+ table.tableName
5046
+ ], () => {
5047
+ const changed = /* @__PURE__ */ new Map([[tableKey(table), table]]);
5048
+ const visited = /* @__PURE__ */ new Set([stepKey({
5049
+ table,
5050
+ kind: write
5051
+ })]);
5052
+ const pending = [{
5053
+ table,
5054
+ kind: write
5055
+ }];
5056
+ for (let step = pending.shift(); step !== void 0; step = pending.shift()) for (const reference of referencesTo(contract, step.table)) {
5057
+ const next = nextStep(step.kind, reference);
5058
+ if (next !== void 0 && !visited.has(stepKey(next))) {
5059
+ visited.add(stepKey(next));
5060
+ changed.set(tableKey(next.table), next.table);
5061
+ pending.push(next);
5062
+ }
5063
+ }
5064
+ return Object.freeze([...changed.values()]);
5065
+ });
5066
+ }
5067
+ function referencesTo(contract, target) {
5068
+ 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) => ({
5069
+ table: {
5070
+ namespaceId,
5071
+ tableName
5072
+ },
5073
+ onDelete: foreignKey.onDelete,
5074
+ onUpdate: foreignKey.onUpdate
5075
+ }))));
5076
+ }
5077
+ function nextStep(kind, reference) {
5078
+ switch (kind === "delete" ? reference.onDelete : reference.onUpdate) {
5079
+ case "cascade": return {
5080
+ table: reference.table,
5081
+ kind
5082
+ };
5083
+ case "setNull":
5084
+ case "setDefault": return {
5085
+ table: reference.table,
5086
+ kind: "update"
5087
+ };
5088
+ default: return;
5089
+ }
5090
+ }
5091
+ function stepKey(step) {
5092
+ return JSON.stringify([
5093
+ step.kind,
5094
+ step.table.namespaceId,
5095
+ step.table.tableName
5096
+ ]);
5097
+ }
5045
5098
  const encoder = new TextEncoder();
5046
5099
  /** 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. */
5047
5100
  function chunkKeys(keys, limits) {
@@ -5193,6 +5246,7 @@ function readsTableAsFound(graph, inputs, { id, find }, table) {
5193
5246
  const found = stateEdgeOf([graph.inputsOf(id)["state"] ?? []].flat(), table);
5194
5247
  return read !== void 0 && sameTable(read, table) && own !== void 0 && own.from === found?.from;
5195
5248
  }
5249
+ /** A builder marks a write's condition as its `Find`'s by giving both the same object; equal but separate conditions are not merged. */
5196
5250
  function foldsIntoCondition(graph, { id, find }, where) {
5197
5251
  const { filter, link, requires } = graph.inputsOf(id);
5198
5252
  return find.ast.where === where && rowsOfConditionReadOf(find.ast) !== void 0 && [
@@ -5710,28 +5764,6 @@ function writeOf(ast) {
5710
5764
  case "select": return;
5711
5765
  }
5712
5766
  }
5713
- /** The string a `Map` keys a decoded row identity by: equal decoded keys give equal strings. */
5714
- function stitchKey(parts) {
5715
- const [only, ...others] = parts;
5716
- if (others.length === 0) return partText(only);
5717
- return JSON.stringify(parts.map(partText));
5718
- }
5719
- function partText(value) {
5720
- if (typeof value === "string") return value;
5721
- if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") return String(value);
5722
- if (value instanceof Uint8Array) return Array.from(value, (byte) => byte.toString(16).padStart(2, "0")).join("");
5723
- if (value instanceof Date) return value.toISOString();
5724
- if (isTemporal(value)) return String(value);
5725
- throw ormError("ORM.ROW_IDENTITY_MISSING", `An include matches child rows to their parents by key, and a key value of kind "${kindOf(value)}" cannot be matched. Key a relation by columns that decode to a number, string, bigint, boolean, byte array, date or Temporal value.`, { meta: { kind: kindOf(value) } });
5726
- }
5727
- function isTemporal(value) {
5728
- return typeof value === "object" && value !== null && String(Reflect.get(value, Symbol.toStringTag)).startsWith("Temporal.");
5729
- }
5730
- function kindOf(value) {
5731
- if (value === null) return "null";
5732
- if (Array.isArray(value)) return "array";
5733
- return typeof value;
5734
- }
5735
5767
  const RELATED_KEY_LIMITS = {
5736
5768
  parameters: 1e4,
5737
5769
  bytes: 1024 * 1024
@@ -6729,7 +6761,7 @@ function addFilteredWrite(b, model, parent, name, relation, mutation) {
6729
6761
  };
6730
6762
  const keyFilters = keyFiltersOf(b.context.contract, model, relation, related.state.tables, parent.node);
6731
6763
  if (mutation.kind === "deleteAll") {
6732
- addDeleteAll(b, related, keyFilters);
6764
+ addDeleteAll(b, related, keyFilters, whereOf(related));
6733
6765
  return;
6734
6766
  }
6735
6767
  if (mutation.kind === "delete") {
@@ -6749,7 +6781,7 @@ function addFilteredWrite(b, model, parent, name, relation, mutation) {
6749
6781
  addUpdateFirst(b, related, set, keyFilters);
6750
6782
  return;
6751
6783
  }
6752
- addUpdateAll(b, related, set, keyFilters, "count");
6784
+ addUpdateAll(b, related, set, keyFilters, "count", whereOf(related));
6753
6785
  }
6754
6786
  function keyFiltersOf(contract, model, relation, { root, scope }, parent) {
6755
6787
  const localColumns = localColumnsOf(contract, model, relation);
@@ -6971,12 +7003,12 @@ function updateAllGraph(collection, set, returns) {
6971
7003
  b.graph.setResult(addUpdateAll(b, collection, set, {
6972
7004
  filters: keys,
6973
7005
  links: []
6974
- }, returns));
7006
+ }, returns, where));
6975
7007
  return b.graph;
6976
7008
  }
6977
- function addUpdateAll(b, collection, set, { filters, links }, returns) {
7009
+ function addUpdateAll(b, collection, set, { filters, links }, returns, where) {
6978
7010
  return updateRows(b, modelOf(collection), set, {
6979
- where: whereOf(collection),
7011
+ where,
6980
7012
  filters,
6981
7013
  links,
6982
7014
  payloads: [],
@@ -6996,23 +7028,36 @@ function deleteAllGraph(collection, returns) {
6996
7028
  b.graph.setResult(addDeleteAll(b, collection, {
6997
7029
  filters: [],
6998
7030
  links: []
6999
- }));
7031
+ }, whereOf(collection)));
7000
7032
  return b.graph;
7001
7033
  }
7002
- const find = findRows(b, selectRowsAst(collection, state).withWhere(whereOf(collection)), noInputs);
7003
- b.graph.setResult(withIncludeNodes(b, collection, find));
7004
- addDeleteAll(b, collection, {
7005
- filters: identityColumnsOf(collection).length > 0 ? [{
7006
- from: find,
7007
- columns: sameRowColumns(collection)
7008
- }] : [],
7009
- links: []
7034
+ const where = whereOf(collection);
7035
+ const find = findRows(b, selectRowsAst(collection, state).withWhere(where), noInputs);
7036
+ const read = withIncludeNodes(b, collection, find);
7037
+ b.graph.setResult(read);
7038
+ if (identityColumnsOf(collection).length === 0) {
7039
+ addDeleteAll(b, collection, {
7040
+ filters: [],
7041
+ links: []
7042
+ }, where);
7043
+ return b.graph;
7044
+ }
7045
+ keepRowsTheDeleteRemoved(b, collection, {
7046
+ find,
7047
+ read,
7048
+ deleted: addDeleteAll(b, collection, {
7049
+ filters: [{
7050
+ from: find,
7051
+ columns: sameRowColumns(collection)
7052
+ }],
7053
+ links: []
7054
+ }, where)
7010
7055
  });
7011
7056
  return b.graph;
7012
7057
  }
7013
- function addDeleteAll(b, collection, keyFilters) {
7058
+ function addDeleteAll(b, collection, keyFilters, where) {
7014
7059
  return deleteRows(b, collection.state.tables, {
7015
- where: whereOf(collection),
7060
+ where,
7016
7061
  ...keyFilters
7017
7062
  });
7018
7063
  }
@@ -7128,17 +7173,37 @@ function deleteFirstGraph(collection) {
7128
7173
  const first = addFindOfFirstRow(b, collection, selectRowsAst);
7129
7174
  if (first === void 0) return b.graph;
7130
7175
  const { find, where } = first;
7131
- b.graph.setResult(withIncludeNodes(b, collection, find));
7132
- deleteRows(b, state.tables, {
7133
- where,
7134
- filters: [{
7135
- from: find,
7136
- columns: sameRowColumns(collection)
7137
- }],
7138
- links: []
7176
+ const read = withIncludeNodes(b, collection, find);
7177
+ b.graph.setResult(read);
7178
+ keepRowsTheDeleteRemoved(b, collection, {
7179
+ find,
7180
+ read,
7181
+ deleted: deleteRows(b, state.tables, {
7182
+ where,
7183
+ filters: [{
7184
+ from: find,
7185
+ columns: sameRowColumns(collection)
7186
+ }],
7187
+ links: []
7188
+ })
7139
7189
  });
7140
7190
  return b.graph;
7141
7191
  }
7192
+ /** On a database with `RETURNING`, unless the delete took the place of the read, keeps only the rows read that the delete removed, with the values it returned. */
7193
+ function keepRowsTheDeleteRemoved(b, collection, { find, read, deleted }) {
7194
+ const { graph } = b;
7195
+ if (graph.result === deleted || !hasContractCapability(collection.context.contract, "returning")) return;
7196
+ const found = graph.nodeAt(find);
7197
+ if (!(found instanceof Find)) throw new InternalError(`node ${find} read the rows a Delete removes, and is not a Find`);
7198
+ const { alias } = collection.state.tables.root;
7199
+ const identity = sameRowColumns(collection);
7200
+ const columns = new Map(identity.map((mapping) => [mapping[0].alias, mapping]));
7201
+ for (const item of found.ast.projection) if (item.expr.kind === "column-ref" && item.expr.table === alias && !columns.has(item.alias)) columns.set(item.alias, [item, item]);
7202
+ graph.setResult(graph.add(new DeletedRows(identity.map(([column]) => column.alias)), {
7203
+ found: new WholeRows(read),
7204
+ deleted: new Rows(deleted, [...columns.values()])
7205
+ }));
7206
+ }
7142
7207
  function createAllGraph(collection, data, conflict, returns) {
7143
7208
  const b = builderOf(collection);
7144
7209
  if (data.length === 0) return b.graph;
@@ -7434,15 +7499,24 @@ function runOn(ctx, scope) {
7434
7499
  function shapeRows(graph, id, storageRows, callerRows) {
7435
7500
  const { context, namespaceId, modelName, state } = callerRows;
7436
7501
  const { contract } = context;
7437
- if (loadsIncludesPerRelation(contract, state.includes)) return consumeRowsWithAttachedIncludes(callerRows, storageRows, hiddenColumnsOf(graph, id, state));
7502
+ const read = rowsReadAt(graph, id);
7503
+ if (loadsIncludesPerRelation(contract, state.includes)) return consumeRowsWithAttachedIncludes(callerRows, storageRows, hiddenColumnsOf(graph, read, state));
7438
7504
  const { tableName } = state.tables.root.storage;
7439
7505
  const selected = state.selectedFields ?? getColumnsReadOnTable(contract, namespaceId, modelName, tableName);
7440
- const hiddenColumns = graph.columnsReadFrom(id).map((column) => column.alias).filter((column) => !selected.includes(column));
7506
+ const hiddenColumns = graph.columnsReadFrom(read).map((column) => column.alias).filter((column) => !selected.includes(column));
7441
7507
  return mapResultRows(consumeCollectionRows(callerRows, storageRows), (row) => {
7442
7508
  stripHiddenMappedFields(contract, namespaceId, modelName, row, hiddenColumns);
7443
7509
  return blindCast(row);
7444
7510
  });
7445
7511
  }
7512
+ /** The node whose rows reach `id`: followed through every node that passes on the rows of one input. */
7513
+ function rowsReadAt(graph, id) {
7514
+ const slot = graph.nodeAt(id)?.passesRowsOf;
7515
+ if (slot === void 0) return id;
7516
+ const [edge, ...others] = [graph.inputsOf(id)[slot] ?? []].flat();
7517
+ if (edge === void 0 || others.length > 0) throw new InternalError(`node ${id} passes on the rows of slot "${slot}", which holds no single edge`);
7518
+ return rowsReadAt(graph, edge.from);
7519
+ }
7446
7520
  function statementNodes(graph) {
7447
7521
  return graph.nodes().filter(([, node]) => node instanceof StatementNode);
7448
7522
  }