@prisma/orm-toolchain 8.0.0-rc.17-dev.37 → 8.0.0-rc.17-dev.38

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 (30) hide show
  1. package/dist/{aggregate-C0Kci0iw.mjs → aggregate-CJjYCgNP.mjs} +6 -2
  2. package/dist/aggregate-CJjYCgNP.mjs.map +1 -0
  3. package/dist/{aggregate-C23h_Ybm.d.mts → aggregate-MAVa_CD0.d.mts} +6 -2
  4. package/dist/{aggregate-C23h_Ybm.d.mts.map → aggregate-MAVa_CD0.d.mts.map} +1 -1
  5. package/dist/{caught-errors-DUV-u8yQ-DuPp394m.mjs → caught-errors-olsx_RBn-Cg0ilJtv.mjs} +133 -8
  6. package/dist/caught-errors-olsx_RBn-Cg0ilJtv.mjs.map +1 -0
  7. package/dist/cli.mjs +368 -93
  8. package/dist/cli.mjs.map +1 -1
  9. package/dist/cli__control-api.d.mts +14 -9
  10. package/dist/cli__control-api.d.mts.map +1 -1
  11. package/dist/cli__control-api.mjs +2 -2
  12. package/dist/cli__control-api__testing.d.mts +1 -1
  13. package/dist/cli__control-api__testing.mjs +1 -0
  14. package/dist/cli__control-api__testing.mjs.map +1 -1
  15. package/dist/cli__migration-cli.mjs +2 -2
  16. package/dist/cli__migration-cli.mjs.map +1 -1
  17. package/dist/{db-sign-DvCsMwUF-D5UIkRXD.d.mts → db-sign-D90hPxFE-B-YLAvFQ.d.mts} +77 -22
  18. package/dist/db-sign-D90hPxFE-B-YLAvFQ.d.mts.map +1 -0
  19. package/dist/migration-tools.d.mts +1 -1
  20. package/dist/migration-tools.mjs +1 -1
  21. package/dist/migration-tools__aggregate.d.mts +1 -1
  22. package/dist/migration-tools__aggregate.mjs +1 -1
  23. package/dist/{ref-BITTabCb-DT5r3Y3B.mjs → ref-BMhPu-wB-DU1LW2lb.mjs} +439 -160
  24. package/dist/ref-BMhPu-wB-DU1LW2lb.mjs.map +1 -0
  25. package/dist/vite-plugin-contract-emit.mjs +1 -1
  26. package/package.json +12 -12
  27. package/dist/aggregate-C0Kci0iw.mjs.map +0 -1
  28. package/dist/caught-errors-DUV-u8yQ-DuPp394m.mjs.map +0 -1
  29. package/dist/db-sign-DvCsMwUF-D5UIkRXD.d.mts.map +0 -1
  30. package/dist/ref-BITTabCb-DT5r3Y3B.mjs.map +0 -1
package/dist/cli.mjs CHANGED
@@ -1,16 +1,17 @@
1
1
  import { a as expandContractInputs, c as globContractInputMatching, d as loadConfigFiles, g as requireConfigSections, h as ormConfigSection, i as evaluateConfigModule, r as buildLoadedConfig } from "./exports-CELbmah_.mjs";
2
2
  import { t as MigrationToolsError } from "./errors-B1xJ5JTo-CrQL55Qf.mjs";
3
3
  import { t as contractSnapshotDir } from "./contract-snapshot-store-CNu34KAd-D9xN1Sll.mjs";
4
+ import { s as readMigrationsDir } from "./io-CUFeeOVP-CEgOEVwW.mjs";
4
5
  import { t as EMPTY_CONTRACT_HASH } from "./constants-CM-w38DQ-Cz_EXbOc.mjs";
5
6
  import { c as spaceMigrationDirectory, l as spaceRefsDirectory } from "./verify-contract-spaces-sL5mlmCX-K2P69KDp.mjs";
6
- import { $ as migrationsDirFor, A as errorPathUnreachable, D as errorMigrationPackageNotFound, E as errorMarkerMissing, J as errorTargetMismatch, L as errorRunnerFailed, O as errorMigrationPlanningFailed, Q as maskConnectionUrl, R as errorRuntime, S as errorHashMismatch, _ as errorContractValidationFailed, a as appRefsDirFor, at as runCommandAction, b as errorFileNotFound, c as closeQuietly, d as displayPath, et as readContractEnvelope, f as errorAdvanceRefArgConflict, g as errorContractConfigMissing, h as errorContractArgConflict, i as appMigrationsDirFor, k as errorNoMigrations, m as errorConfigValidation$1, n as CliStructuredError$1$1, nt as requireLiveDatabase, o as baseDirFor, ot as targetSupportsMigrations, q as errorTargetMigrationNotSupported, s as chooseAction, t as ActionableCliError, tt as redactUrlCredentials, u as contractPathFor, v as errorDatabaseConnectionRequired, w as errorLegendHumanOnly, x as errorFromCaught, y as errorDriverRequired, z as errorSignRefsNotWritten } from "./caught-errors-DUV-u8yQ-DuPp394m.mjs";
7
+ import { A as errorMigrationPackageNotFound, B as errorRunnerFailed, C as errorFileNotFound, D as errorLegendHumanOnly, H as errorSignRefsNotWritten, J as errorStatementNeedsMigrationFile, M as errorNoMigrations, N as errorPathUnreachable, Q as errorTargetMismatch, S as errorDriverRequired, T as errorHashMismatch, V as errorRuntime, Z as errorTargetMigrationNotSupported, _ as errorContractArgConflict, a as appRefsDirFor, at as printedPlanCommand, b as errorConvertAndDelete, c as cliCommand, ct as requireLiveDatabase, dt as runCommandAction, f as contractPathFor, ft as selfEmitCommand, g as errorConfigValidation$1, ht as targetSupportsMigrations, i as appMigrationsDirFor, it as printedPath, j as errorMigrationPlanningFailed, k as errorMarkerMissing, l as cliInvocation, m as errorAdvanceRefArgConflict, mt as statementFlag, n as CliStructuredError$1$1, nt as maskConnectionUrl, o as baseDirFor, ot as readContractEnvelope, p as displayPath, pt as shellQuoted, rt as migrationsDirFor, s as chooseAction, st as redactUrlCredentials, t as ActionableCliError, u as closeQuietly, v as errorContractConfigMissing, w as errorFromCaught, x as errorDatabaseConnectionRequired, y as errorContractValidationFailed } from "./caught-errors-olsx_RBn-Cg0ilJtv.mjs";
7
8
  import { r as getEmittedArtifactPaths } from "./exports-BP5EU7G8-CdTO3MPb.mjs";
8
9
  import { r as isInSpaceHistory } from "./graph-membership-C-5WMh1R-BUtW54H2.mjs";
9
10
  import { d as writeRef, r as readRef } from "./refs-CS997f-J-BxkRLuCE.mjs";
10
- import { a as contractHashAtMarker } from "./aggregate-C0Kci0iw.mjs";
11
+ import { a as contractHashAtMarker } from "./aggregate-CJjYCgNP.mjs";
11
12
  import { i as createScaffoldSpecifierResolver } from "./import-roots-B6vrm5bT.mjs";
12
13
  import { o as isLiveMarkerRef } from "./ref-resolution-kNMjYJ26.mjs";
