@prisma/orm-family-sql 8.0.0-rc.22-dev.7 → 8.0.0-rc.22-dev.9

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 (47) hide show
  1. package/dist/{canonicalization-hooks-Ce1v_TDl.mjs → canonicalization-hooks-BeJHD713.mjs} +18 -1
  2. package/dist/canonicalization-hooks-BeJHD713.mjs.map +1 -0
  3. package/dist/{check-expressions-DuWjvG4h.d.mts → check-expressions-Bh5KC2X5.d.mts} +8 -2
  4. package/dist/{check-expressions-DuWjvG4h.d.mts.map → check-expressions-Bh5KC2X5.d.mts.map} +1 -1
  5. package/dist/{check-expressions-BDsLvzqN.mjs → check-expressions-Mmzgx0XE.mjs} +4 -3
  6. package/dist/check-expressions-Mmzgx0XE.mjs.map +1 -0
  7. package/dist/{config-types-BCXwEBZH.mjs → config-types-YRGsoUT7.mjs} +2 -2
  8. package/dist/{config-types-BCXwEBZH.mjs.map → config-types-YRGsoUT7.mjs.map} +1 -1
  9. package/dist/{contract-builder-Y2rB4xMf.mjs → contract-builder-BwPOolrg.mjs} +2 -2
  10. package/dist/{contract-builder-Y2rB4xMf.mjs.map → contract-builder-BwPOolrg.mjs.map} +1 -1
  11. package/dist/contract-prisma7__provider.mjs +4 -4
  12. package/dist/contract-psl.mjs +1 -1
  13. package/dist/contract-psl__attribute-specs.mjs +1 -1
  14. package/dist/contract-psl__provider.mjs +2 -2
  15. package/dist/contract-ts.mjs +3 -3
  16. package/dist/contract-ts__config-types.mjs +1 -1
  17. package/dist/contract-ts__contract-builder.mjs +2 -2
  18. package/dist/contract.d.mts +2 -2
  19. package/dist/contract.mjs +3 -3
  20. package/dist/contract__canonicalization-hooks.mjs +1 -1
  21. package/dist/contract__check-expressions.d.mts +2 -2
  22. package/dist/contract__check-expressions.mjs +2 -2
  23. package/dist/{control-CdumaQYh.d.mts → control-CyJM0mMS.d.mts} +372 -26
  24. package/dist/control-CyJM0mMS.d.mts.map +1 -0
  25. package/dist/{control-BSX7UWk2.mjs → control-Ltpja41u.mjs} +1159 -59
  26. package/dist/control-Ltpja41u.mjs.map +1 -0
  27. package/dist/{derived-checks-D__agoFB-Boa1MHcA.mjs → derived-checks-D__agoFB-DxuPwZ7v.mjs} +3 -3
  28. package/dist/{derived-checks-D__agoFB-Boa1MHcA.mjs.map → derived-checks-D__agoFB-DxuPwZ7v.mjs.map} +1 -1
  29. package/dist/family.d.mts +2 -2
  30. package/dist/family.mjs +4 -4
  31. package/dist/family__control.d.mts +2 -2
  32. package/dist/family__control.mjs +2 -2
  33. package/dist/family__ir.mjs +1 -1
  34. package/dist/family__pack.mjs +2 -2
  35. package/dist/{generator-functions-Hy4pDDr9-HEQuSSaK.mjs → generator-functions-Hy4pDDr9-DlmTbI_c.mjs} +2 -2
  36. package/dist/{generator-functions-Hy4pDDr9-HEQuSSaK.mjs.map → generator-functions-Hy4pDDr9-DlmTbI_c.mjs.map} +1 -1
  37. package/dist/{interpreter-Ct1zWXKw-CRkWwRAw.mjs → interpreter-Ct1zWXKw-CLQnlWhR.mjs} +4 -4
  38. package/dist/{interpreter-Ct1zWXKw-CRkWwRAw.mjs.map → interpreter-Ct1zWXKw-CLQnlWhR.mjs.map} +1 -1
  39. package/dist/{psl-field-resolution-BnusQmZy-CX0b0mPk.mjs → psl-field-resolution-BnusQmZy-_QYc6Ywf.mjs} +2 -2
  40. package/dist/{psl-field-resolution-BnusQmZy-CX0b0mPk.mjs.map → psl-field-resolution-BnusQmZy-_QYc6Ywf.mjs.map} +1 -1
  41. package/dist/{sql-contract-serializer-sMY3prTx-CBHrlt9O.mjs → sql-contract-serializer-sMY3prTx-BfYfhVR_.mjs} +2 -2
  42. package/dist/{sql-contract-serializer-sMY3prTx-CBHrlt9O.mjs.map → sql-contract-serializer-sMY3prTx-BfYfhVR_.mjs.map} +1 -1
  43. package/package.json +18 -18
  44. package/dist/canonicalization-hooks-Ce1v_TDl.mjs.map +0 -1
  45. package/dist/check-expressions-BDsLvzqN.mjs.map +0 -1
  46. package/dist/control-BSX7UWk2.mjs.map +0 -1
  47. package/dist/control-CdumaQYh.d.mts.map +0 -1
@@ -1,32 +1,36 @@
1
1
  import { d as namingOf } from "./naming-DEpT6Zad-C9PFkWt6.mjs";
2
- import { t as sqlContractCanonicalizationHooks } from "./canonicalization-hooks-Ce1v_TDl.mjs";
2
+ import { t as sqlContractCanonicalizationHooks } from "./canonicalization-hooks-BeJHD713.mjs";
3
+ import { n as declaredJsonType } from "./codec-json-type-DUWyBtJk-BVTavkH0.mjs";
4
+ import { n as isStorageValueSet } from "./storage-value-set-uGUEBAMJ-hX-zFqN5.mjs";
5
+ import { n as reachesAny, r as referenceKey } from "./check-expressions-Mmzgx0XE.mjs";
3
6
  import { _ as unquotedSqlBaseName, a as renderSqlTypeName, c as sameSqlColumnType, m as sqlStorageType, n as isSqlDataType, p as sqlDataTypeOfCodec, r as nameIsCatalogText, u as sqlCodecColumnLength, y as validateSqlTypeParams } from "./sql-data-type-LVBldu1a-Bq203xWX.mjs";
4
7
  import { s as StorageTable } from "./storage-table-B_MrLtQX-eWx6BgGT.mjs";
5
8
  import { c as SqlSchemaIR, n as RelationalSchemaNodeKind, u as SqlTableIR } from "./types-1ZKE0deC-Dou4ugcz.mjs";
6
9
  import { f as sqlExpressionRegistration, m as sqlTextsReadBack, o as printSqlExpressionLiteral } from "./sql-expression-CKgKznXS.mjs";
7
10
  import { d as nonEmptyTypeParams, u as isStorageTypeInstance } from "./types-CISwoRED.mjs";
8
11
  import { g as valueObjectStorageTypeMissingMessage } from "./validators-qcQteqs2.mjs";
9
- import { a as describeUnsupportedSqlAttribute, b as sqlAttributeSpecs } from "./psl-field-resolution-BnusQmZy-CX0b0mPk.mjs";
12
+ import { a as describeUnsupportedSqlAttribute, b as sqlAttributeSpecs } from "./psl-field-resolution-BnusQmZy-_QYc6Ywf.mjs";
10
13
  import { t as describeUnresolvedSqlType } from "./diagnostics-CSrneG0n.mjs";
11
14
  import { t as sqlEmission } from "./dist-BJjqJT_M.mjs";
12
- import { a as sqlFamilyGeneratorFunctions, i as sqlFamilyGeneratorDescriptors, n as sqlFamilyAuthoringTypes, o as sqlFamilyPslBlockDescriptors, r as sqlFamilyEntityTypes } from "./generator-functions-Hy4pDDr9-HEQuSSaK.mjs";
15
+ import { a as sqlFamilyGeneratorFunctions, i as sqlFamilyGeneratorDescriptors, n as sqlFamilyAuthoringTypes, o as sqlFamilyPslBlockDescriptors, r as sqlFamilyEntityTypes } from "./generator-functions-Hy4pDDr9-DlmTbI_c.mjs";
13
16
  import { c as verifySqlSchemaByDiff, n as classifyDiffSubjectGranularity, o as enforceSqlDataTypeInvariants, t as classifyDiffEntityKind } from "./schema-verify-C3wbdviw-nQ4tG9N7.mjs";
14
17
  import { t as sqlFamilyError } from "./errors-B5g0xWro-C8plbqga.mjs";
15
- import { t as SqlContractSerializer } from "./sql-contract-serializer-sMY3prTx-CBHrlt9O.mjs";
18
+ import { t as SqlContractSerializer } from "./sql-contract-serializer-sMY3prTx-BfYfhVR_.mjs";
16
19
  import { t as collectSupportedCodecTypeIds } from "./verify-BVk5bjdH-DhKm6hB3.mjs";
17
20
  import { isStructuredError, structuredError } from "@prisma/orm-framework/utils/structured-error";
18
21
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
19
22
  import { collectScalarTypeConstructors, tsTaggedTemplateSource } from "@prisma/orm-framework/components/authoring";
20
23
  import { ContractValidationError } from "@prisma/orm-framework/contract/contract-validation-error";
21
24
  import { UNBOUND_NAMESPACE_ID, isPlainRecord } from "@prisma/orm-framework/components/ir";
22
- import { asNamespaceId, governingControlPolicy } from "@prisma/orm-framework/contract/types";
25
+ import { asNamespaceId, governingControlPolicy, valueObjectAt, valueObjectsWithCoordinates } from "@prisma/orm-framework/contract/types";
26
+ import { invariant } from "@prisma/orm-framework/utils/assertions";
23
27
  import { assembleDataTypes, codecForRef, dataTypeParams, objectSchemaKeys, readContractValue } from "@prisma/orm-framework/components/codec";
24
28
  import { canonicalizeJson } from "@prisma/orm-framework/components/utils";
25
29
  import { blindCast } from "@prisma/orm-framework/utils/casts";
26
30
  import { InternalError, isInternalError } from "@prisma/orm-framework/utils/internal-error";
27
31
  import { type } from "arktype";
28
32
  import { notOk, ok } from "@prisma/orm-framework/utils/result";
29
- import { APP_SPACE_ID, SchemaTreeNode, VERIFY_CODE_HASH_MISMATCH, VERIFY_CODE_MARKER_MISSING, VERIFY_CODE_TARGET_MISMATCH, assembleAuthoringContributions as assembleAuthoringContributions$1, describeMigrationStatement, enumValueStatementText, extractCodecLookup, fieldStatementText, issueOutcome, migrationRunnerFailure, modelDisplayName, sameMarkerHashes } from "@prisma/orm-framework/components/control";
33
+ import { APP_SPACE_ID, SchemaTreeNode, VERIFY_CODE_HASH_MISMATCH, VERIFY_CODE_MARKER_MISSING, VERIFY_CODE_TARGET_MISMATCH, assembleAuthoringContributions as assembleAuthoringContributions$1, describeMigrationStatement, enumValueStatementText, extractCodecLookup, fieldStatementText, issueOutcome, migrationRunnerFailure, modelDisplayName, modelStatementText, sameMarkerHashes, valueObjectFieldStatementText } from "@prisma/orm-framework/components/control";
30
34
  import { assertDescriptorSelfConsistency } from "@prisma/orm-toolchain/migration-tools/spaces";
31
35
  import { jsonToTsSource } from "@prisma/orm-framework/ts-render";