13
- import { $ as refuseUnknownInvariants, A as executeRefListCommand, B as loadContractSourceWithStack, D as executeMigrationPlanCommand, E as executeMigrationNewCommand, F as listRefsByContractHash, G as migrationSpaceListEntriesFromAggregate, H as looksLikePath, I as liveMarkerUse, J as refuseContractSpaceIntegrity, K as preflightRefAdvancement, L as loadAggregateIntegrityViolations, M as findPackageByDirPath, N as formatSourceDiagnostic, P as hasMigrationPath, Q as refusePackageCorruptionOnAggregate, R as loadContractRawSafely, T as executeMigrateShowPlan, U as mapContractAtError, V as loadContractSpaceAggregateForCli, X as refuseMarkerOutsideGraph, Z as refuseMissingInvariantPath, _t as statusForMigrationHash, a as RECORDED_OR_EMPTY_CONTRACT_REF_FORMS, at as resolveMigrationRef, b as executeContractEmit, c as appliedHashesFromLedger, ct as retryCommandFor, d as buildReadAggregate, dt as runMigrationList, et as requireDatabaseForLiveMarkerUse, f as buildRefAdvancementFields, ft as selfEmitCommand, g as deriveStatusEdgeAnnotations, gt as statementFlag, h as createControlClient, ht as sourceWarningDiagnostic, i as RECORDED_CONTRACT_REF_FORMS, j as executeRefSetCommand, k as executeRefDeleteCommand, m as computeRefAdvancementName, mt as snapshotVerifierFor, n as DB_UPDATE_POLICY, nt as resolveContractRef$1, o as advanceRefSafely, p as checkSingleTarget, pt as shellQuoted, q as readMigrationRefs, r as NO_REF_ADVANCEMENT, rt as resolveContractRefToSnapshot, t as ALL_CONTRACT_REF_FORMS, tt as resolveAppTargetPath, u as buildMigrationSpaceGraphEntries, ut as runMigrationCheck, vt as toDeclaredExtensionsFromRaw, y as enumerateCheckSpaces, yt as validateLoadedContract, z as loadContractSource } from "./ref-BITTabCb-DT5r3Y3B.mjs";
14
+ import { $ as refuseMissingInvariantPath, A as executeRefDeleteCommand, B as loadContractRawSafely, D as executeMigrationNewCommand, E as executeMigrateShowPlan, F as hasMigrationPath, G as mapContractAtError, H as loadContractSourceWithStack, I as isStatementVerb, J as preflightRefAdvancement, L as listRefsByContractHash, M as executeRefSetCommand, N as findPackageByDirPath, O as executeMigrationPlanCommand, P as formatSourceDiagnostic, Q as refuseMarkerOutsideGraph, R as liveMarkerUse, U as loadContractSpaceAggregateForCli, V as loadContractSource, W as looksLikePath, X as refuseContractSpaceIntegrity, Y as readMigrationRefs, _ as deriveStatusEdgeAnnotations, _t as toDeclaredExtensionsFromRaw, a as RECORDED_OR_EMPTY_CONTRACT_REF_FORMS, at as resolveContractRefToSnapshot, b as enumerateCheckSpaces, c as appliedHashesFromLedger, d as buildReadAggregate, et as refusePackageCorruptionOnAggregate, f as buildRefAdvancementFields, ft as runMigrationCheck, g as createControlClient, gt as statusForMigrationHash, h as convertAndDelete, ht as sourceWarningDiagnostic, i as RECORDED_CONTRACT_REF_FORMS, it as resolveContractRef$1, j as executeRefListCommand, m as computeRefAdvancementName, mt as snapshotVerifierFor, n as DB_UPDATE_POLICY, nt as requireDatabaseForLiveMarkerUse, o as advanceRefSafely, p as checkSingleTarget, pt as runMigrationList, q as migrationSpaceListEntriesFromAggregate, r as NO_REF_ADVANCEMENT, rt as resolveAppTargetPath, st as resolveMigrationRef, t as ALL_CONTRACT_REF_FORMS, tt as refuseUnknownInvariants, u as buildMigrationSpaceGraphEntries, ut as retryCommandFor, vt as validateLoadedContract, x as executeContractEmit, z as loadAggregateIntegrityViolations } from "./ref-BMhPu-wB-DU1LW2lb.mjs";
14
15
  import { a as PRISMA7_QUICK_REFERENCE_STEP, i as PRISMA7_LOOP_STEP, n as InitOutputSchema, o as buildNextSteps, r as NEXT_STEPS_BEFORE_SCAFFOLD, t as DB_SIGN_STEP } from "./output-BcC8eB0h-C5bRd-aC.mjs";
15
16
  import { createRequire } from "node:module";
16
17
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
@@ -39,7 +40,7 @@ import { applyEdits, modify, parse, printParseErrorCode } from "jsonc-parser";
39
40
  import stringWidth from "string-width";
40
41
  import { bold, createColors, cyan, cyanBright, dim, green, yellow } from "colorette";
41
42
  import { build } from "esbuild";
42
- //#region ../../../1-framework/3-tooling/cli/dist/load-config-DrsxHOYw.mjs
43
+ //#region ../../../1-framework/3-tooling/cli/dist/load-config-DAbKTcah.mjs
43
44
  /**
44
45
  * `isStructuredError` is the repo's own check, and it is the one that matters here: it holds the
45
46
  * regular expression for a dotted `NAMESPACE.SUBCODE`, so only a code the protocol accepts
@@ -765,6 +766,140 @@ function createContractPrintCommand({ printPsl }) {
765
766
  });
766
767
  }
767
768
  const contractPrintCommand = createContractPrintCommand({ printPsl });
769
+ /** What a runner failure says of a type change that failed: who converted the values, and how it failed. */
770
+ function failedTypeChangeText(change) {
771
+ if (change.by === "cast") return change.reason === "noCast" ? `The database has no cast from the old type of field "${change.field}" to its new type.` : `A value of field "${change.field}" cannot be converted to its new type by the database's cast.`;
772
+ switch (change.reason) {
773
+ case "value": return `The conversion of field "${change.field}" failed on a value its new type cannot hold.`;
774
+ case "invalidResult": return `The conversion of field "${change.field}" left a value its new type cannot hold.`;
775
+ case "expressionError": return `The conversion of field "${change.field}" failed with an error in its expression.`;
776
+ }
777
+ }
778
+ function migrationPlanCommand$1(invocation, flags, from) {
779
+ return `\`${printedPlanCommand(invocation, from, flags)}\``;
780
+ }
781
+ /** A `db migrate` command as advice prints it. */
782
+ function dbMigrateCommand(invocation) {
783
+ return `\`${cliCommand(invocation, "db migrate")}\``;
784
+ }
785
+ /** The step between filling a planned migration.ts and applying it, which writes its operations. */
786
+ const RUN_PLANNED_FILE = "run that migration.ts with the `node` command `migration plan` prints";
787
+ function backfillFlags(reports) {
788
+ return [...new Set(reports.flatMap(({ field }) => field === void 0 ? [] : [statementFlag({
789
+ verb: "backfill",
790
+ text: field
791
+ })]))];
792
+ }
793
+ /** The way out of a failed cast for `db update`, which plans and applies in one step. */
794
+ function dbUpdateFailedTypeChangeFix(change, databaseStorageHash, invocation) {
795
+ const plan = migrationPlanCommand$1(invocation, [statementFlag({
796
+ verb: "convert",
797
+ text: change.field
798
+ })], databaseStorageHash);
799
+ return `${failedTypeChangeText(change)} Plan the change with ${plan}, write the conversion in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}.`;
800
+ }
801
+ /** The way out of rows without a value for `db update`, which plans and applies in one step. */
802
+ function dbUpdateRowsWithoutValueFix(reports, databaseStorageHash, invocation) {
803
+ const flags = backfillFlags(reports);
804
+ const plan = flags.length === 0 ? void 0 : `${migrationPlanCommand$1(invocation, flags, databaseStorageHash)}, fill the backfill steps in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}`;
805
+ if (reports[0]?.reason === "nullValues") {
806
+ const keep = "Set a value in those rows, or keep the field optional.";
807
+ return plan === void 0 ? keep : `${keep} Or plan it with ${plan}.`;
808
+ }
809
+ return plan === void 0 ? "Make the field optional." : `Plan it with ${plan}. Or make the field optional.`;
810
+ }
811
+ /**
812
+ * The way out of rows without a value for `db init`: a migration plan needs an origin contract,
813
+ * which a database that `db init` never initialized does not have.
814
+ */
815
+ function dbInitRowsWithoutValueFix(reports, invocation) {
816
+ const field = reports[0]?.field;
817
+ const subject = field === void 0 ? "it" : `field "${field}"`;
818
+ return `Run \`${cliCommand(invocation, "db init")}\` with ${subject} optional. Then make it required with \`${cliCommand(invocation, "db update")}\`, which says how to give the rows a value.`;
819
+ }
820
+ function failedMigrationText(failed, invocation) {
821
+ const dirName = basename(failed.directory);
822
+ return {
823
+ directory: printedPath(invocation, failed.directory),
824
+ name: dirName.slice(dirName.indexOf("_") + 1),
825
+ from: failed.from,
826
+ nodeCommand: selfEmitCommand(invocation, join(failed.directory, "migration.ts")),
827
+ invocation
828
+ };
829
+ }
830
+ function replan(flags, failed, except = void 0) {
831
+ const others = except === void 0 ? "its other statements" : `its other statements except any ${except}`;
832
+ const plan = migrationPlanCommand$1(failed.invocation, [
833
+ "--name",
834
+ failed.name,
835
+ ...flags
836
+ ], failed.from);
837
+ return `delete \`${failed.directory}\` (copy any code you wrote in its migration.ts first), plan it again with ${plan} and ${others}, fill in the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${dbMigrateCommand(failed.invocation)}`;
838
+ }
839
+ /**
840
+ * Where to fix code written in the failed migration's `migration.ts`, and the command that runs the
841
+ * file again.
842
+ */
843
+ function failedMigrationFile(failedMigration) {
844
+ if (failedMigration === void 0) return {
845
+ file: "the migration.ts of the failed migration",
846
+ run: "run that file with node"
847
+ };
848
+ return {
849
+ file: `\`${failedMigration.directory}/migration.ts\``,
850
+ run: `run \`${failedMigration.nodeCommand}\``
851
+ };
852
+ }
853
+ function migrateFailedTypeChangeFix(change, failedMigration, invocation) {
854
+ if (change.by === "conversion") {
855
+ const { file, run } = failedMigrationFile(failedMigration);
856
+ return `${failedTypeChangeText(change)} The failed apply changed nothing. Fix the conversion in ${file}, ${run}, and re-run ${dbMigrateCommand(invocation)}.`;
857
+ }
858
+ const convert = statementFlag({
859
+ verb: "convert",
860
+ text: change.field
861
+ });
862
+ if (failedMigration === void 0) return `${failedTypeChangeText(change)} Plan the type change again with ${migrationPlanCommand$1(invocation, [convert], void 0)}, write the conversion in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}.`;
863
+ const deleted = `\`${statementFlag({
864
+ verb: "delete",
865
+ text: change.field
866
+ })}\``;
867
+ const { file, run } = failedMigrationFile(failedMigration);
868
+ return `${failedTypeChangeText(change)} The failed apply changed nothing. ${file} has no conversion for field "${change.field}": write one there, ${run}, and re-run ${dbMigrateCommand(invocation)}. Or ${replan([convert], failedMigration, deleted)}.`;
869
+ }
870
+ function migrateRowsWithoutValueFix(reports, failedMigration, invocation) {
871
+ const [first] = reports;
872
+ if (first?.reason === "backfillMissedRows") {
873
+ const { file, run } = failedMigrationFile(failedMigration);
874
+ return `${first.field === void 0 ? "The backfill step" : `The backfill step of field "${first.field}"`} left those rows without a value, and the failed apply changed nothing. Make its run fill every row in ${file}, ${run}, and re-run ${dbMigrateCommand(invocation)}.`;
875
+ }
876
+ const flags = backfillFlags(reports);
877
+ const again = flags.length === 0 || failedMigration === void 0 ? void 0 : replan(flags, failedMigration);
878
+ if (reports.every(({ reason }) => reason === "nullValues")) {
879
+ const rerun = reports.length === 1 ? `Set a value in those rows and re-run ${dbMigrateCommand(invocation)}.` : `Set a value in the rows that hold NULL in each of ${fieldList(reports)} and re-run ${dbMigrateCommand(invocation)}.`;
880
+ const keep = failedMigration === void 0 ? `Or keep ${reports.length === 1 ? "the field" : "those fields"} optional, and plan the migration again.` : `Or keep ${reports.length === 1 ? "the field" : "those fields"} optional: make ${reports.length === 1 ? "it" : "them"} optional in the contract again, delete \`${failedMigration.directory}\` (copy any code you wrote in its migration.ts first), and plan it again with ${migrationPlanCommand$1(invocation, ["--name", failedMigration.name], failedMigration.from)} and its other statements, put back any code you copied, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}.`;
881
+ return [
882
+ rerun,
883
+ ...again === void 0 ? [] : [`Or ${again}.`],
884
+ keep
885
+ ].join(" ");
886
+ }
887
+ if (reports[0]?.reason === "nullValues") return again === void 0 ? "The migration also adds a required field the existing rows have no value for, so setting values is not enough: make the new fields optional, and plan the migration again." : `The migration also adds a required field the existing rows have no value for, so setting values is not enough. The failed apply changed nothing: ${again}.`;
888
+ return again === void 0 ? "Make the field optional, and plan the migration again." : `The failed apply changed nothing. To keep the field required, ${again}. Or make the field optional, and plan it again.`;
889
+ }
890
+ function fieldList(reports) {
891
+ return reports.map(({ field }) => field === void 0 ? void 0 : `"${field}"`).filter((field) => field !== void 0).join(", ");
892
+ }
893
+ /**
894
+ * The way out of a failed `db migrate` apply: every path and command it prints works from where the
895
+ * CLI ran, with the `--config` it was given.
896
+ */
897
+ function migrateFix(failure, invocation) {
898
+ const failedMigration = failure.failedMigration === void 0 ? void 0 : failedMigrationText(failure.failedMigration, invocation);
899
+ if (failure.failedTypeChange !== void 0) return migrateFailedTypeChangeFix(failure.failedTypeChange, failedMigration, invocation);
900
+ if (failure.rowsWithoutValue !== void 0) return migrateRowsWithoutValueFix(failure.rowsWithoutValue, failedMigration, invocation);
901
+ return `Fix the issue and re-run \`${cliCommand(invocation, "db migrate", ["--to", "<contract>"])}\` — previously applied migrations are preserved.`;
902
+ }
768
903
  const DB_INIT_ADDITIVE_ONLY_FIX = "`db init` applies only additive changes. Run `{bin} db update`, which also applies widening and destructive ones once you answer what each operation that would lose data means, with `--delete` or `--rename`.";
769
904
  const DB_INIT_NEEDS_MIGRATION_FIX = "`db init` applies only additive changes, and `db update` does not apply data operations. Plan a migration with `{bin} migration plan`, which can include them, and apply it with `{bin} db migrate`.";
770
905
  /**
@@ -793,7 +928,7 @@ function markerMismatchDetail(failure) {
793
928
  * The `assertNever` is deliberate: a control-API failure code this does not
794
929
  * handle must stop the command rather than degrade into a generic message.
795
930
  */