32
36
  //#region ../../../2-sql-family/9-family/dist/control.mjs
@@ -875,6 +879,19 @@ function databaseFunction(expression) {
875
879
  }
876
880
  };
877
881
  }
882
+ /** Whether the data type of `codecRef`'s codec reads `json` as `contract.json` would; a codec the stack does not know accepts nothing. */
883
+ function acceptedByDataType(json, codecRef, types) {
884
+ const descriptor = types.codecLookup.descriptorFor(codecRef.codecId);
885
+ const dataType = descriptor === void 0 ? void 0 : types.dataTypeLookup.get(descriptor.dataType);
886
+ if (dataType === void 0) return false;
887
+ try {
888
+ dataType.fromContract(json, dataTypeParams(dataType, codecRef.typeParams));
889
+ return true;
890
+ } catch (error) {
891
+ if (isStructuredError(error)) return false;
892
+ throw error;
893
+ }
894
+ }
878
895
  function convertColumn(name, column, types, hooks) {
879
896
  const dataType = sqlDataTypeOfCodec(column.codecId, types);
880
897
  const storage = sqlStorageType(dataType, types.dataTypeLookup);
@@ -1318,6 +1335,165 @@ function partitionIssuesByControlPolicy(options) {
1318
1335
  function subjectKey(subject) {
1319
1336
  return `${subject.namespaceId}\u0000${subject.entityKind ?? ""}\u0000${subject.entityName ?? ""}\u0000${subject.rlsPolicy ?? ""}`;
1320
1337
  }
1338
+ /**
1339
+ * The way out of a refusal that no statement or second plan can lift: a migration the user writes
1340
+ * by hand, which rewrites `what` with the other operations of the change.
1341
+ */
1342
+ function handWrittenMigrationAdvice(what) {
1343
+ return `Write this change as a hand-written migration instead: run prisma migration new, and in the operations of the migration.ts it writes, rewrite ${what} yourself, with the other operations of the change. Then run that migration.ts to emit its ops.json.`;
1344
+ }
1345
+ const BLANK = /* @__PURE__ */ new Set([
1346
+ " ",
1347
+ " ",
1348
+ "\n",
1349
+ "\r"
1350
+ ]);
1351
+ const ESCAPES = {
1352
+ b: "\b",
1353
+ f: "\f",
1354
+ n: "\n",
1355
+ r: "\r",
1356
+ t: " ",
1357
+ "/": "/",
1358
+ "\\": "\\"
1359
+ };
1360
+ function isNameFirst(char) {
1361
+ return /^[A-Za-z_]$/.test(char) || (char.codePointAt(0) ?? 0) >= 128;
1362
+ }
1363
+ function isNameChar(char) {
1364
+ return isNameFirst(char) || /^[0-9]$/.test(char);
1365
+ }
1366
+ var Reader = class {
1367
+ text;
1368
+ position = 0;
1369
+ constructor(text) {
1370
+ this.text = text;
1371
+ }
1372
+ get done() {
1373
+ return this.position >= this.text.length;
1374
+ }
1375
+ peek(offset = 0) {
1376
+ return this.text[this.position + offset] ?? "";
1377
+ }
1378
+ next() {
1379
+ const char = this.peek();
1380
+ this.position += 1;
1381
+ return char;
1382
+ }
1383
+ skipBlank() {
1384
+ while (BLANK.has(this.peek())) this.position += 1;
1385
+ }
1386
+ };
1387
+ function readShorthandName(reader) {
1388
+ if (!isNameFirst(reader.peek())) return void 0;
1389
+ let name = "";
1390
+ while (!reader.done && isNameChar(reader.peek())) name += reader.next();
1391
+ return name;
1392
+ }
1393
+ function readStringLiteral(reader) {
1394
+ const quote = reader.next();
1395
+ let value = "";
1396
+ while (!reader.done) {
1397
+ const char = reader.next();
1398
+ if (char === quote) return value;
1399
+ if (char !== "\\") {
1400
+ if ((char.codePointAt(0) ?? 0) < 32) return void 0;
1401
+ value += char;
1402
+ continue;
1403
+ }
1404
+ const escaped = reader.next();
1405
+ if (escaped === quote) value += quote;
1406
+ else if (escaped === "u") {
1407
+ const hex = reader.text.slice(reader.position, reader.position + 4);
1408
+ if (!/^[0-9A-Fa-f]{4}$/.test(hex)) return void 0;
1409
+ reader.position += 4;
1410
+ value += String.fromCharCode(Number.parseInt(hex, 16));
1411
+ } else {
1412
+ const replacement = ESCAPES[escaped];
1413
+ if (replacement === void 0) return void 0;
1414
+ value += replacement;
1415
+ }
1416
+ }
1417
+ }
1418
+ function readBracket(reader) {
1419
+ reader.next();
1420
+ reader.skipBlank();
1421
+ let step;
1422
+ const first = reader.peek();
1423
+ if (first === "*") {
1424
+ reader.next();
1425
+ step = { kind: "wildcard" };
1426
+ } else if (first === "'" || first === "\"") {
1427
+ const name = readStringLiteral(reader);
1428
+ step = name === void 0 ? void 0 : {
1429
+ kind: "member",
1430
+ name
1431
+ };
1432
+ }
1433
+ reader.skipBlank();
1434
+ return step !== void 0 && reader.next() === "]" ? step : void 0;
1435
+ }
1436
+ /**
1437
+ * Parses an RFC 9535 JSONPath that uses only member name selectors (`.lat`, `['lat']`) and the
1438
+ * wildcard selector (`[*]`, `.*`), which selects the elements of a list and the member values of an
1439
+ * object. Any other JSONPath feature is refused with the reason.
1440
+ */
1441
+ function parseJsonPath(text) {
1442
+ const unsupported = notOk(`path ${JSON.stringify(text)} is not a JSONPath of member names (.name or ['name']) and wildcards ([*] or .*) from $`);
1443
+ const reader = new Reader(text);
1444
+ if (reader.next() !== "$") return unsupported;
1445
+ const steps = [];
1446
+ while (!reader.done) {
1447
+ reader.skipBlank();
1448
+ const char = reader.peek();
1449
+ let step;
1450
+ if (char === "." && reader.peek(1) === "*") {
1451
+ reader.position += 2;
1452
+ step = { kind: "wildcard" };
1453
+ } else if (char === ".") {
1454
+ reader.next();
1455
+ const name = readShorthandName(reader);
1456
+ step = name === void 0 ? void 0 : {
1457
+ kind: "member",
1458
+ name
1459
+ };
1460
+ } else if (char === "[") step = readBracket(reader);
1461
+ if (step === void 0) return unsupported;
1462
+ steps.push(step);
1463
+ }
1464
+ return ok({
1465
+ text,
1466
+ steps
1467
+ });
1468
+ }
1469
+ /** The longest start of `path`'s text that is a path of `steps` selectors, without trailing blanks. */
1470
+ function writtenPrefix(path, steps) {
1471
+ for (let end = path.text.length - 1; end > 0; end -= 1) {
1472
+ const prefix = path.text.slice(0, end).trimEnd();
1473
+ const parsed = parseJsonPath(prefix);
1474
+ if (parsed.ok && parsed.value.steps.length === steps) return prefix;
1475
+ }
1476
+ return jsonPathText(path.steps.slice(0, steps));
1477
+ }
1478
+ /** The path split at its last selector, when that selector is a member name. */
1479
+ function keyPathOf(path) {
1480
+ const last = path.steps.at(-1);
1481
+ if (last?.kind !== "member") return void 0;
1482
+ const objects = path.steps.slice(0, -1);
1483
+ return {
1484
+ path,
1485
+ objects,
1486
+ objectsText: writtenPrefix(path, objects.length),
1487
+ key: last.name
1488
+ };
1489
+ }
1490
+ /** The steps as a JSONPath: a member name in shorthand when it is an identifier, else in brackets. */
1491
+ function jsonPathText(steps) {
1492
+ return `$${steps.map((step) => {
1493
+ if (step.kind === "wildcard") return "[*]";
1494
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(step.name) ? `.${step.name}` : `[${JSON.stringify(step.name)}]`;
1495
+ }).join("")}`;
1496
+ }
1321
1497
  const COLUMN_RENAME_UNMATCHED_CODE = "MIGRATION.COLUMN_RENAME_UNMATCHED";
1322
1498
  function tableLabel$1(namespaceId, table) {
1323
1499
  return namespaceId === void 0 || namespaceId === UNBOUND_NAMESPACE_ID ? table : `${namespaceId}.${table}`;
@@ -1542,6 +1718,13 @@ const NO_RENAMED_ORIGINS = {
1542
1718
  originTable: (current) => current,
1543
1719
  originColumn: (_origin, column) => column
1544
1720
  };
1721
+ const PLANNED_WITH_DIFF = { kind: "plannedWithDiff" };
1722
+ function plannedAt(operationIndexes) {
1723
+ return {
1724
+ kind: "planned",
1725
+ operationIndexes
1726
+ };
1727
+ }
1545
1728
  const DRIFTED = "so the database has drifted from that contract. Inspect it with prisma db schema, or leave out this statement.";
1546
1729
  const UNMATCHED = "A statement plans the rename a hand-written rename call makes, and that call does not match the contracts. Leave out this statement.";
1547
1730
  function statementRefused(statement, summary, why, location, refusedOperationClass) {
@@ -1618,6 +1801,9 @@ function columnRenameRefused(statement, label, rename, mismatch) {
1618
1801
  });
1619
1802
  }
1620
1803
  }
1804
+ function planned(operationIndexes) {
1805
+ return operationIndexes.ok ? ok(plannedAt(operationIndexes.value)) : operationIndexes;
1806
+ }
1621
1807
  var StatementPlanner = class {
1622
1808
  #fromContract;
1623
1809
  #contract;
@@ -1644,13 +1830,14 @@ var StatementPlanner = class {
1644
1830
  this.#target = input.target;
1645
1831
  this.#ownership = input.ownership;
1646
1832
  }
1647
- /** Plans one statement; the result is the positions of the operations it accounts for. */
1833
+ /** Plans one statement; the result is the operations it accounts for. */
1648
1834
  plan(statement) {
1649
1835
  switch (statement.entity) {
1650
- case "namespace": return this.#planNamespace(statement);
1651
- case "model": return this.#planModel(statement);
1652
- case "field": return this.#planField(statement);
1653
- case "enumValue": return ok([]);
1836
+ case "namespace": return planned(this.#planNamespace(statement));
1837
+ case "model": return planned(this.#planModel(statement));
1838
+ case "field": return planned(this.#planField(statement));
1839
+ case "enumValue":
1840
+ case "valueObjectField": return ok(PLANNED_WITH_DIFF);
1654
1841
  }
1655
1842
  }
1656
1843
  /** Where a table of the origin is in the working schema, after the renames planned so far. */
@@ -1881,7 +2068,7 @@ function planStatements(input) {
1881
2068
  calls: [],
1882
2069
  tableRenames: [],
1883
2070
  columnRenames: [],
1884
- appliedStatements: [],
2071
+ plannedStatements: [],
1885
2072
  origins: NO_RENAMED_ORIGINS
1886
2073
  });
1887
2074
  if (fromContract === null) return notOk(statementRefused(first, "Statements need an origin contract, and this plan has none", "A statement names models and fields of the origin contract, and this plan has none. Plan from a contract that has the old names, or leave out the statement.", void 0));
@@ -1890,21 +2077,21 @@ function planStatements(input) {
1890
2077
  fromContract,
1891
2078
  ownership: input.ownership
1892
2079
  });
1893
- const appliedStatements = [];
2080
+ const plannedStatements = [];
1894
2081
  const namespacesFirst = [...input.statements.filter((statement) => statement.entity === "namespace"), ...input.statements.filter((statement) => statement.entity !== "namespace")];
1895
2082
  for (const statement of namespacesFirst) {
1896
- const operationIndexes = planner.plan(statement);
1897
- if (!operationIndexes.ok) return operationIndexes;
1898
- appliedStatements.push({
2083
+ const operations = planner.plan(statement);
2084
+ if (!operations.ok) return operations;
2085
+ plannedStatements.push({
1899
2086
  statement,
1900
- operationIndexes: operationIndexes.value
2087
+ operations: operations.value
1901
2088
  });
1902
2089
  }
1903
2090
  return ok({
1904
2091
  calls: planner.calls,
1905
2092
  tableRenames: planner.tableRenames,
1906
2093
  columnRenames: planner.columnRenames,
1907
- appliedStatements,
2094
+ plannedStatements,
1908
2095
  origins: planner.origins()
1909
2096
  });
1910
2097
  }
@@ -1915,7 +2102,7 @@ function planStatements(input) {
1915
2102
  */
1916
2103
  function fieldStatementColumns(statements, contract) {
1917
2104
  const columnsOf = (kind) => statements.flatMap((statement) => {
1918
- if (statement.kind !== kind) return [];
2105
+ if (statement.kind !== kind || statement.entity !== "field") return [];
1919
2106
  const table = modelTable(contract, statement.field);
1920
2107
  const column = fieldColumn(contract, statement.field);
1921
2108
  return table === void 0 || column === void 0 ? [] : [{
@@ -1938,7 +2125,7 @@ function fieldStatementColumns(statements, contract) {
1938
2125
  */
1939
2126
  function backfillOfDefaultedField(statements, fromContract, contract) {
1940
2127
  for (const statement of statements) {
1941
- if (statement.kind !== "backfill" || fromContract === null) continue;
2128
+ if (statement.kind !== "backfill" || statement.entity !== "field" || fromContract === null) continue;
1942
2129
  const originModel = sqlModelStorage(fromContract, statement.field);
1943
2130
  if (originModel === void 0 || Object.hasOwn(originModel.fields, statement.field.field)) continue;
1944
2131
  const table = modelTable(contract, statement.field);
@@ -1953,15 +2140,258 @@ function backfillOfDefaultedField(statements, fromContract, contract) {
1953
2140
  }
1954
2141
  }
1955
2142
  /**
1956
- * Every statement of a plan in the order given, with the operations it accounts for: a rename's
1957
- * from `renames`, and none yet for any other statement.
2143
+ * The operations of a statement the statement planner does not take: a value object field backfill
2144
+ * and a variant convert are planned with the diff; a field convert or backfill accounts for none.
1958
2145
  */
1959
- function appliedStatementsInOrder(statements, renames) {
1960
- return statements.map((statement) => renames.find((applied) => applied.statement === statement) ?? {
1961
- statement,
1962
- operationIndexes: []
2146
+ function operationsOutsideStatementPlanner(statement) {
2147
+ if (statement.kind === "rename") return plannedAt([]);
2148
+ switch (statement.entity) {
2149
+ case "field": return plannedAt([]);
2150
+ case "valueObjectField":
2151
+ case "model": return PLANNED_WITH_DIFF;
2152
+ }
2153
+ }
2154
+ /**
2155
+ * Every statement of a plan in the order given, with the operations it accounts for: a planned
2156
+ * statement's from `planned`, and a statement planned with the diff's from
2157
+ * `operationIndexesPlannedWithDiff`, which finds them among the target's whole plan. A model rename
2158
+ * takes both, since renaming a variant whose discriminator value changed also rewrites the value.
2159
+ */
2160
+ function appliedStatementsInOrder(statements, planned, operationIndexesPlannedWithDiff) {
2161
+ return statements.map((statement) => {
2162
+ const operations = planned.find((entry) => entry.statement === statement)?.operations ?? operationsOutsideStatementPlanner(statement);
2163
+ if (operations.kind === "plannedWithDiff") return {
2164
+ statement,
2165
+ operationIndexes: operationIndexesPlannedWithDiff(statement)
2166
+ };
2167
+ return {
2168
+ statement,
2169
+ operationIndexes: statement.kind === "rename" && statement.entity === "model" ? [...operations.operationIndexes, ...operationIndexesPlannedWithDiff(statement)].sort((left, right) => left - right) : operations.operationIndexes
2170
+ };
1963
2171
  });
1964
2172
  }
2173
+ const WILDCARD = { kind: "wildcard" };
2174
+ function isMany$2(many) {
2175
+ return many !== void 0 && many !== false;
2176
+ }
2177
+ function requiredValueObject(storage, reference) {
2178
+ const valueObject = valueObjectAt(storage, reference);
2179
+ invariant(valueObject !== void 0, `value object "${reference.entityName}" in namespace "${reference.namespaceId}" is not in storage; the contract validators refuse a reference to a missing value object`);
2180
+ return valueObject;
2181
+ }
2182
+ function nestedReferences(valueObject) {
2183
+ return Object.values(valueObject.fields).flatMap(({ type }) => type.kind === "valueObject" ? [type] : []);
2184
+ }
2185
+ function containsItself(storage, from) {
2186
+ const own = /* @__PURE__ */ new Set([referenceKey(from)]);
2187
+ return nestedReferences(requiredValueObject(storage, from)).some((nested) => reachesAny(storage, nested, own));
2188
+ }
2189
+ /** The paths from `steps` to each object of `target` inside an object of `from`. */
2190
+ function pathsWithin(storage, from, steps, target) {
2191
+ const targets = /* @__PURE__ */ new Set([referenceKey(target)]);
2192
+ if (containsItself(storage, from)) return reachesAny(storage, from, targets) ? {
2193
+ kind: "containsItself",
2194
+ valueObject: from.entityName
2195
+ } : {
2196
+ kind: "paths",
2197
+ paths: []
2198
+ };
2199
+ const paths = referenceKey(from) === referenceKey(target) ? [steps] : [];
2200
+ for (const [name, field] of Object.entries(requiredValueObject(storage, from).fields)) {
2201
+ if (field.type.kind !== "valueObject") continue;
2202
+ const nested = pathsWithin(storage, field.type, [
2203
+ ...steps,
2204
+ {
2205
+ kind: "member",
2206
+ name
2207
+ },
2208
+ ...isMany$2(field.many) ? [WILDCARD] : []
2209
+ ], target);
2210
+ if (nested.kind !== "paths") return nested;
2211
+ paths.push(...nested.paths);
2212
+ }
2213
+ return {
2214
+ kind: "paths",
2215
+ paths
2216
+ };
2217
+ }
2218
+ function reachOf(storage, field, target) {
2219
+ const targets = /* @__PURE__ */ new Set([referenceKey(target)]);
2220
+ const { type } = field;
2221
+ if (type.kind === "union") return type.members.some((member) => member.kind === "valueObject" && reachesAny(storage, member, targets)) ? { kind: "union" } : {
2222
+ kind: "paths",
2223
+ paths: []
2224
+ };
2225
+ if (type.kind !== "valueObject") return {
2226
+ kind: "paths",
2227
+ paths: []
2228
+ };
2229
+ if (field.dict === true) return reachesAny(storage, type, targets) ? { kind: "dictionary" } : {
2230
+ kind: "paths",
2231
+ paths: []
2232
+ };
2233
+ return pathsWithin(storage, type, isMany$2(field.many) ? [WILDCARD] : [], target);
2234
+ }
2235
+ /** The columns of the destination, in managed tables the working schema has, that hold a model field. */
2236
+ function storedColumns(contract, tables) {
2237
+ const found = /* @__PURE__ */ new Map();
2238
+ for (const namespace of Object.values(contract.domain.namespaces)) for (const model of Object.values(namespace.models)) {
2239
+ const { storage } = model;
2240
+ if (!isSqlModelStorage(storage)) continue;
2241
+ const location = {
2242
+ namespaceId: storage.namespaceId,
2243
+ table: storage.table
2244
+ };
2245
+ if (tableControlPolicy(contract, location) !== "managed") continue;
2246
+ for (const [fieldName, field] of Object.entries(model.fields)) {
2247
+ const column = storage.fields[fieldName]?.column;
2248
+ if (column === void 0) continue;
2249
+ if (!tables.hasColumn(storage.namespaceId, storage.table, column)) continue;
2250
+ found.set(JSON.stringify([
2251
+ storage.namespaceId,
2252
+ storage.table,
2253
+ column
2254
+ ]), {
2255
+ ...location,
2256
+ column,
2257
+ field
2258
+ });
2259
+ }
2260
+ }
2261
+ return [...found.values()];
2262
+ }
2263
+ /**
2264
+ * Finds every place the destination stores a value object: each column of the working schema, in a
2265
+ * managed table, whose field holds it, at every path to its objects, nested or in lists. The paths
2266
+ * are written with the destination's names. A column whose paths cannot be listed, because it holds
2267
+ * the value object through a value object that contains itself, a union or a dictionary, is the
2268
+ * failure.
2269
+ */
2270
+ function valueObjectPlaces(contract, tables) {
2271
+ const columns = storedColumns(contract, tables);
2272
+ return (target) => {
2273
+ const places = [];
2274
+ for (const column of columns) {
2275
+ const reach = reachOf(contract.storage, column.field, target);
2276
+ if (reach.kind !== "paths") return notOk({
2277
+ column,
2278
+ reach
2279
+ });
2280
+ for (const steps of reach.paths) places.push({
2281
+ namespaceId: column.namespaceId,
2282
+ table: column.table,
2283
+ column: column.column,
2284
+ steps
2285
+ });
2286
+ }
2287
+ return ok(places);
2288
+ };
2289
+ }
2290
+ function fieldChanges(fromContract, contract, statements) {
2291
+ const renamedNamespaces = /* @__PURE__ */ new Map();
2292
+ const renames = [];
2293
+ for (const statement of statements) {
2294
+ if (statement.kind !== "rename") continue;
2295
+ if (statement.entity === "namespace") renamedNamespaces.set(statement.from, statement.to);
2296
+ if (statement.entity === "valueObjectField") renames.push(statement);
2297
+ }
2298
+ const changes = [];
2299
+ for (const { coordinate, valueObject } of valueObjectsWithCoordinates(fromContract.storage)) {
2300
+ const target = {
2301
+ ...coordinate,
2302
+ namespaceId: renamedNamespaces.get(coordinate.namespaceId) ?? coordinate.namespaceId
2303
+ };
2304
+ const destination = valueObjectAt(contract.storage, target);
2305
+ if (destination === void 0) continue;
2306
+ for (const from of Object.keys(valueObject.fields)) {
2307
+ const valueObjectField = {
2308
+ namespaceId: asNamespaceId(coordinate.namespaceId),
2309
+ valueObject: coordinate.entityName,
2310
+ field: from
2311
+ };
2312
+ const statement = renames.find((rename) => rename.from.namespaceId === valueObjectField.namespaceId && rename.from.valueObject === valueObjectField.valueObject && rename.from.field === from);
2313
+ if (statement !== void 0) changes.push({
2314
+ valueObjectField,
2315
+ target,
2316
+ from,
2317
+ to: statement.to.field,
2318
+ statement
2319
+ });
2320
+ else if (!Object.hasOwn(destination.fields, from)) changes.push({
2321
+ valueObjectField,
2322
+ target,
2323
+ from,
2324
+ to: void 0,
2325
+ statement: void 0
2326
+ });
2327
+ }
2328
+ }
2329
+ return changes;
2330
+ }
2331
+ function columnText(column) {
2332
+ return `column "${column.column}" of "${column.table}"`;
2333
+ }
2334
+ function refused(change, fromContract, contract, column, reason, why) {
2335
+ const from = valueObjectFieldStatementText(fromContract, change.valueObjectField);
2336
+ if (change.statement === void 0) return {
2337
+ kind: "unsupportedOperation",
2338
+ summary: `Cannot remove value object field "${from}": ${reason}`,
2339
+ why: `${why} ${handWrittenMigrationAdvice(`the JSON of ${columnText(column)}`)}`
2340
+ };
2341
+ return {
2342
+ kind: "statementRefused",
2343
+ summary: `Cannot rename value object field "${from}" to "${valueObjectFieldStatementText(contract, change.statement.to)}": ${reason}`,
2344
+ why: `${why} ${handWrittenMigrationAdvice(`the JSON of ${columnText(column)}`)}`,
2345
+ refusedStatement: change.statement
2346
+ };
2347
+ }
2348
+ function reachRefusal(reach, column, change, contracts) {
2349
+ if (reach.kind === "containsItself") return refused(change, contracts.fromContract, contracts.contract, column, `${columnText(column)} holds it inside value object "${reach.valueObject}", which contains itself, so the JSON can hold it at any depth`, "The plan rewrites a key at every path from a column to its value object, and a value object that contains itself has no last path.");
2350
+ return refused(change, contracts.fromContract, contracts.contract, column, `${columnText(column)} holds a ${reach.kind} of value objects`, "The plan rewrites a key only in a column that holds a value object or a list of them.");
2351
+ }
2352
+ /**
2353
+ * The key rewrites of value object fields a plan makes. A value object of the origin is compared,
2354
+ * field by field, with the value object of the same name in the destination: a rename statement
2355
+ * renames a field's key, and a field the destination lacks that no statement renames is removed,
2356
+ * which the plan asks about. Each rewrite acts on every column of the working schema whose field
2357
+ * holds the value object, at every path to its objects, nested or in lists. The paths are written
2358
+ * with the destination's names, so an outer rename runs before an inner one: the rewrites come out
2359
+ * ordered by the depth of their paths. A path through a value object that contains itself, or a
2360
+ * column that holds a union or a dictionary of value objects, is refused. With no origin contract,
2361
+ * nothing is known to have changed.
2362
+ */
2363
+ function planValueObjectFieldRewrites(input) {
2364
+ const { fromContract, contract } = input;
2365
+ if (fromContract === null) return ok([]);
2366
+ const changes = fieldChanges(fromContract, contract, input.statements);
2367
+ if (changes.length === 0) return ok([]);
2368
+ const placesOf = valueObjectPlaces(contract, input.tables);
2369
+ const rewrites = [];
2370
+ for (const change of changes) {
2371
+ const places = placesOf(change.target);
2372
+ if (!places.ok) {
2373
+ const { reach, column } = places.failure;
2374
+ return notOk(reachRefusal(reach, column, change, {
2375
+ fromContract,
2376
+ contract
2377
+ }));
2378
+ }
2379
+ for (const { steps, ...place } of places.value) rewrites.push({
2380
+ depth: steps.length,
2381
+ rewrite: {
2382
+ valueObjectField: change.valueObjectField,
2383
+ ...place,
2384
+ path: jsonPathText([...steps, {
2385
+ kind: "member",
2386
+ name: change.from
2387
+ }]),
2388
+ to: change.to,
2389
+ statement: change.statement
2390
+ }
2391
+ });
2392
+ }
2393
+ return ok([...rewrites].sort((left, right) => left.depth - right.depth).map(({ rewrite }) => rewrite));
2394
+ }
1965
2395
  function sameValue(left, right) {
1966
2396
  return JSON.stringify(left) === JSON.stringify(right);
1967
2397
  }
@@ -1994,12 +2424,67 @@ function columnsTypedBy(contract, namespaceId, enumName) {
1994
2424
  ...location,
1995
2425
  column,
1996
2426
  codecRef: buildColumnCodecRef(stored, void 0),
1997
- many: stored.many !== false && stored.many !== void 0
2427
+ many: stored.many !== false && stored.many !== void 0,
2428
+ member: void 0
1998
2429
  });
1999
2430
  }
2000
2431
  }
2001
2432
  return [...found.values()];
2002
2433
  }
2434
+ function isMany$1(many) {
2435
+ return many !== void 0 && many !== false;
2436
+ }
2437
+ /**
2438
+ * The members of value objects, in the destination's columns, that the enum's storage value set
2439
+ * types: each column and path where the destination stores the value object.
2440
+ */
2441
+ function membersTypedBy(contract, placesOf, namespaceId, enumName) {
2442
+ const found = [];
2443
+ for (const { coordinate, valueObject } of valueObjectsWithCoordinates(contract.storage)) {
2444
+ const typed = Object.entries(valueObject.fields).filter(([, field]) => field.valueSet !== void 0 && field.valueSet.spaceId === void 0 && field.valueSet.namespaceId === namespaceId && field.valueSet.entityName === enumName);
2445
+ if (typed.length === 0) continue;
2446
+ const places = placesOf(coordinate);
2447
+ if (!places.ok) return places;
2448
+ for (const [name, field] of typed) for (const { steps, ...place } of places.value) found.push({
2449
+ ...place,
2450
+ codecRef: void 0,
2451
+ many: false,
2452
+ member: {
2453
+ path: jsonPathText([
2454
+ ...steps,
2455
+ {
2456
+ kind: "member",
2457
+ name
2458
+ },
2459
+ ...isMany$1(field.many) ? [{ kind: "wildcard" }] : []
2460
+ ]),
2461
+ nullable: field.nullable
2462
+ }
2463
+ });
2464
+ }
2465
+ return ok(found);
2466
+ }
2467
+ function unlistedRefusal(contract, enums, changes, { column, reach }) {
2468
+ const where = `column "${column.column}" of "${column.table}"`;
2469
+ const reason = reach.kind === "containsItself" ? `${where} holds it inside value object "${reach.valueObject}", which contains itself, so the JSON can hold it at any depth` : `${where} holds a ${reach.kind} of value objects`;
2470
+ const why = reach.kind === "containsItself" ? "The plan rewrites an enum value inside JSON at every path from a column to its member, and a value object that contains itself has no last path." : "The plan rewrites an enum value inside JSON only in a column that holds a value object or a list of them.";
2471
+ const statement = changes.find((change) => change.statement !== void 0)?.statement;
2472
+ if (statement === void 0) {
2473
+ const [first] = changes;
2474
+ invariant(first !== void 0, "an enum with no changed value plans no rewrite to refuse");
2475
+ return {
2476
+ kind: "unsupportedOperation",
2477
+ summary: `Cannot remove enum value "${enumValueStatementText(enums.fromContract, first.enumValue)}": ${reason}`,
2478
+ why: `${why} ${handWrittenMigrationAdvice(`the JSON of ${where}`)}`
2479
+ };
2480
+ }
2481
+ return {
2482
+ kind: "statementRefused",
2483
+ summary: `Cannot rename enum value "${enumValueStatementText(enums.fromContract, statement.from)}" to "${enumValueStatementText(contract, statement.to)}": ${reason}`,
2484
+ why: `${why} ${handWrittenMigrationAdvice(`the JSON of ${where}`)}`,
2485
+ refusedStatement: statement
2486
+ };
2487
+ }
2003
2488
  function isStoredEnumValue(value) {
2004
2489
  return typeof value === "string" || typeof value === "number";
2005
2490
  }
@@ -2155,6 +2640,7 @@ function planEnumValueRewrites(input) {
2155
2640
  if (statement.entity === "namespace") renamedNamespaces.set(statement.from, statement.to);
2156
2641
  if (statement.entity === "enumValue") valueRenames.push(statement);
2157
2642
  }
2643
+ const placesOf = valueObjectPlaces(contract, input.tables);
2158
2644
  const rewrites = [];
2159
2645
  for (const [originNamespace, namespace] of Object.entries(fromContract.domain.namespaces)) for (const [enumName, originEnum] of Object.entries(namespace.enum ?? {})) {
2160
2646
  const namespaceId = renamedNamespaces.get(originNamespace) ?? originNamespace;
@@ -2197,7 +2683,10 @@ function planEnumValueRewrites(input) {
2197
2683
  const merged = merging(to);
2198
2684
  if (merged !== void 0) return notOk(mergingRefusal(statement, enums, from, to, merged.name));
2199
2685
  }
2200
- const columns = columnsTypedBy(contract, namespaceId, enumName).filter((column) => input.tables.hasColumn(column.namespaceId, column.table, column.column));
2686
+ if (checked.length === 0) continue;
2687
+ const members = membersTypedBy(contract, placesOf, namespaceId, enumName);
2688
+ if (!members.ok) return notOk(unlistedRefusal(contract, enums, checked, members.failure));
2689
+ const columns = [...columnsTypedBy(contract, namespaceId, enumName).filter((column) => input.tables.hasColumn(column.namespaceId, column.table, column.column)), ...members.value];
2201
2690
  if (columns.length === 0) continue;
2202
2691
  const taken = [...originEnum.members.map(({ value }) => value), ...destinationEnum.members.map(({ value }) => value)];
2203
2692
  for (const group of orderChanges(checked)) {
@@ -2240,19 +2729,6 @@ function keptData(group, taken, merging) {
2240
2729
  })] : moved(change)])];
2241
2730
  }
2242
2731
  /**
2243
- * The applied statements with each enum value rename given the operations its rewrites lowered
2244
- * to, at their positions in the plan: the rewrites are ordered with the diff, not with the renames.
2245
- */
2246
- function withEnumValueOperations(applied, operationIndexesOf) {
2247
- return applied.map(({ statement, operationIndexes }) => statement.kind === "rename" && statement.entity === "enumValue" ? {
2248
- statement,
2249
- operationIndexes: operationIndexesOf(statement)
2250
- } : {
2251
- statement,
2252
- operationIndexes
2253
- });
2254
- }
2255
- /**
2256
2732
  * The value the database stores for `value`, a stored value as the contract writes it: the column's
2257
2733
  * codec reads it as a value of its data type and writes it with `toWire`, as a literal default is
2258
2734
  * written. With no codec, or one the stack does not have, the value is used as written.
@@ -2439,6 +2915,116 @@ function fieldOfColumn(contract, table, column) {
2439
2915
  if (new Set(fields.map(({ storageNamespace }) => storageNamespace)).size !== 1) return void 0;
2440
2916
  return (fields.find(({ isRoot }) => isRoot) ?? fields[0])?.subject;
2441
2917
  }
2918
+ /** The name each scalar type constructor of `namespace` is written as, by the codec it makes; the first declared wins. */
2919
+ function scalarTypeNamesOf(namespace) {
2920
+ const constructors = [...collectScalarTypeConstructors(namespace)];
2921
+ return (codecRef) => constructors.find(([, output]) => output.codecId === codecRef.codecId && JSON.stringify(output.typeParams ?? {}) === JSON.stringify(codecRef.typeParams ?? {}))?.[0];
2922
+ }
2923
+ function fieldNamed(contract, text) {
2924
+ for (const { coordinate, valueObject } of valueObjectsWithCoordinates(contract.storage)) for (const [name, field] of Object.entries(valueObject.fields)) if (valueObjectFieldStatementText(contract, {
2925
+ namespaceId: asNamespaceId(coordinate.namespaceId),
2926
+ valueObject: coordinate.entityName,
2927
+ field: name
2928
+ }) === text) return {
2929
+ text,
2930
+ field
2931
+ };
2932
+ }
2933
+ function isMany(field) {
2934
+ return field.many !== void 0 && field.many !== false;
2935
+ }
2936
+ function valueSetValues(contract, field) {
2937
+ const reference = field.valueSet;
2938
+ if (reference === void 0) return void 0;
2939
+ const valueSet = Object.hasOwn(contract.storage.namespaces, reference.namespaceId) ? contract.storage.namespaces[reference.namespaceId]?.entries?.["valueSet"]?.[reference.entityName] : void 0;
2940
+ return isStorageValueSet(valueSet) ? valueSet.values : void 0;
2941
+ }
2942
+ function isJsonObject(value) {
2943
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2944
+ }
2945
+ function json(value) {
2946
+ return JSON.stringify(value);
2947
+ }
2948
+ var FieldValueCheck = class {
2949
+ check;
2950
+ constructor(check) {
2951
+ this.check = check;
2952
+ }
2953
+ /** The type of one value of `field`, as its schema writes it. */
2954
+ typeText(field) {
2955
+ const { type } = field;
2956
+ if (type.kind === "valueObject") return type.entityName;
2957
+ if (type.kind === "union") return "value of its union";
2958
+ if (field.valueSet !== void 0) return `value of ${field.valueSet.entityName}`;
2959
+ const codecRef = buildColumnCodecRef(type, void 0);
2960
+ return this.check.types.scalarTypeName(codecRef) ?? `value of codec ${json(type.codecId)}`;
2961
+ }
2962
+ fieldProblem(value, named) {
2963
+ const { field, text } = named;
2964
+ if (value === null && field.nullable) return void 0;
2965
+ if (!isMany(field)) return this.oneValueProblem(value, named);
2966
+ if (!Array.isArray(value)) return `value ${json(value)} for field ${json(text)} is not a list of ${this.typeText(field)}`;
2967
+ const elementNullable = field.many !== false && field.many?.elementNullable === true;
2968
+ for (const element of value) {
2969
+ if (element === null && elementNullable) continue;
2970
+ const problem = this.oneValueProblem(element, named);
2971
+ if (problem !== void 0) return problem;
2972
+ }
2973
+ }
2974
+ oneValueProblem(value, named) {
2975
+ const { field, text } = named;
2976
+ const { type } = field;
2977
+ const notA = `value ${json(value)} for field ${json(text)} is not a ${this.typeText(field)}`;
2978
+ if (type.kind === "union") return void 0;
2979
+ if (type.kind === "valueObject") return isJsonObject(value) ? this.objectProblem(value, type, text) : notA;
2980
+ const values = valueSetValues(this.check.contract, field);
2981
+ if (values !== void 0) return values.includes(value) ? void 0 : `${notA}; it takes ${values.map(json).join(", ")}`;
2982
+ const codecRef = buildColumnCodecRef(type, void 0);
2983
+ if (this.check.types.codecLookup.descriptorFor(codecRef.codecId) === void 0) return `field ${json(text)} has codec ${json(codecRef.codecId)}, which the stack does not have, so no value can be checked against it`;
2984
+ return acceptedByDataType(value, codecRef, this.check.types) ? void 0 : notA;
2985
+ }
2986
+ objectProblem(value, reference, text) {
2987
+ const valueObject = valueObjectAt(this.check.contract.storage, reference);
2988
+ if (valueObject === void 0) return void 0;
2989
+ const name = reference.entityName;
2990
+ for (const key of Object.keys(value)) if (!Object.hasOwn(valueObject.fields, key)) return `value ${json(value)} for field ${json(text)} has key ${json(key)}, and ${name} has no field ${json(key)}`;
2991
+ for (const [key, field] of Object.entries(valueObject.fields)) {
2992
+ const fieldText = valueObjectFieldStatementText(this.check.contract, {
2993
+ namespaceId: asNamespaceId(reference.namespaceId),
2994
+ valueObject: name,
2995
+ field: key
2996
+ });
2997
+ const member = Object.hasOwn(value, key) ? value[key] : void 0;
2998
+ if (member === void 0) {
2999
+ if (field.nullable) continue;
3000
+ return `value ${json(value)} for field ${json(text)} lacks field ${json(fieldText)}, which is required`;
3001
+ }
3002
+ const problem = this.fieldProblem(member, {
3003
+ text: fieldText,
3004
+ field
3005
+ });
3006
+ if (problem !== void 0) return problem;
3007
+ }
3008
+ }
3009
+ };
3010
+ /** Why `field` cannot be the field a `fillStoredKey` call fills at `keyPath`: its last name must be the key the path ends at. */
3011
+ function fillKeyProblem(keyPath, field) {
3012
+ if (field === void 0) return void 0;
3013
+ return field.text.slice(field.text.lastIndexOf(".") + 1) === keyPath.key ? void 0 : `field ${json(field.text)} does not name key ${json(keyPath.key)}, the key path ${json(keyPath.path)} ends at`;
3014
+ }
3015
+ /**
3016
+ * Why `value` cannot fill the field, or `undefined` when the field has no check or takes the value:
3017
+ * an enum value must be one of its value set's values, a list must hold values of its element's
3018
+ * type, a value object must hold its required fields and no other key, each checked the same way,
3019
+ * and a scalar must be one its codec's data type accepts.
3020
+ */
3021
+ function fillValueProblem(value, field) {
3022
+ const check = field?.check;
3023
+ if (field === void 0 || check === void 0) return void 0;
3024
+ const named = fieldNamed(check.contract, field.text);
3025
+ if (named === void 0) return `field ${json(field.text)} is not a value object field of the end contract`;
3026
+ return new FieldValueCheck(check).fieldProblem(value, named);
3027
+ }
2442
3028
  /** What a codec hook's call is about: the column of the field event it was returned for. */
2443
3029
  function fieldEventStorage(field) {
2444
3030
  return {
@@ -2484,11 +3070,22 @@ function modelsStoring(contract, namespaceId, table) {
2484
3070
  }];
2485
3071
  }));
2486
3072
  }
3073
+ function isRemovedVariant(model, context) {
3074
+ return context.removedVariants.some((variant) => variant.namespaceId === model.namespaceId && variant.model === model.model);
3075
+ }
2487
3076
  function subjectOf(target, context) {
2488
3077
  if (target.enumValue !== void 0) return {
2489
3078
  kind: "enumValue",
2490
3079
  ...target.enumValue
2491
3080
  };
3081
+ if (target.valueObjectField !== void 0) return {
3082
+ kind: "valueObjectField",
3083
+ ...target.valueObjectField
3084
+ };
3085
+ if (target.model !== void 0) return {
3086
+ kind: "model",
3087
+ ...target.model
3088
+ };
2492
3089
  const storage = {
2493
3090
  kind: "storage",
2494
3091
  name: target.storageName
@@ -2510,7 +3107,11 @@ function subjectOf(target, context) {
2510
3107
  const column = context.origins.originColumn(origin, target.table.column);
2511
3108
  for (const model of [...models].sort((a, b) => Number(b.isRoot) - Number(a.isRoot))) {
2512
3109
  const field = Object.entries(model.fields).find(([, stored]) => stored.column === column)?.[0];
2513
- if (field !== void 0) return {
3110
+ if (field === void 0) continue;
3111
+ return isRemovedVariant(model.coordinate, context) ? {
3112
+ kind: "model",
3113
+ ...model.coordinate
3114
+ } : {
2514
3115
  kind: "field",
2515
3116
  ...model.coordinate,
2516
3117
  field
@@ -2548,9 +3149,12 @@ function subjectsOfCalls(calls, context) {
2548
3149
  const temporaryValues = [];
2549
3150
  let operationIndex = 0;
2550
3151
  for (const call of calls) {
2551
- for (const { table, column, value } of call.temporaryValues) temporaryValues.push({
3152
+ for (const { table, column, value, valueObjectField } of call.temporaryValues) temporaryValues.push({
2552
3153
  operationIndex,
2553
- subject: fieldOfColumn(context.contract, table, column) ?? {
3154
+ subject: valueObjectField !== void 0 ? {
3155
+ kind: "valueObjectField",
3156
+ ...valueObjectField
3157
+ } : fieldOfColumn(context.contract, table, column) ?? {
2554
3158
  kind: "storage",
2555
3159
  name: `${table}.${column}`
2556
3160
  },
@@ -2563,7 +3167,7 @@ function subjectsOfCalls(calls, context) {
2563
3167
  subject,
2564
3168
  loss: target.loss,
2565
3169
  label: call.label,
2566
- ...ifDefined("keepDataAdvice", keepTableAdvice(target, subject, context)),
3170
+ ...ifDefined("keepDataAdvice", target.keepDataAdvice ?? keepTableAdvice(target, subject, context)),
2567
3171
  ...ifDefined("keepDataEdit", target.keepDataEdit)
2568
3172
  });
2569
3173
  }
@@ -2735,24 +3339,34 @@ function migrationRange(edges, operationIndex, operationCount) {
2735
3339
  };
2736
3340
  }
2737
3341
  /**
2738
- * The marks of the steps of `operations` that belong to the same migration as the operation at
2739
- * `operationIndex`, in plan order: `edges` say how many operations each migration of the plan has.
3342
+ * The steps of `operations` that belong to the same migration as the operation at `operationIndex`
3343
+ * and carry a mark `markOf` reads, in plan order: `edges` say how many operations each migration of
3344
+ * the plan has.
2740
3345
  */
2741
- function requiredColumnsOfMigration(operations, edges, operationIndex) {
3346
+ function marksOfMigration(operations, edges, operationIndex, markOf) {
2742
3347
  const { start, end } = migrationRange(edges, operationIndex, operations.length);
2743
3348
  return operations.slice(start, end).flatMap((operation, offset) => [
2744
3349
  ...operation.precheck,
2745
3350
  ...operation.execute,
2746
3351
  ...operation.postcheck
2747
3352
  ].flatMap((step) => {
2748
- const required = requiredColumnOf(step);
2749
- return required === void 0 ? [] : [{
3353
+ const mark = markOf(step);
3354
+ return mark === void 0 ? [] : [{
2750
3355
  operation,
2751
3356
  operationIndex: start + offset,
2752
- required
3357
+ step,
3358
+ mark
2753
3359
  }];
2754
3360
  }));
2755
3361
  }
3362
+ /** The marks of the steps that mark a column as becoming required, as {@link marksOfMigration} finds them. */
3363
+ function requiredColumnsOfMigration(operations, edges, operationIndex) {
3364
+ return marksOfMigration(operations, edges, operationIndex, requiredColumnOf).map(({ operation, operationIndex: index, mark }) => ({
3365
+ operation,
3366
+ operationIndex: index,
3367
+ required: mark
3368
+ }));
3369
+ }
2756
3370
  /**
2757
3371
  * A runner failure's summary and reports for the rows that columns becoming required have no value
2758
3372
  * in. The failed operation's marks are counted first, and the first of them with such rows is the
@@ -2797,7 +3411,11 @@ const RowsHoldingValueMeta = type({ rowsHoldingValue: {
2797
3411
  "codecRef?": {
2798
3412
  codecId: "string",
2799
3413
  "typeParams?": "unknown"
2800
- }
3414
+ },
3415
+ table: "string",
3416
+ column: "string",
3417
+ storedValue: "string | number",
3418
+ "path?": "string"
2801
3419
  } });
2802
3420
  /**
2803
3421
  * The meta of the check before a stored enum value is removed from a column: it fails while rows
@@ -2810,7 +3428,7 @@ function rowsHoldingValueMeta(mark) {
2810
3428
  function rowsHoldingValueOf(step) {
2811
3429
  const meta = RowsHoldingValueMeta(step.meta ?? {});
2812
3430
  if (meta instanceof type.errors) return void 0;
2813
- const { enumValue, value, codecRef } = meta.rowsHoldingValue;
3431
+ const { enumValue, value, codecRef, table, column, storedValue, path } = meta.rowsHoldingValue;
2814
3432
  return {
2815
3433
  enumValue: {
2816
3434
  ...enumValue.namespaceId === void 0 ? {} : { namespaceId: asNamespaceId(enumValue.namespaceId) },
@@ -2818,7 +3436,11 @@ function rowsHoldingValueOf(step) {
2818
3436
  member: enumValue.member
2819
3437
  },
2820
3438
  value,
2821
- ...codecRef === void 0 ? {} : { codecRef: codecRefOf(codecRef) }
3439
+ ...codecRef === void 0 ? {} : { codecRef: codecRefOf(codecRef) },
3440
+ table,
3441
+ column,
3442
+ storedValue,
3443
+ ...ifDefined("path", path)
2822
3444
  };
2823
3445
  }
2824
3446
  function codecRefOf(codecRef) {
@@ -2827,9 +3449,67 @@ function codecRefOf(codecRef) {
2827
3449
  typeParams: blindCast(codecRef.typeParams)
2828
3450
  };
2829
3451
  }
2830
- /** What a runner failure says of the rows that hold a stored value a column cannot lose: the value as the database stores it. */
2831
- function rowsHoldingValueSummary(table, column, storedValue, rows) {
2832
- return `${`${rows} ${rows === 1 ? "row" : "rows"} of "${table}"`} ${rows === 1 ? "holds" : "hold"} ${JSON.stringify(storedValue)} in column "${column}", which takes no NULL, so the value cannot be removed.`;
3452
+ function holdingText(place, rows) {
3453
+ const holds = `${`${rows} ${rows === 1 ? "row" : "rows"} of "${place.table}"`} ${rows === 1 ? "holds" : "hold"} ${JSON.stringify(place.storedValue)}`;
3454
+ return place.path === void 0 ? `${holds} in column "${place.column}"` : `${holds} at path ${JSON.stringify(place.path)} in column "${place.column}"`;
3455
+ }
3456
+ /** What a runner failure says of the rows that hold a stored value a column, or a member at a path inside it, cannot lose: the value as the database stores it. */
3457
+ function rowsHoldingValueSummary(place, rows) {
3458
+ const holds = holdingText(place, rows);
3459
+ return place.path === void 0 ? `${holds}, which takes no NULL, so the value cannot be removed.` : `${holds}, a member that takes no null, so the value cannot be removed.`;
3460
+ }
3461
+ /** The marked removal checks of the migration of the operation at `operationIndex`, in plan order. */
3462
+ function removalsOfMigration(operations, edges, operationIndex) {
3463
+ return marksOfMigration(operations, edges, operationIndex, rowsHoldingValueOf).map(({ operation, operationIndex: index, step, mark }) => ({
3464
+ operation,
3465
+ operationIndex: index,
3466
+ check: step,
3467
+ mark
3468
+ }));
3469
+ }
3470
+ /**
3471
+ * A runner failure's summary and reports for the rows that hold stored values removals cannot take
3472
+ * out of required columns. The failed removal is counted first, and the summary names it; undefined
3473
+ * when that count fails. Then each other removal of `others` whose check `checkFails` says fails is
3474
+ * counted, until a count fails, such as for a column an earlier operation adds, so that the advice
3475
+ * can name every column that still holds a removed value.
3476
+ */
3477
+ async function rowsHoldingValueFailure(input) {
3478
+ const { failed } = input;
3479
+ const report = (removal, rows) => ({
3480
+ enumValue: removal.mark.enumValue,
3481
+ value: removal.mark.storedValue,
3482
+ rows,
3483
+ operationIndex: removal.operationIndex,
3484
+ ...ifDefined("keepDataEdit", input.keepDataEdit(removal))
3485
+ });
3486
+ let rows;
3487
+ try {
3488
+ rows = await input.count(failed);
3489
+ } catch {
3490
+ return;
3491
+ }
3492
+ const counted = [{
3493
+ removal: failed,
3494
+ rows
3495
+ }];
3496
+ for (const other of input.others) {
3497
+ if (other.operationIndex === failed.operationIndex) continue;
3498
+ let otherRows;
3499
+ try {
3500
+ otherRows = await input.checkFails(other) ? await input.count(other) : 0;
3501
+ } catch {
3502
+ break;
3503
+ }
3504
+ if (otherRows > 0) counted.push({
3505
+ removal: other,
3506
+ rows: otherRows
3507
+ });
3508
+ }
3509
+ return {
3510
+ summary: counted.length === 1 ? rowsHoldingValueSummary(failed.mark, rows) : ["Rows hold values that the migration removes where no null is allowed, so the values cannot be removed:", ...counted.map((each) => `- ${holdingText(each.removal.mark, each.rows)}`)].join("\n"),
3511
+ reports: counted.map((each) => report(each.removal, each.rows))
3512
+ };
2833
3513
  }
2834
3514
  /** Keywords that end an expression and continue the statement around it. */
2835
3515
  const STATEMENT_KEYWORDS = /* @__PURE__ */ new Set([
@@ -2948,6 +3628,426 @@ function sqlTypeLookupsOf(frameworkComponents) {
2948
3628
  dataTypeLookup: assembleDataTypes(frameworkComponents).lookup
2949
3629
  };
2950
3630
  }
3631
+ /** The edit that keeps the data a removal loses: the removal, replaced by the replacements, in order. */
3632
+ function keepDataEdit(removal, replacements, classes) {
3633
+ return {
3634
+ remove: removal.renderTypeScript(),
3635
+ replaceWith: replacements.map((replacement) => classes.replacementOf(removal, replacement).renderTypeScript()).join(", ")
3636
+ };
3637
+ }
3638
+ /**
3639
+ * The enum value each removal is about, with the edit that keeps its data when the member keeps
3640
+ * its name and only its stored value changes.
3641
+ */
3642
+ function storedValueSubjects(calls, classes) {
3643
+ const subjects = /* @__PURE__ */ new Map();
3644
+ for (const [call, rewrite] of calls) {
3645
+ if (!classes.isRemoval(call)) continue;
3646
+ subjects.set(call, {
3647
+ enumValue: rewrite.enumValue,
3648
+ ...ifDefined("keepDataEdit", rewrite.keepData === void 0 ? void 0 : {
3649
+ ...keepDataEdit(call, rewrite.keepData, classes),
3650
+ ...rewrite.swapsValues ? { swapsValues: true } : {}
3651
+ })
3652
+ });
3653
+ }
3654
+ return subjects;
3655
+ }
3656
+ /**
3657
+ * The edit that keeps the data a failed removal check found: `removal`, the call the check's mark
3658
+ * and its column describe, replaced by a replacement whose new value is the placeholder
3659
+ * `"<stored value>"`.
3660
+ */
3661
+ function keepRowsEdit(removal, mark, classes) {
3662
+ return keepDataEdit(removal, [{
3663
+ from: mark.value,
3664
+ to: "<stored value>"
3665
+ }], classes);
3666
+ }
3667
+ function operationCount(call) {
3668
+ return "companions" in call && Array.isArray(call.companions) ? 1 + call.companions.length : 1;
3669
+ }
3670
+ /** The positions, among the plan's operations, of the operations that carry out `statement`. */
3671
+ function storedValueOperationIndexes(planCalls, calls, statement) {
3672
+ const indexes = [];
3673
+ let position = 0;
3674
+ for (const call of planCalls) {
3675
+ if (calls.get(call)?.statement === statement) indexes.push(position);
3676
+ position += operationCount(call);
3677
+ }
3678
+ return indexes;
3679
+ }
3680
+ /** A value a planner-written operation takes from the user: its `migration.ts` writes `placeholder(slot)` where the value goes. */
3681
+ var UnfilledValue = class {
3682
+ slot;
3683
+ constructor(slot) {
3684
+ this.slot = slot;
3685
+ Object.freeze(this);
3686
+ }
3687
+ };
3688
+ /**
3689
+ * A policy that allows `data` operations plans a migration whose `migration.ts` the user can fill,
3690
+ * so it refuses; any other, as `db update` runs, fills a temporary value, as it does for a new
3691
+ * required column. It assumes that a policy that allows `data` operations means a `migration.ts` is
3692
+ * written, which holds while `migration plan` is the only command whose planner policy allows them.
3693
+ */
3694
+ function unnamedFieldFillOf(policy) {
3695
+ return policy.allowedOperationClasses.includes("data") ? "refuse" : "temporaryValue";
3696
+ }
3697
+ const TEMPORARY_JSON_VALUES = {
3698
+ string: "",
3699
+ number: 0,
3700
+ boolean: false,
3701
+ object: {},
3702
+ array: []
3703
+ };
3704
+ /**
3705
+ * The temporary value of a field, as JSON: an empty list for any list, and for a scalar the empty
3706
+ * value of the JSON type its codec declares, when the codec's data type takes it. A field that
3707
+ * holds one value object or one enum value has none, since no one value stands for every object or
3708
+ * member; nor does a scalar whose data type refuses the empty value, as a date refuses `""`. Without
3709
+ * one, the result says why.
3710
+ */
3711
+ function temporaryValueOf(field, types) {
3712
+ if (field.many !== void 0 && field.many !== false) return ok([]);
3713
+ if (field.type.kind !== "scalar") return notOk("it holds a value object, and no one value stands for every object");
3714
+ if (field.valueSet !== void 0) return notOk("it holds an enum value, and no one member stands for every object");
3715
+ const codecRef = buildColumnCodecRef(field.type, void 0);
3716
+ const descriptor = types.codecLookup.descriptorFor(codecRef.codecId);
3717
+ const jsonType = descriptor === void 0 ? void 0 : declaredJsonType(descriptor);
3718
+ const empty = jsonType === void 0 ? void 0 : TEMPORARY_JSON_VALUES[jsonType];
3719
+ if (empty === void 0) return notOk(`its codec ${JSON.stringify(codecRef.codecId)} declares no JSON type, so it has no empty value`);
3720
+ return acceptedByDataType(empty, codecRef, types) ? ok(empty) : notOk(`the data type of its codec ${JSON.stringify(codecRef.codecId)} does not take the empty value ${JSON.stringify(empty)}`);
3721
+ }
3722
+ function sameField(left, right) {
3723
+ return left.namespaceId === right.namespaceId && left.valueObject === right.valueObject && left.field === right.field;
3724
+ }
3725
+ /** The fields each value object of both contracts makes required: new to the destination, or optional in the origin. */
3726
+ function requiredFields(fromContract, contract, statements) {
3727
+ const originNamespaces = /* @__PURE__ */ new Map();
3728
+ const renamedFrom = /* @__PURE__ */ new Map();
3729
+ const backfills = [];
3730
+ for (const statement of statements) {
3731
+ if (statement.kind === "backfill" && statement.entity === "valueObjectField") backfills.push(statement);
3732
+ if (statement.kind !== "rename") continue;
3733
+ if (statement.entity === "namespace") originNamespaces.set(statement.to, statement.from);
3734
+ if (statement.entity === "valueObjectField") renamedFrom.set(JSON.stringify(statement.to), statement.from);
3735
+ }
3736
+ const fields = [];
3737
+ for (const { coordinate, valueObject } of valueObjectsWithCoordinates(contract.storage)) {
3738
+ const origin = valueObjectAt(fromContract.storage, {
3739
+ ...coordinate,
3740
+ namespaceId: originNamespaces.get(coordinate.namespaceId) ?? coordinate.namespaceId
3741
+ });
3742
+ if (origin === void 0) continue;
3743
+ const renamedFields = new Set([...renamedFrom.values()].filter((from) => from.valueObject === coordinate.entityName).map((from) => from.field));
3744
+ const removedFields = Object.keys(origin.fields).filter((name) => !Object.hasOwn(valueObject.fields, name) && !renamedFields.has(name));
3745
+ for (const [name, field] of Object.entries(valueObject.fields)) {
3746
+ if (field.nullable) continue;
3747
+ const valueObjectField = {
3748
+ namespaceId: asNamespaceId(coordinate.namespaceId),
3749
+ valueObject: coordinate.entityName,
3750
+ field: name
3751
+ };
3752
+ const originName = renamedFrom.get(JSON.stringify(valueObjectField))?.field ?? name;
3753
+ const originField = Object.hasOwn(origin.fields, originName) ? origin.fields[originName] : void 0;
3754
+ if (originField !== void 0 && !originField.nullable) continue;
3755
+ fields.push({
3756
+ valueObjectField,
3757
+ target: coordinate,
3758
+ field,
3759
+ statement: backfills.find((backfill) => sameField(backfill.field, valueObjectField)),
3760
+ removedFields: originField === void 0 ? removedFields : []
3761
+ });
3762
+ }
3763
+ }
3764
+ return fields;
3765
+ }
3766
+ function backfillAdvice(contract, required, text) {
3767
+ const backfill = `--backfill ${text} to write the value the plan fills them with.`;
3768
+ if (required.removedFields.length === 0) return `Add ${backfill}`;
3769
+ const removed = required.removedFields.map((field) => valueObjectFieldStatementText(contract, {
3770
+ ...required.valueObjectField,
3771
+ field
3772
+ }));
3773
+ return `If it is a field renamed, add ${removed.map((from) => `--rename ${from}:${text}`).join(" or ")}. Otherwise add ${backfill} With ${removed.map((from) => `--delete ${from}`).join(" or ")}, the new field still needs --backfill ${text}.`;
3774
+ }
3775
+ function placeText(place) {
3776
+ return `path ${JSON.stringify(jsonPathText(place.steps))} in column "${place.column}" of "${place.table}"`;
3777
+ }
3778
+ function needsValue(required, places, text, why) {
3779
+ const [place] = places;
3780
+ return {
3781
+ kind: "nullabilityConflict",
3782
+ summary: `Value object field "${text}" is required, and existing objects may have no value for it, at:\n${places.map((each) => `- ${placeText(each)}`).join("\n")}`,
3783
+ why,
3784
+ location: {
3785
+ namespaceId: place.namespaceId,
3786
+ entityKind: "table",
3787
+ entityName: place.table,
3788
+ column: place.column
3789
+ },
3790
+ meta: { valueObjectField: required.valueObjectField }
3791
+ };
3792
+ }
3793
+ function unlisted(text, column, table, reason) {
3794
+ return {
3795
+ kind: "unsupportedOperation",
3796
+ summary: `Cannot fill value object field "${text}": column "${column}" of "${table}" holds ${reason}`,
3797
+ why: `The plan fills a key at every path from a column to its value object, and it cannot list the paths in such a column. ${handWrittenMigrationAdvice(`the JSON of column "${column}" of "${table}"`)}`
3798
+ };
3799
+ }
3800
+ const REACH_REASONS = {
3801
+ containsItself: "it inside a value object that contains itself",
3802
+ union: "a union of value objects",
3803
+ dictionary: "a dictionary of value objects"
3804
+ };
3805
+ function fillAt(required, place, text, value) {
3806
+ return {
3807
+ valueObjectField: required.valueObjectField,
3808
+ namespaceId: place.namespaceId,
3809
+ table: place.table,
3810
+ column: place.column,
3811
+ path: jsonPathText([...place.steps, {
3812
+ kind: "member",
3813
+ name: required.valueObjectField.field
3814
+ }]),
3815
+ value,
3816
+ field: text,
3817
+ statement: required.statement
3818
+ };
3819
+ }
3820
+ /**
3821
+ * The fills of value object fields a plan makes. A field of a value object that both contracts have
3822
+ * is filled when the destination makes it required and the origin lacks it or makes it optional. A
3823
+ * backfill statement fills it with a value the user writes in `migration.ts`. Without one,
3824
+ * `unnamed` decides: `refuse` names the statement, and `temporaryValue` fills a scalar field whose
3825
+ * codec has a temporary value its data type takes, and refuses any other. Under `refuse`, when the
3826
+ * value object also lost a field no statement renames, the refusal offers that rename first. Each
3827
+ * fill acts on every column of the working schema whose field holds the value object, at every path to its objects, nested or in lists, as
3828
+ * the destination names them. A column that holds the value object where its paths cannot be listed
3829
+ * is refused. With no origin contract, nothing is known to have changed.
3830
+ */
3831
+ function planValueObjectFieldFills(input) {
3832
+ const { fromContract, contract } = input;
3833
+ if (fromContract === null) return ok([]);
3834
+ const newlyRequired = requiredFields(fromContract, contract, input.statements);
3835
+ if (newlyRequired.length === 0) return ok([]);
3836
+ const placesOf = valueObjectPlaces(contract, input.tables);
3837
+ const fills = [];
3838
+ for (const required of newlyRequired) {
3839
+ const text = valueObjectFieldStatementText(contract, required.valueObjectField);
3840
+ const places = placesOf(required.target);
3841
+ if (!places.ok) {
3842
+ const { column, reach } = places.failure;
3843
+ return notOk(unlisted(text, column.column, column.table, REACH_REASONS[reach.kind]));
3844
+ }
3845
+ const [first, ...rest] = places.value;
3846
+ if (first === void 0) continue;
3847
+ const temporary = required.statement === void 0 && input.unnamed === "temporaryValue" ? temporaryValueOf(required.field, input.types) : void 0;
3848
+ if (temporary !== void 0 && !temporary.ok) return notOk(needsValue(required, [first, ...rest], text, `db update cannot choose a value for field "${text}": ${temporary.failure}. Plan a migration with prisma migration plan --backfill ${text} instead, and write the value in its migration.ts.`));
3849
+ const value = temporary !== void 0 ? temporary.value : required.statement !== void 0 ? new UnfilledValue(`${text}:value`) : void 0;
3850
+ if (value === void 0) return notOk(needsValue(required, [first, ...rest], text, backfillAdvice(contract, required, text)));
3851
+ fills.push(...places.value.map((place) => fillAt(required, place, text, value)));
3852
+ }
3853
+ return ok(fills);
3854
+ }
3855
+ function modelAt(contract, coordinate) {
3856
+ const namespaces = contract.domain.namespaces;
3857
+ const namespace = Object.hasOwn(namespaces, coordinate.namespaceId) ? namespaces[coordinate.namespaceId] : void 0;
3858
+ return namespace !== void 0 && Object.hasOwn(namespace.models, coordinate.model) ? namespace.models[coordinate.model] : void 0;
3859
+ }
3860
+ function baseOf(contract, variant) {
3861
+ const base = modelAt(contract, variant)?.base;
3862
+ return base === void 0 ? void 0 : {
3863
+ namespaceId: asNamespaceId(base.namespace),
3864
+ model: base.model
3865
+ };
3866
+ }
3867
+ function variantValue(contract, variant) {
3868
+ const base = baseOf(contract, variant);
3869
+ if (base === void 0) return void 0;
3870
+ return Object.entries(modelAt(contract, base)?.variants ?? {}).find(([, reference]) => reference.namespace === variant.namespaceId && reference.model === variant.model)?.[0];
3871
+ }
3872
+ /** The discriminator column of `base` in the destination, when a managed table of the working schema has it. */
3873
+ function discriminatorColumn(contract, base, tables) {
3874
+ const model = modelAt(contract, base);
3875
+ const discriminator = model?.discriminator;
3876
+ if (model === void 0 || discriminator === void 0 || !isSqlModelStorage(model.storage)) return;
3877
+ const { namespaceId, table } = model.storage;
3878
+ const column = model.storage.fields[discriminator.field]?.column;
3879
+ if (column === void 0 || !tables.hasColumn(namespaceId, table, column)) return void 0;
3880
+ if (tableControlPolicy(contract, {
3881
+ namespaceId,
3882
+ table
3883
+ }) !== "managed") return void 0;
3884
+ const stored = contract.storage.namespaces[namespaceId]?.entries.table?.[table]?.columns[column];
3885
+ if (stored === void 0) return void 0;
3886
+ return {
3887
+ namespaceId,
3888
+ table,
3889
+ column,
3890
+ codecRef: buildColumnCodecRef(stored, void 0)
3891
+ };
3892
+ }
3893
+ /** The destination variant's own table, when it has one whose foreign key to the base table cascades. */
3894
+ function cascadingTableOf(contract, variant, base) {
3895
+ const model = modelAt(contract, variant);
3896
+ if (model === void 0 || !isSqlModelStorage(model.storage)) return void 0;
3897
+ const { namespaceId, table } = model.storage;
3898
+ if (namespaceId === base.namespaceId && table === base.table) return void 0;
3899
+ const foreignKey = contract.storage.namespaces[namespaceId]?.entries.table?.[table]?.foreignKeys.find(({ target, onDelete }) => onDelete === "cascade" && target.namespaceId === base.namespaceId && target.tableName === base.table);
3900
+ return foreignKey === void 0 ? void 0 : {
3901
+ namespaceId,
3902
+ table,
3903
+ columns: foreignKey.source.columns,
3904
+ references: foreignKey.target.columns
3905
+ };
3906
+ }
3907
+ function sameModel(left, right) {
3908
+ return left.namespaceId === right.namespaceId && left.model === right.model;
3909
+ }
3910
+ function originVariants(contract) {
3911
+ return Object.entries(contract.domain.namespaces).flatMap(([namespaceId, namespace]) => Object.entries(namespace.models).flatMap(([model, definition]) => definition.base === void 0 ? [] : [{
3912
+ namespaceId: asNamespaceId(namespaceId),
3913
+ model
3914
+ }]));
3915
+ }
3916
+ /** Where a model of the origin is in the destination, after the plan's namespace and model renames. */
3917
+ function destinationOf(model, statements) {
3918
+ const rename = statements.find((statement) => statement.kind === "rename" && statement.entity === "model" && sameModel(statement.from, model));
3919
+ if (rename !== void 0) return {
3920
+ coordinate: rename.to,
3921
+ rename
3922
+ };
3923
+ const namespace = statements.find((statement) => statement.kind === "rename" && statement.entity === "namespace" && statement.from === model.namespaceId);
3924
+ return {
3925
+ coordinate: namespace?.kind === "rename" && namespace.entity === "namespace" ? {
3926
+ ...model,
3927
+ namespaceId: namespace.to
3928
+ } : model,
3929
+ rename: void 0
3930
+ };
3931
+ }
3932
+ function rewriteOf(model, input) {
3933
+ const from = variantValue(input.fromContract, model);
3934
+ const originBase = baseOf(input.fromContract, model);
3935
+ if (from === void 0 || originBase === void 0) return void 0;
3936
+ const destination = destinationOf(model, input.statements);
3937
+ const to = variantValue(input.contract, destination.coordinate);
3938
+ const removed = modelAt(input.contract, destination.coordinate) === void 0;
3939
+ if (to === from || to === void 0 && !removed) return void 0;
3940
+ const base = baseOf(input.contract, destination.coordinate) ?? destinationOf(originBase, input.statements).coordinate;
3941
+ const column = discriminatorColumn(input.contract, base, input.tables);
3942
+ if (column === void 0) return void 0;
3943
+ const convert = input.statements.find((statement) => statement.kind === "convert" && statement.entity === "model" && sameModel(statement.model, destination.coordinate));
3944
+ const statement = to === void 0 ? void 0 : destination.rename ?? convert;
3945
+ return {
3946
+ model,
3947
+ ...column,
3948
+ from,
3949
+ to: statement === void 0 ? void 0 : to,
3950
+ removed,
3951
+ cascadingTable: cascadingTableOf(input.contract, destination.coordinate, column),
3952
+ statement
3953
+ };
3954
+ }
3955
+ function chainRefusal(rewrite, other, contract) {
3956
+ return {
3957
+ kind: "unsupportedOperation",
3958
+ summary: `Cannot rewrite discriminator value "${rewrite.from}" of variant "${modelStatementText(contract, rewrite.model)}" to "${rewrite.to}": variant "${modelStatementText(contract, other.model)}" moves from that value in the same column`,
3959
+ why: `Column "${rewrite.column}" of "${rewrite.table}" would hold one value for rows of two variants while the plan rewrites them. Change one discriminator value in this migration and the other in a later one.`
3960
+ };
3961
+ }
3962
+ /**
3963
+ * The row rewrites a plan makes for the variants of the origin whose discriminator value the
3964
+ * destination changes or drops. A rename or convert statement rewrites a changed value in the base
3965
+ * table's discriminator column; a changed value with no statement, and a variant the destination no
3966
+ * longer has, delete the rows that hold the old value, which the plan asks about. Deletions come
3967
+ * first, so a value freed by a deleted variant can be taken by another. A rewrite whose new value
3968
+ * another variant still moves from is refused. With no origin contract, nothing is known to have
3969
+ * changed.
3970
+ */
3971
+ function planVariantRowRewrites(input) {
3972
+ const { fromContract } = input;
3973
+ if (fromContract === null) return ok([]);
3974
+ const rewrites = originVariants(fromContract).flatMap((model) => {
3975
+ const rewrite = rewriteOf(model, {
3976
+ ...input,
3977
+ fromContract
3978
+ });
3979
+ return rewrite === void 0 ? [] : [rewrite];
3980
+ });
3981
+ const sameColumn = (left, right) => left.namespaceId === right.namespaceId && left.table === right.table && left.column === right.column;
3982
+ for (const rewrite of rewrites) {
3983
+ if (rewrite.to === void 0) continue;
3984
+ const other = rewrites.find((candidate) => candidate !== rewrite && candidate.to !== void 0 && sameColumn(candidate, rewrite) && candidate.from === rewrite.to);
3985
+ if (other !== void 0) return notOk(chainRefusal(rewrite, other, fromContract));
3986
+ }
3987
+ return ok([...rewrites.filter(({ to }) => to === void 0), ...rewrites.filter(({ to }) => to !== void 0)]);
3988
+ }
3989
+ /**
3990
+ * The stored rewrites of a plan, as the target's calls: the key rewrites and fills of value object
3991
+ * fields, the stored value rewrites of enum values, and the row rewrites of variants. The first
3992
+ * kind a plan refuses is the plan's failure.
3993
+ */
3994
+ function planStoredRewrites(input) {
3995
+ const { statements, fromContract, contract, tables, types } = input;
3996
+ const keyRewrites = planValueObjectFieldRewrites({
3997
+ statements,
3998
+ fromContract,
3999
+ contract,
4000
+ tables
4001
+ });
4002
+ if (!keyRewrites.ok) return notOk(keyRewrites.failure);
4003
+ const fills = planValueObjectFieldFills({
4004
+ statements,
4005
+ fromContract,
4006
+ contract,
4007
+ tables,
4008
+ types,
4009
+ unnamed: unnamedFieldFillOf(input.policy)
4010
+ });
4011
+ if (!fills.ok) return notOk(fills.failure);
4012
+ const valueRewrites = planEnumValueRewrites({
4013
+ statements,
4014
+ fromContract,
4015
+ contract,
4016
+ tables,
4017
+ codecs: types.codecLookup
4018
+ });
4019
+ if (!valueRewrites.ok) return notOk(valueRewrites.failure);
4020
+ const variantRewrites = planVariantRowRewrites({
4021
+ statements,
4022
+ fromContract,
4023
+ contract,
4024
+ tables
4025
+ });
4026
+ if (!variantRewrites.ok) return notOk(variantRewrites.failure);
4027
+ const storedKeyCalls = input.calls.storedKeyCalls(keyRewrites.value);
4028
+ const storedKeyFillCalls = input.calls.storedKeyFillCalls(fills.value);
4029
+ const storedValueCalls = input.calls.storedValueCalls(valueRewrites.value);
4030
+ const variantRowCalls = input.calls.variantRowCalls(variantRewrites.value);
4031
+ const rewrites = new Map([
4032
+ ...storedKeyCalls,
4033
+ ...storedKeyFillCalls,
4034
+ ...storedValueCalls,
4035
+ ...variantRowCalls
4036
+ ]);
4037
+ return ok({
4038
+ calls: [
4039
+ ...storedKeyCalls.keys(),
4040
+ ...storedKeyFillCalls.keys(),
4041
+ ...storedValueCalls.keys(),
4042
+ ...variantRowCalls.keys()
4043
+ ],
4044
+ operationIndexes: (planCalls, statement) => storedValueOperationIndexes(planCalls, rewrites, statement),
4045
+ storedValues: storedValueSubjects(storedValueCalls, input.calls.storedValueClasses),
4046
+ storedKeys: new Map([...storedKeyCalls, ...storedKeyFillCalls].map(([call, change]) => [call, change.valueObjectField])),
4047
+ variantRows: new Map([...variantRowCalls].map(([call, rewrite]) => [call, rewrite.model])),
4048
+ removedVariants: variantRewrites.value.flatMap(({ model, removed }) => removed ? [model] : [])
4049
+ });
4050
+ }
2951
4051
  const TABLE_NAME_CASE_CHANGED_CODE = "MIGRATION.TABLE_NAME_CASE_CHANGED";
2952
4052
  function lowerFirst(value) {
2953
4053
  return value.charAt(0).toLowerCase() + value.slice(1);
@@ -3143,6 +4243,6 @@ function columnCodecRef(codecId, column) {
3143
4243
  }
3144
4244
  var control_default = new SqlFamilyDescriptor();
3145
4245
  //#endregion
3146
- export { sqlTypeLookupsOf as $, planEnumValueRewrites as A, requiredColumnsOfMigration as B, fieldRenameStorageEffect as C, otherSpaceDeclaring as D, modelRenameStorageEffect as E, plannerSuccess as F, rowsHoldingValueSummary as G, resolveTableRenameAgainst as H, readColumnDefault as I, runnerFailure as J, rowsWithoutValueFailure as K, readReportedDefault as L, planFieldEventOperations as M, planStatements as N, partitionCallsByControlPolicy as O, plannerFailure as P, sqlOfSlot as Q, requiredColumnMeta as R, fieldOfColumn as S, isUnfilledSlot as T, rowsHoldingValueMeta as U, resolveColumnRenameAgainst as V, rowsHoldingValueOf as W, slotSource as X, runnerSuccess as Y, sqlDefaultFunctions as Z, createSqlTextSources as _, appliedStatementsInOrder as a, unmatchedTableRename as at, encodeStoredValue as b, checkSqlExpressionText as c, contractNamespaceToSchemaIR as d, storageNameOfOperation as et, contractToSchemaIR as f, createMigrationPlan as g, convertedColumnOf as h, TABLE_NAME_CASE_CHANGED_CODE as i, unmatchedColumnRename as it, planFieldEventCalls as j, partitionIssuesByControlPolicy as k, columnTakesTemporaryValue as l, convertedColumnMeta as m, INIT_ADDITIVE_POLICY as n, unconvertedFieldOf as nt, assembleAuthoringContributions$1 as o, withEnumValueOperations as ot, control_default as p, rowsWithoutValueSummary as q, NO_RENAMED_ORIGINS as r, unknownCallNames as rt, backfillOfDefaultedField as s, COLUMN_RENAME_UNMATCHED_CODE as t, subjectsOfCalls as tt, contractColumns as u, detectDestructiveChanges as v, fieldStatementColumns as w, fieldEventStorage as x, detectTableNameCaseChanges as y, requiredColumnOf as z };
4246
+ export { requiredColumnsOfMigration as $, jsonPathText as A, planFieldEventOperations as B, fieldEventStorage as C, fillKeyProblem as D, fieldStatementColumns as E, parseJsonPath as F, planVariantRowRewrites as G, planStoredRewrites as H, partitionCallsByControlPolicy as I, readColumnDefault as J, plannerFailure as K, partitionIssuesByControlPolicy as L, keyPathOf as M, modelRenameStorageEffect as N, fillValueProblem as O, otherSpaceDeclaring as P, requiredColumnOf as Q, planEnumValueRewrites as R, encodeStoredValue as S, unnamedFieldFillOf as St, fieldRenameStorageEffect as T, planValueObjectFieldFills as U, planStatements as V, planValueObjectFieldRewrites as W, removalsOfMigration as X, readReportedDefault as Y, requiredColumnMeta as Z, convertedColumnOf as _, subjectsOfCalls as _t, UnfilledValue as a, rowsWithoutValueFailure as at, detectDestructiveChanges as b, unmatchedColumnRename as bt, assembleAuthoringContributions$1 as c, runnerSuccess as ct, columnTakesTemporaryValue as d, sqlDefaultFunctions as dt, resolveColumnRenameAgainst as et, contractColumns as f, sqlOfSlot as ft, convertedColumnMeta as g, storedValueSubjects as gt, control_default as h, storedValueOperationIndexes as ht, TABLE_NAME_CASE_CHANGED_CODE as i, rowsHoldingValueOf as it, keepRowsEdit as j, isUnfilledSlot as k, backfillOfDefaultedField as l, scalarTypeNamesOf as lt, contractToSchemaIR as m, storageNameOfOperation as mt, INIT_ADDITIVE_POLICY as n, rowsHoldingValueFailure as nt, acceptedByDataType as o, rowsWithoutValueSummary as ot, contractNamespaceToSchemaIR as p, sqlTypeLookupsOf as pt, plannerSuccess as q, NO_RENAMED_ORIGINS as r, rowsHoldingValueMeta as rt, appliedStatementsInOrder as s, runnerFailure as st, COLUMN_RENAME_UNMATCHED_CODE as t, resolveTableRenameAgainst as tt, checkSqlExpressionText as u, slotSource as ut, createMigrationPlan as v, unconvertedFieldOf as vt, fieldOfColumn as w, detectTableNameCaseChanges as x, unmatchedTableRename as xt, createSqlTextSources as y, unknownCallNames as yt, planFieldEventCalls as z };
3147
4247
 
3148
- //# sourceMappingURL=control-BSX7UWk2.mjs.map
4248
+ //# sourceMappingURL=control-Ltpja41u.mjs.map