796
- function mapDbInitFailure(failure) {
931
+ function mapDbInitFailure(failure, invocation) {
797
932
  if (failure.code === "PLANNING_FAILED") {
798
933
  const conflicts = failure.conflicts ?? [];
799
934
  const planningFailed = errorMigrationPlanningFailed({ conflicts });
@@ -819,7 +954,8 @@ function mapDbInitFailure(failure) {
819
954
  }
820
955
  });
821
956
  if (failure.code === "RUNNER_FAILED") {
822
- const fix = (typeof failure.meta?.["runnerErrorCode"] === "string" ? failure.meta["runnerErrorCode"] : void 0) === "MIGRATION.LEGACY_MARKER_SHAPE" ? "Legacy marker-table shape detected. Drop `prisma_contract.marker` (Postgres) or `_prisma_marker` (SQLite) and re-run `{bin} db init` to recreate it with the current per-space schema." : "Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `{bin} db init`";
957
+ const runnerCode = typeof failure.meta?.["runnerErrorCode"] === "string" ? failure.meta["runnerErrorCode"] : void 0;
958
+ const fix = failure.rowsWithoutValue !== void 0 ? dbInitRowsWithoutValueFix(failure.rowsWithoutValue, invocation) : runnerCode === "MIGRATION.LEGACY_MARKER_SHAPE" ? "Legacy marker-table shape detected. Drop `prisma_contract.marker` (Postgres) or `_prisma_marker` (SQLite) and re-run `{bin} db init` to recreate it with the current per-space schema." : "Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `{bin} db init`";
823
959
  return errorRunnerFailed(failure.summary, {
824
960
  why: failure.why ?? "Migration runner failed",
825
961
  fix,
@@ -857,8 +993,13 @@ function renderPreviewStatement(text, language) {
857
993
  function previewBlockHeader(preview) {
858
994
  return preview.statements.length > 0 && preview.statements.every((s) => s.language === "sql") ? "DDL preview" : "Operation preview";
859
995
  }
860
- function operationCountText(count) {
861
- if (count === 0) return "no operations";
996
+ const SLOT_TEXT = {
997
+ convert: "conversion slot written in migration.ts",
998
+ backfill: "backfill slots written in migration.ts"
999
+ };
1000
+ function operationCountText(entry) {
1001
+ const count = entry.operationIndexes.length;
1002
+ if (count === 0) return SLOT_TEXT[entry.verb] ?? "no operations";
862
1003
  return count === 1 ? "1 operation" : `${count} operations`;
863
1004
  }
864
1005
  /**
@@ -872,7 +1013,7 @@ function appliedStatementBlocks(applied) {
872
1013
  kind: "tree",
873
1014
  roots: [{
874
1015
  label: "Statements applied",
875
- children: applied.map((entry) => ({ label: `${entry.description} (${operationCountText(entry.operationIndexes.length)})` }))
1016
+ children: applied.map((entry) => ({ label: `${entry.description} (${operationCountText(entry)})` }))
876
1017
  }]
877
1018
  }];
878
1019
  }
@@ -973,6 +1114,18 @@ function plannerWarningBlocks(result) {
973
1114
  items: warnings.map((warning) => warning.summary)
974
1115
  }];
975
1116
  }
1117
+ /** The new required fields whose existing rows get a temporary value, and how to choose the value. */
1118
+ function temporaryValueBlocks$1(result, invocation, databaseStorageHash) {
1119
+ const get = result.mode === "plan" ? "would get" : "got";
1120
+ return (result.temporaryValues ?? []).map(({ field, value }) => ({
1121
+ kind: "summary",
1122
+ status: "warn",
1123
+ text: `Existing rows ${get} ${value} in field "${field}". To choose the value, plan a migration with ${printedPlanCommand(invocation, databaseStorageHash, [statementFlag({
1124
+ verb: "backfill",
1125
+ text: field
1126
+ })])} instead.`
1127
+ }));
1128
+ }
976
1129
  function planSummaryText(result) {
977
1130
  const operations = result.plan.operations.length;
978
1131
  const spaces = result.perSpace?.length ?? 0;
@@ -1009,7 +1162,7 @@ function questionBlocks(result) {
1009
1162
  }]
1010
1163
  }];
1011
1164
  }
1012
- function planBlocks$1(result) {
1165
+ function planBlocks$1(result, invocation, databaseStorageHash) {
1013
1166
  const planned = result.plannedAdvanceRef;
1014
1167
  return [
1015
1168
  {
@@ -1019,6 +1172,7 @@ function planBlocks$1(result) {
1019
1172
  },
1020
1173
  ...plannerWarningBlocks(result),
1021
1174
  ...operationBlocks$2(result),
1175
+ ...temporaryValueBlocks$1(result, invocation, databaseStorageHash),
1022
1176
  ...appliedStatementBlocks(result.appliedStatements ?? []),
1023
1177
  ...questionBlocks(result),
1024
1178
  {
@@ -1072,7 +1226,7 @@ function fallbackMarkerBlocks(result) {
1072
1226
  }]]
1073
1227
  }];
1074
1228
  }
1075
- function applyBlocks(result) {
1229
+ function applyBlocks(result, invocation, databaseStorageHash) {
1076
1230
  const advanced = result.advancedRef;
1077
1231
  return [
1078
1232
  {
@@ -1082,6 +1236,7 @@ function applyBlocks(result) {
1082
1236
  },
1083
1237
  ...plannerWarningBlocks(result),
1084
1238
  ...operationBlocks$2(result),
1239
+ ...temporaryValueBlocks$1(result, invocation, databaseStorageHash),
1085
1240
  ...appliedStatementBlocks(result.appliedStatements ?? []),
1086
1241
  ...fallbackMarkerBlocks(result),
1087
1242
  ...advanced === null || advanced === void 0 ? [] : [{
@@ -1094,13 +1249,17 @@ function applyBlocks(result) {
1094
1249
  }]
1095
1250
  ];
1096
1251
  }
1097
- /** What a `db init` / `db update` result looks like in human mode. */
1098
- function migrationResultBlocks(result) {
1099
- return result.mode === "plan" ? planBlocks$1(result) : applyBlocks(result);
1252
+ /**
1253
+ * What a `db init` / `db update` result looks like in human mode. Printed commands repeat
1254
+ * `invocation`, and a printed `migration plan` starts from `databaseStorageHash`, the contract the
1255
+ * database was at before the run, when a migration on disk ends at it.
1256
+ */
1257
+ function migrationResultBlocks(result, invocation, databaseStorageHash) {
1258
+ return result.mode === "plan" ? planBlocks$1(result, invocation, databaseStorageHash) : applyBlocks(result, invocation, databaseStorageHash);
1100
1259
  }
1101
1260
  /** Where the user goes next, as typed actions rather than trailing prose. */
1102
- function migrationResultNextActions(result, applyCommand) {
1103
- return result.mode === "plan" ? [runCommandAction("Apply the planned operations", applyCommand)] : [runCommandAction(result.perSpace !== void 0 && result.perSpace.length === 1 ? "Confirm the space is up to date" : "Confirm every space is up to date", "{bin} migration status")];
1261
+ function migrationResultNextActions(result, invocation, applyCommand) {
1262
+ return result.mode === "plan" ? [runCommandAction("Apply the planned operations", applyCommand)] : [runCommandAction(result.perSpace !== void 0 && result.perSpace.length === 1 ? "Confirm the space is up to date" : "Confirm every space is up to date", cliCommand(invocation, "migration status"))];
1104
1263
  }
1105
1264
  /** Reads the emitted contract as the raw document the control API validates. */
1106
1265
  async function readContractDocument(contractPath) {
@@ -1175,9 +1334,9 @@ function initPresentations$1(inputs) {
1175
1334
  value: "dry run"
1176
1335
  }] : []
1177
1336
  ]
1178
- }, ...migrationResultBlocks(document)],
1337
+ }, ...migrationResultBlocks(document, inputs.invocation, void 0)],
1179
1338
  json: () => document,
1180
- next: () => migrationResultNextActions(document, "{bin} db init")
1339
+ next: () => migrationResultNextActions(document, inputs.invocation, cliCommand(inputs.invocation, "db init"))
1181
1340
  };
1182
1341
  }
1183
1342
  function initDocument(inputs) {
@@ -1273,7 +1432,7 @@ function createDbInitCommand(createClient) {
1273
1432
  migrationsDir,
1274
1433
  onProgress: controlProgressReporter(ctx.report)
1275
1434
  });
1276
- if (!result.ok) return notOk$1(normalizeError(mapDbInitFailure(result.failure)));
1435
+ if (!result.ok) return notOk$1(normalizeError(mapDbInitFailure(result.failure, cliInvocation(ctx, args.flags.db))));
1277
1436
  const advancementHash = result.value.mode === "apply" ? result.value.marker?.storageHash ?? result.value.destination.storageHash : result.value.destination.storageHash;
1278
1437
  const advanced = advancement === null ? ok$1(NO_REF_ADVANCEMENT) : await buildRefAdvancementFields({
1279
1438
  name: advancement.name,
@@ -1304,6 +1463,7 @@ function createDbInitCommand(createClient) {
1304
1463
  });
1305
1464
  return ok$1(ctx.present({ data: document }, initPresentations$1({
1306
1465
  document,
1466
+ invocation: cliInvocation(ctx, args.flags.db),
1307
1467
  contractPath: prepared.value.contractDisplayPath,
1308
1468
  database: prepared.value.database,
1309
1469
  dryRun: args.flags.dryRun
@@ -1545,18 +1705,18 @@ async function readEmittedContract(inputs) {
1545
1705
  function requireVerifyConnection(inputs) {
1546
1706
  const dbConnection = inputs.db ?? inputs.config.db?.connection;
1547
1707
  if (typeof dbConnection !== "string" || dbConnection.length === 0) return notOk$1(normalizeError(errorDatabaseConnectionRequired({
1548
- why: `Database connection is required for ${inputs.invocation} (set db.connection in prisma.config.ts, or pass --db <url>)`,
1708
+ why: `Database connection is required for ${inputs.commandLine} (set db.connection in prisma.config.ts, or pass --db <url>)`,
1549
1709
  missingFlags: ["--db"],
1550
- retryCommand: `{bin} ${inputs.invocation} --db <url>`
1710
+ retryCommand: `{bin} ${inputs.commandLine} --db <url>`
1551
1711
  })));
1552
- if (inputs.config.driver === void 0) return notOk$1(normalizeError(errorDriverRequired({ why: `Config.driver is required for ${inputs.invocation}` })));
1712
+ if (inputs.config.driver === void 0) return notOk$1(normalizeError(errorDriverRequired({ why: `Config.driver is required for ${inputs.commandLine}` })));
1553
1713
  return ok$1(dbConnection);
1554
1714
  }
1555
1715
  /**
1556
1716
  * A failure the verification could not recover from — a dropped connection, a driver throw — as a settlement the user can act on, reported as every command reports what it caught, without the connection string.
1557
1717
  */
1558
1718
  function verificationThrow(inputs) {
1559
- return normalizeError(errorFromCaught(inputs.error, (message) => `Unexpected error during ${inputs.invocation}: ${message}`, { connection: inputs.connection }));
1719
+ return normalizeError(errorFromCaught(inputs.error, (message) => `Unexpected error during ${inputs.commandLine}: ${message}`, { connection: inputs.connection }));
1560
1720
  }
1561
1721
  const OUTCOME_LABEL = {
1562
1722
  "not-found": "missing",
@@ -1769,15 +1929,13 @@ function signSummary(spaces) {
1769
1929
  const signedText = signed.length === 0 ? "signed nothing" : `signed ${quotedList(signed)}`;
1770
1930
  return `${problems.charAt(0).toUpperCase()}${problems.slice(1)}; ${signedText}`;
1771
1931
  }
1772
- function rerunCommand(invocation) {
1773
- return [
1774
- "{bin} db sign",
1775
- ...invocation.contractRef === void 0 ? [] : [`--contract "${invocation.contractRef}"`],
1776
- ...invocation.advanceRef === void 0 ? [] : [`--advance-ref ${invocation.advanceRef}`],
1777
- ...invocation.noAdvanceRef ? ["--no-advance-ref"] : [],
1778
- ...invocation.configPath === void 0 ? [] : [`--config "${invocation.configPath}"`],
1779
- ...invocation.db === void 0 ? [] : ["--db <url>"]
1780
- ].join(" ");
1932
+ /** The `db sign` command that runs this one again, with the arguments that change what it signs or where. */
1933
+ function rerunCommand(invocation, args) {
1934
+ return cliCommand(invocation, "db sign", [
1935
+ ...args.contractRef === void 0 ? [] : ["--contract", shellQuoted(args.contractRef)],
1936
+ ...args.advanceRef === void 0 ? [] : ["--advance-ref", shellQuoted(args.advanceRef)],
1937
+ ...args.noAdvanceRef ? ["--no-advance-ref"] : []
1938
+ ]);
1781
1939
  }
1782
1940
  function markerConflictDiagnostic(outcome, rerun) {
1783
1941
  const { expected, found } = outcome;
@@ -1989,16 +2147,14 @@ function createDbSignCommand(createClient = createControlClient) {
1989
2147
  const connection = requireVerifyConnection({
1990
2148
  config: ctx.config,
1991
2149
  db: args.flags.db,
1992
- invocation: "db sign"
2150
+ commandLine: "db sign"
1993
2151
  });
1994
2152
  if (!connection.ok) return notOk$1(connection.failure);
1995
2153
  const dbConnection = connection.value;
1996
- const rerun = rerunCommand({
2154
+ const rerun = rerunCommand(cliInvocation(ctx, args.flags.db), {
1997
2155
  contractRef,
1998
2156
  advanceRef: args.flags.advanceRef,
1999
- noAdvanceRef: args.flags.noAdvanceRef,
2000
- configPath: ctx.configPath,
2001
- db: args.flags.db
2157
+ noAdvanceRef: args.flags.noAdvanceRef
2002
2158
  });
2003
2159
  const header = headerBlock$1({
2004
2160
  contract: contractRef ?? emitted.value.displayPath,
@@ -2093,7 +2249,7 @@ function createDbSignCommand(createClient = createControlClient) {
2093
2249
  } catch (error) {
2094
2250
  return notOk$1(verificationThrow({
2095
2251
  error,
2096
- invocation: "db sign",
2252
+ commandLine: "db sign",
2097
2253
  connection: dbConnection
2098
2254
  }));
2099
2255
  } finally {
@@ -2109,10 +2265,11 @@ const dbSignCommand = createDbSignCommand();
2109
2265
  * The `assertNever` is deliberate: a control-API failure code this does not
2110
2266
  * handle must stop the command rather than degrade into a generic message.
2111
2267
  */
2112
- function mapDbUpdateFailure(failure) {
2268
+ function mapDbUpdateFailure(failure, invocation) {
2113
2269
  if (failure.code === "PLANNING_FAILED") return errorMigrationPlanningFailed({ conflicts: failure.conflicts ?? [] });
2114
2270
  if (failure.code === "RUNNER_FAILED") {
2115
- const fix = (typeof failure.meta?.["runnerErrorCode"] === "string" ? failure.meta["runnerErrorCode"] : void 0) === "MIGRATION.LEGACY_MARKER_SHAPE" ? "Legacy marker-table shape detected. Drop `prisma_contract.marker` (Postgres) or `_prisma_marker` (SQLite) and re-run `{bin} db init` to recreate it with the current per-space schema." : "Inspect the reported conflict, reconcile schema drift if needed, then re-run `{bin} db update`";
2271
+ const runnerCode = typeof failure.meta?.["runnerErrorCode"] === "string" ? failure.meta["runnerErrorCode"] : void 0;
2272
+ const fix = failure.failedTypeChange !== void 0 ? dbUpdateFailedTypeChangeFix(failure.failedTypeChange, failure.databaseStorageHash, invocation) : failure.rowsWithoutValue !== void 0 ? dbUpdateRowsWithoutValueFix(failure.rowsWithoutValue, failure.databaseStorageHash, invocation) : runnerCode === "MIGRATION.LEGACY_MARKER_SHAPE" ? `Legacy marker-table shape detected. Drop \`prisma_contract.marker\` (Postgres) or \`_prisma_marker\` (SQLite) and re-run \`${cliCommand(invocation, "db init")}\` to recreate it with the current per-space schema.` : `Inspect the reported conflict, reconcile schema drift if needed, then re-run \`${cliCommand(invocation, "db update")}\``;
2116
2273
  return errorRunnerFailed(failure.summary, {
2117
2274
  why: failure.why ?? "Migration runner failed",
2118
2275
  fix,
@@ -2145,11 +2302,7 @@ function promptPlanQuestions(prompt) {
2145
2302
  }));
2146
2303
  };
2147
2304
  }
2148
- /**
2149
- * The statement verbs the ORM commands declare. Each command declares the verbs its questions
2150
- * use: `migration plan` takes `rename` and `delete`, and `db update` also `allow`.
2151
- */
2152
- const ormStatementVerbs = {
2305
+ const verbs = {
2153
2306
  rename: {
2154
2307
  arity: 1,
2155
2308
  brief: "Rename a model or field instead of dropping it: old:new, each side Model, namespace.Model, Model.field or namespace.Model.field; repeat for several, applied in order"
@@ -2161,6 +2314,38 @@ const ormStatementVerbs = {
2161
2314
  allow: {
2162
2315
  arity: 1,
2163
2316
  brief: "Let the command widen who can read or write the rows of a model: --allow Model"
2317
+ },
2318
+ convert: {
2319
+ arity: 1,
2320
+ brief: "Convert the values of a field whose type changes with code you write into the migration: Model.field, named as the new contract names it"
2321
+ },
2322
+ backfill: {
2323
+ arity: 1,
2324
+ brief: "Fill a required field in existing rows with code you write into the migration: Model.field, new or made required"
2325
+ }
2326
+ };
2327
+ /** The statement verbs `migration plan` declares: it writes a migration, so a convert or backfill has a file to fill. */
2328
+ const migrationPlanStatementVerbs = {
2329
+ rename: verbs.rename,
2330
+ delete: verbs.delete,
2331
+ convert: verbs.convert,
2332
+ backfill: verbs.backfill
2333
+ };
2334
+ /**
2335
+ * The statement verbs `db update` declares. It applies its plan directly, with no migration file to
2336
+ * fill, so it declares `convert` and `backfill` only to refuse them with a reason.
2337
+ */
2338
+ const dbUpdateStatementVerbs = {
2339
+ rename: verbs.rename,
2340
+ delete: verbs.delete,
2341
+ allow: verbs.allow,
2342
+ convert: {
2343
+ arity: 1,
2344
+ brief: "Not available here: db update has no migration file to fill; use migration plan"
2345
+ },
2346
+ backfill: {
2347
+ arity: 1,
2348
+ brief: "Not available here: db update has no migration file to fill; use migration plan"
2164
2349
  }
2165
2350
  };
2166
2351
  function updatePresentations(inputs) {
@@ -2188,35 +2373,49 @@ function updatePresentations(inputs) {
2188
2373
  value: "dry run"
2189
2374
  }] : []
2190
2375
  ]
2191
- }, ...migrationResultBlocks(document)],
2376
+ }, ...migrationResultBlocks(document, inputs.invocation, inputs.databaseStorageHash)],
2192
2377
  json: () => document,
2193
- next: () => migrationResultNextActions(document, [
2194
- "{bin} db update",
2195
- ...inputs.to === void 0 ? [] : [`--to ${shellQuoted(inputs.to)}`],
2196
- ...inputs.dbGiven ? ["--db <url>"] : [],
2197
- ...inputs.advanceRef === void 0 ? [] : [`--advance-ref ${shellQuoted(inputs.advanceRef)}`],
2378
+ next: () => migrationResultNextActions(document, inputs.invocation, cliCommand(inputs.invocation, "db update", [
2379
+ ...inputs.to === void 0 ? [] : ["--to", shellQuoted(inputs.to)],
2380
+ ...inputs.advanceRef === void 0 ? [] : ["--advance-ref", shellQuoted(inputs.advanceRef)],
2198
2381
  ...inputs.statements.map(statementFlag)
2199
- ].join(" "))
2382
+ ]))
2200
2383
  };
2201
2384
  }
2202
2385
  /**
2203
- * The entries a dry run lists, each marked answered when a flag it was given answers its question:
2204
- * a `--delete` answers every loss of its subject, and an `--allow` one operation, in order.
2386
+ * Whether a flag the run was given answers each entry's question: a `--delete` answers every loss
2387
+ * of its subject, and an `--allow` one operation, in order.
2205
2388
  */
2206
- function subjectEntriesJson(entries, verb, given) {
2389
+ function answeredByFlags(entries, verb, given) {
2207
2390
  const flagsLeft = /* @__PURE__ */ new Map();
2208
2391
  for (const statement of given) if (statement.verb === verb) flagsLeft.set(statement.text, (flagsLeft.get(statement.text) ?? 0) + 1);
2209
2392
  return entries.map((entry) => {
2210
2393
  const left = flagsLeft.get(entry.text) ?? 0;
2211
2394
  if (left > 0 && verb === "allow") flagsLeft.set(entry.text, left - 1);
2212
- return {
2213
- operationIndex: entry.operationIndex,
2214
- subject: migrationSubjectJson(entry.subject),
2215
- text: entry.text,
2216
- answered: left > 0
2217
- };
2395
+ return left > 0;
2218
2396
  });
2219
2397
  }
2398
+ function subjectEntryJson(entry, answered) {
2399
+ return {
2400
+ operationIndex: entry.operationIndex,
2401
+ subject: migrationSubjectJson(entry.subject),
2402
+ text: entry.text,
2403
+ answered: answered === true
2404
+ };
2405
+ }
2406
+ /** The data-loss entries a dry run lists, each with how it loses data and whether a flag answers it. */
2407
+ function dataLossEntriesJson(entries, given) {
2408
+ const answered = answeredByFlags(entries, "delete", given);
2409
+ return entries.map((entry, index) => ({
2410
+ ...subjectEntryJson(entry, answered[index]),
2411
+ ...ifDefined("loss", entry.loss)
2412
+ }));
2413
+ }
2414
+ /** The access entries a dry run lists, each marked answered when an `--allow` it was given answers it. */
2415
+ function accessEntriesJson(entries, given) {
2416
+ const answered = answeredByFlags(entries, "allow", given);
2417
+ return entries.map((entry, index) => subjectEntryJson(entry, answered[index]));
2418
+ }
2220
2419
  function updateDocument(inputs) {
2221
2420
  const { value } = inputs;
2222
2421
  return {
@@ -2245,9 +2444,10 @@ function updateDocument(inputs) {
2245
2444
  } },
2246
2445
  ...ifDefined("perSpace", value.perSpace),
2247
2446
  appliedStatements: value.appliedStatements,
2447
+ temporaryValues: value.temporaryValues,
2248
2448
  ...value.mode === "plan" ? {
2249
- dataLoss: subjectEntriesJson(value.dataLoss, "delete", inputs.statements),
2250
- accessWidening: subjectEntriesJson(value.accessWidening, "allow", inputs.statements)
2449
+ dataLoss: dataLossEntriesJson(value.dataLoss, inputs.statements),
2450
+ accessWidening: accessEntriesJson(value.accessWidening, inputs.statements)
2251
2451
  } : {},
2252
2452
  ...ifDefined("warnings", value.warnings),
2253
2453
  advancedRef: inputs.advancedRef,
@@ -2288,10 +2488,24 @@ function createDbUpdateCommand(createClient) {
2288
2488
  placeholder: "name"
2289
2489
  })
2290
2490
  } },
2291
- statements: ormStatementVerbs,
2491
+ statements: dbUpdateStatementVerbs,
2292
2492
  needs: { config: ormConfigSection },
2293
2493
  handler: async (args, ctx) => {
2294
2494
  const startedAt = Date.now();
2495
+ const given = ctx.statements.values().flatMap(({ verb, text }) => isStatementVerb(verb) ? [{
2496
+ verb,
2497
+ text
2498
+ }] : []);
2499
+ if (["convert", "backfill"].flatMap((verb) => ctx.statements.take(verb)).length > 0) {
2500
+ const databaseStorageHash = await databaseContractIfReachable({
2501
+ config: ctx.config,
2502
+ cwd: ctx.cwd,
2503
+ db: args.flags.db,
2504
+ commandName: "db update",
2505
+ createClient
2506
+ });
2507
+ return notOk$1(normalizeError(errorStatementNeedsMigrationFile(given, cliInvocation(ctx, args.flags.db), databaseStorageHash)));
2508
+ }
2295
2509
  const renames = ctx.statements.take("rename").map(({ text }) => ({
2296
2510
  verb: "rename",
2297
2511
  text
@@ -2358,6 +2572,7 @@ function createDbUpdateCommand(createClient) {
2358
2572
  }
2359
2573
  const mode = args.flags.dryRun ? "plan" : "apply";
2360
2574
  let document;
2575
+ let databaseStorageHash;
2361
2576
  try {
2362
2577
  await client.connect(dbConnection);
2363
2578
  const reportPlannerWarnings = (warnings) => {
@@ -2377,7 +2592,7 @@ function createDbUpdateCommand(createClient) {
2377
2592
  });
2378
2593
  if (!result.ok) {
2379
2594
  reportPlannerWarnings(result.failure.warnings ?? []);
2380
- return notOk$1(normalizeError(mapDbUpdateFailure(result.failure)));
2595
+ return notOk$1(normalizeError(mapDbUpdateFailure(result.failure, cliInvocation(ctx, args.flags.db))));
2381
2596
  }
2382
2597
  const advancementHash = result.value.mode === "apply" ? result.value.marker?.storageHash ?? result.value.destination.storageHash : result.value.destination.storageHash;
2383
2598
  const advanced = advancement === null ? ok$1(NO_REF_ADVANCEMENT) : await buildRefAdvancementFields({
@@ -2389,6 +2604,7 @@ function createDbUpdateCommand(createClient) {
2389
2604
  hash: advancementHash
2390
2605
  });
2391
2606
  if (!advanced.ok) return notOk$1(normalizeError(advanced.failure));
2607
+ databaseStorageHash = result.value.databaseStorageHash;
2392
2608
  document = updateDocument({
2393
2609
  value: result.value,
2394
2610
  targetId: ctx.config.target.targetId,
@@ -2411,11 +2627,12 @@ function createDbUpdateCommand(createClient) {
2411
2627
  });
2412
2628
  return ok$1(ctx.present({ data: document }, updatePresentations({
2413
2629
  document,
2630
+ invocation: cliInvocation(ctx, args.flags.db),
2631
+ databaseStorageHash,
2414
2632
  contractPath: prepared.value.contractDisplayPath,
2415
2633
  database: prepared.value.database,
2416
2634
  to: args.flags.to,
2417
2635
  dryRun: args.flags.dryRun,
2418
- dbGiven: args.flags.db !== void 0,
2419
2636
  advanceRef: args.flags.advanceRef,
2420
2637
  statements: [...renames, ...previewConsents]
2421
2638
  })));
@@ -2424,6 +2641,40 @@ function createDbUpdateCommand(createClient) {
2424
2641
  }
2425
2642
  const dbUpdateCommand = createDbUpdateCommand(createControlClient);
2426
2643
  /**
2644
+ * The storage hash of the contract the database is at, when the database already exists and can be
2645
+ * reached and a migration of the application space ends at that contract, so that `migration plan
2646
+ * --from` resolves it. Anything else gives undefined: this only adds `--from` to a refusal, and it
2647
+ * never creates a database to read the marker.
2648
+ */
2649
+ async function databaseContractIfReachable(inputs) {
2650
+ const prepared = await prepareMigrationRun(inputs);
2651
+ if (!prepared.ok) return void 0;
2652
+ const { client, dbConnection, migrationsDir } = prepared.value;
2653
+ const read = async () => {
2654
+ await client.connect(dbConnection, {
2655
+ existingDatabaseOnly: true,
2656
+ connectTimeoutMs: MARKER_READ_TIMEOUT_MS
2657
+ });
2658
+ const marker = await client.readMarker();
2659
+ if (marker === null) return void 0;
2660
+ const { packages } = await readMigrationsDir(join(migrationsDir, APP_SPACE_ID), { migrationsDir });
2661
+ return packages.some(({ metadata }) => metadata.to === marker.storageHash) ? marker.storageHash : void 0;
2662
+ };
2663
+ return settledWithin(read().catch(() => void 0).finally(() => closeQuietly(client)), MARKER_READ_TIMEOUT_MS);
2664
+ }
2665
+ /** How long the refusal waits for the marker before it refuses without `--from`. */
2666
+ const MARKER_READ_TIMEOUT_MS = 3e3;
2667
+ function settledWithin(promise, ms) {
2668
+ return new Promise((resolve) => {
2669
+ const timer = setTimeout(() => resolve(void 0), ms);
2670
+ timer.unref();
2671
+ promise.then((value) => {
2672
+ clearTimeout(timer);
2673
+ resolve(value);
2674
+ });
2675
+ });
2676
+ }
2677
+ /**
2427
2678
  * Collapse the aggregate verifier's per-space contract-satisfaction results
2428
2679
  * into a single {@link VerifyDatabaseSchemaResult} for the CLI display
2429
2680
  * surface, and carry the deduplicated unclaimed-elements list alongside it.
@@ -2518,7 +2769,7 @@ function modeLabel(mode, strict) {
2518
2769
  const strictness = strict ? "strict" : "tolerant";
2519
2770
  return mode === "schema-only" ? `schema only (${strictness})` : `full (marker + schema, ${strictness})`;
2520
2771
  }
2521
- function invocation(mode, strict) {
2772
+ function commandLine(mode, strict) {
2522
2773
  return [
2523
2774
  "db verify",
2524
2775
  ...mode === "marker-only" ? ["--marker-only"] : [],
@@ -2737,17 +2988,17 @@ function createDbVerifyCommand(createClient = createControlClient) {
2737
2988
  });
2738
2989
  if (!resolved.ok) return notOk$1(resolved.failure);
2739
2990
  const mode = resolved.value;
2740
- const commandInvocation = invocation(mode, strict);
2991
+ const command = commandLine(mode, strict);
2741
2992
  const emitted = await readEmittedContract({
2742
2993
  config: ctx.config,
2743
2994
  cwd: ctx.cwd,
2744
- commandName: commandInvocation
2995
+ commandName: command
2745
2996
  });
2746
2997
  if (!emitted.ok) return notOk$1(emitted.failure);
2747
2998
  const connection = requireVerifyConnection({
2748
2999
  config: ctx.config,
2749
3000
  db: args.flags.db,
2750
- invocation: commandInvocation
3001
+ commandLine: command
2751
3002
  });
2752
3003
  if (!connection.ok) return notOk$1(connection.failure);
2753
3004
  const dbConnection = connection.value;
@@ -2918,7 +3169,7 @@ function createDbVerifyCommand(createClient = createControlClient) {
2918
3169
  } catch (error) {
2919
3170
  return notOk$1(verificationThrow({
2920
3171
  error,
2921
- invocation: commandInvocation,
3172
+ commandLine: command,
2922
3173
  connection: dbConnection
2923
3174
  }));
2924
3175
  } finally {
@@ -9141,17 +9392,22 @@ function migrateShowRunListRows(migrations, rendering, options) {
9141
9392
  const listDirNameWidth = gutter + Math.max(rendering.runListDirNameWidth + LABEL_GAP, MIN_HASH_DATA_COLUMN - gutter) - (multiSpace ? LIST_INDENT : LIST_INDENT * 2);
9142
9393
  return migrations.map((migration) => ` ${formatOnPathMigrationRow(migration.dirName, migration.from, migration.to, listDirNameWidth, options.colorize, options.glyphMode, paintOverrides(options))}`);
9143
9394
  }
9144
- /** A `migrate` apply failure as the CLI's structured error. */
9145
- function mapMigrateFailure(failure) {
9395
+ /**
9396
+ * A `migrate` apply failure as the CLI's structured error; its advice prints paths and commands
9397
+ * that work from where the CLI ran, with the `--config` it was given.
9398
+ */
9399
+ function mapMigrateFailure(failure, invocation) {
9146
9400
  if (failure.code === "MIGRATION_PATH_NOT_FOUND") return errorPathUnreachable(failure);
9147
9401
  return errorRunnerFailed(failure.summary, {
9148
9402
  why: failure.why ?? "Migration runner failed",
9149
- fix: "Fix the issue and re-run `{bin} db migrate --to <contract>` — previously applied migrations are preserved.",
9403
+ fix: migrateFix(failure, invocation),
9150
9404
  meta: failure.meta ?? {},
9151
9405
  ...ifDefined("cause", failure.cause)
9152
9406
  });
9153
9407
  }
9154
- const STATUS_ACTION = runCommandAction("Check every space against the database", "{bin} migration status");
9408
+ function statusAction(invocation) {
9409
+ return runCommandAction("Check every space against the database", cliCommand(invocation, "migration status"));
9410
+ }
9155
9411
  /**
9156
9412
  * The route the migration will take. The graph is a drawing — the engine cannot
9157
9413
  * derive a lane gutter — and the ordered list under it is drawn with the same
@@ -9246,7 +9502,7 @@ function applyPresentations(inputs) {
9246
9502
  }]
9247
9503
  ],
9248
9504
  json: () => document,
9249
- next: () => [STATUS_ACTION]
9505
+ next: () => [statusAction(inputs.invocation)]
9250
9506
  };
9251
9507
  }
9252
9508
  const EMITTED_CONTRACT_TARGET = {
@@ -9459,7 +9715,7 @@ function createMigrateCommand(createClient) {
9459
9715
  ...refEntry?.invariants === void 0 ? {} : { refInvariants: refEntry.invariants },
9460
9716
  ...ifDefined("refName", target.refName)
9461
9717
  });
9462
- if (!applied.ok) return notOk$1(normalizeError(mapMigrateFailure(applied.failure)));
9718
+ if (!applied.ok) return notOk$1(normalizeError(mapMigrateFailure(applied.failure, cliInvocation(ctx, args.flags.db))));
9463
9719
  const { value } = applied;
9464
9720
  let advancedRef = null;
9465
9721
  if (advancement !== null) {
@@ -9502,7 +9758,8 @@ function createMigrateCommand(createClient) {
9502
9758
  document,
9503
9759
  migrationsDir: migrationsRelative,
9504
9760
  database: prepared.value.database,
9505
- to: args.flags.to
9761
+ to: args.flags.to,
9762
+ invocation: cliInvocation(ctx, args.flags.db)
9506
9763
  })));
9507
9764
  }
9508
9765
  });
@@ -10224,7 +10481,7 @@ function newPresentations(inputs) {
10224
10481
  next: () => [{
10225
10482
  kind: "edit-file",
10226
10483
  label: `Write the migration body in ${migrationTs}`
10227
- }, runCommandAction("Run it to self-emit ops.json and attest the package", selfEmitCommand(migrationTs, inputs.configPath))]
10484
+ }, runCommandAction("Run it to self-emit ops.json and attest the package", selfEmitCommand(inputs.invocation, resolve(inputs.invocation.cwd, migrationTs)))]
10228
10485
  };
10229
10486
  }
10230
10487
  function createMigrationNewCommand(createClient) {
@@ -10270,7 +10527,7 @@ function createMigrationNewCommand(createClient) {
10270
10527
  document: scaffolded.value,
10271
10528
  contractPath: contractPath === void 0 ? "(unset)" : displayPath(contractPath, ctx.cwd),
10272
10529
  appMigrationsRelative: displayPath(appMigrationsDirFor(ctx.config), ctx.cwd),
10273
- configPath: ctx.configPath
10530
+ invocation: cliInvocation(ctx, void 0)
10274
10531
  })));
10275
10532
  }
10276
10533
  });
@@ -10373,6 +10630,16 @@ function originNoticeBlocks(result) {
10373
10630
  text: "No db ref set — planning from an empty database. Run db init, db update, or db sign if a database already exists."
10374
10631
  }];
10375
10632
  }
10633
+ function temporaryValueBlocks(result) {
10634
+ return result.temporaryValues.map(({ field, value }) => ({
10635
+ kind: "summary",
10636
+ status: "warn",
10637
+ text: `Existing rows get ${value} in field "${field}". To choose the value, plan again with ${statementFlag({
10638
+ verb: "backfill",
10639
+ text: field
10640
+ })}.`
10641
+ }));
10642
+ }
10376
10643
  function warningBlocks(result) {
10377
10644
  return (result.warnings ?? []).map((text) => ({
10378
10645
  kind: "summary",
@@ -10401,6 +10668,7 @@ function planBlocks(result, migrationsRelative) {
10401
10668
  },
10402
10669
  ...originNoticeBlocks(result),
10403
10670
  ...operationBlocks$1(result),
10671
+ ...temporaryValueBlocks(result),
10404
10672
  ...appliedStatementBlocks(result.appliedStatements),
10405
10673
  outcome
10406
10674
  ];
@@ -10413,19 +10681,20 @@ function planBlocks(result, migrationsRelative) {
10413
10681
  },
10414
10682
  ...originNoticeBlocks(result),
10415
10683
  ...operationBlocks$1(result),
10684
+ ...temporaryValueBlocks(result),
10416
10685
  ...appliedStatementBlocks(result.appliedStatements),
10417
10686
  outcome,
10418
10687
  ...previewBlocks$1(result)
10419
10688
  ];
10420
10689
  }
10421
- function planNextActions(result, migrationsRelative, configPath) {
10690
+ function planNextActions(result, migrationsRelative, invocation) {
10422
10691
  if (result.pendingPlaceholders === true) {
10423
- const stubFiles = [.../* @__PURE__ */ new Set([...result.baselineDir === void 0 ? [] : [join(result.baselineDir, "migration.ts")], ...result.dir === void 0 ? [] : [join(result.dir, "migration.ts")]])];
10692
+ const stubFiles = (result.placeholderDirs ?? []).map((dir) => join(dir, "migration.ts"));
10424
10693
  const migrationTs = stubFiles.at(-1) ?? join("<dir>", "migration.ts");
10425
10694
  return [{
10426
10695
  kind: "edit-file",
10427
10696
  label: `Replace each placeholder(...) call in ${stubFiles.join(" and ") || migrationTs} with your query`
10428
- }, runCommandAction("Run it to self-emit ops.json and attest the package", selfEmitCommand(migrationTs, configPath))];
10697
+ }, runCommandAction("Run it to self-emit ops.json and attest the package", selfEmitCommand(invocation, resolve(invocation.cwd, migrationTs)))];
10429
10698
  }
10430
10699
  const written = [
10431
10700
  ...result.baselineDir === void 0 ? [] : [result.baselineDir],
@@ -10436,7 +10705,7 @@ function planNextActions(result, migrationsRelative, configPath) {
10436
10705
  return [{
10437
10706
  kind: "edit-file",
10438
10707
  label: `Review ${written.join(" and ")}`
10439
- }, runCommandAction("Apply the migration", "{bin} db migrate")];
10708
+ }, runCommandAction("Apply the migration", cliCommand(invocation, "db migrate"))];
10440
10709
  }
10441
10710
  function planPresentations(inputs) {
10442
10711
  return {
@@ -10468,7 +10737,7 @@ function planPresentations(inputs) {
10468
10737
  ]
10469
10738
  }, ...planBlocks(inputs.document, inputs.migrationsRelative)],
10470
10739
  json: () => inputs.document,
10471
- next: () => planNextActions(inputs.document, inputs.migrationsRelative, inputs.configPath)
10740
+ next: () => planNextActions(inputs.document, inputs.migrationsRelative, inputs.invocation)
10472
10741
  };
10473
10742
  }
10474
10743
  function createMigrationPlanCommand(createClient) {
@@ -10498,10 +10767,7 @@ function createMigrationPlanCommand(createClient) {
10498
10767
  placeholder: "contract"
10499
10768
  })
10500
10769
  } },
10501
- statements: {
10502
- rename: ormStatementVerbs.rename,
10503
- delete: ormStatementVerbs.delete
10504
- },
10770
+ statements: migrationPlanStatementVerbs,
10505
10771
  needs: { config: ormConfigSection },
10506
10772
  handler: async (args, ctx) => {
10507
10773
  const seeded = (record) => {
@@ -10523,6 +10789,11 @@ function createMigrationPlanCommand(createClient) {
10523
10789
  }
10524
10790
  });
10525
10791
  };
10792
+ const conflicting = convertAndDelete(ctx.statements.values().flatMap(({ verb, text }) => isStatementVerb(verb) ? [{
10793
+ verb,
10794
+ text
10795
+ }] : []));
10796
+ if (conflicting !== void 0) return notOk$1(normalizeError(errorConvertAndDelete(conflicting)));
10526
10797
  const planned = await executeMigrationPlanCommand({
10527
10798
  config: ctx.config,
10528
10799
  cwd: ctx.cwd,
@@ -10531,10 +10802,14 @@ function createMigrationPlanCommand(createClient) {
10531
10802
  ...ifDefined("name", args.flags.name),
10532
10803
  ...ifDefined("from", args.flags.from),
10533
10804
  ...ifDefined("to", args.flags.to),
10534
- statements: ctx.statements.take("rename").map(({ text }) => ({
10535
- verb: "rename",
10805
+ statements: [
10806
+ "rename",
10807
+ "convert",
10808
+ "backfill"
10809
+ ].flatMap((verb) => ctx.statements.take(verb).map(({ text }) => ({
10810
+ verb,
10536
10811
  text
10537
- })),
10812
+ }))),
10538
10813
  answerQuestions: promptPlanQuestions(ctx.prompt),
10539
10814
  client: createClient({
10540
10815
  family: ctx.config.family,
@@ -10559,7 +10834,7 @@ function createMigrationPlanCommand(createClient) {
10559
10834
  from: args.flags.from,
10560
10835
  to: args.flags.to,
10561
10836
  name: args.flags.name,
10562
- configPath: ctx.configPath
10837
+ invocation: cliInvocation(ctx, void 0)
10563
10838
  })));
10564
10839
  }
10565
10840
  });