@prisma/orm-toolchain 8.0.0-rc.16-dev.7 → 8.0.0-rc.16-dev.8
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.
- package/dist/{aggregate-BGdw05Nj.d.mts → aggregate-C23h_Ybm.d.mts} +29 -21
- package/dist/{aggregate-BGdw05Nj.d.mts.map → aggregate-C23h_Ybm.d.mts.map} +1 -1
- package/dist/{aggregate-CG8Nfsg1.mjs → aggregate-DlfOyErc.mjs} +15 -2
- package/dist/aggregate-DlfOyErc.mjs.map +1 -0
- package/dist/{caught-errors-DHRx2eml-Az6yWv1r.mjs → caught-errors-HFQjjQVE-b_GDV-6J.mjs} +42 -4
- package/dist/caught-errors-HFQjjQVE-b_GDV-6J.mjs.map +1 -0
- package/dist/cli.mjs +153 -124
- package/dist/cli.mjs.map +1 -1
- package/dist/cli__control-api.d.mts +31 -50
- package/dist/cli__control-api.d.mts.map +1 -1
- package/dist/cli__control-api.mjs +2 -2
- package/dist/cli__control-api__testing.d.mts +1 -1
- package/dist/cli__control-api__testing.mjs +2 -0
- package/dist/cli__control-api__testing.mjs.map +1 -1
- package/dist/cli__migration-cli.mjs +1 -1
- package/dist/cli__migration-cli.mjs.map +1 -1
- package/dist/{db-sign-DqskX43K-CtEwW2Y6.d.mts → db-sign-BPf9SzzX-CwOFPxoZ.d.mts} +85 -70
- package/dist/db-sign-BPf9SzzX-CwOFPxoZ.d.mts.map +1 -0
- package/dist/migration-tools.d.mts +1 -1
- package/dist/migration-tools.mjs +1 -1
- package/dist/migration-tools__aggregate.d.mts +1 -1
- package/dist/migration-tools__aggregate.mjs +1 -1
- package/dist/{ref-QYB51IgO-ywgKx10n.mjs → ref-Cc_CTagE-C070Ym7p.mjs} +657 -227
- package/dist/ref-Cc_CTagE-C070Ym7p.mjs.map +1 -0
- package/dist/vite-plugin-contract-emit.mjs +1 -1
- package/package.json +13 -13
- package/dist/aggregate-CG8Nfsg1.mjs.map +0 -1
- package/dist/caught-errors-DHRx2eml-Az6yWv1r.mjs.map +0 -1
- package/dist/db-sign-DqskX43K-CtEwW2Y6.d.mts.map +0 -1
- package/dist/ref-QYB51IgO-ywgKx10n.mjs.map +0 -1
package/dist/cli.mjs
CHANGED
|
@@ -3,19 +3,19 @@ import { t as MigrationToolsError } from "./errors-DD6iLGXk-6I9PqjpZ.mjs";
|
|
|
3
3
|
import { t as contractSnapshotDir } from "./contract-snapshot-store-1S_6vaGt-HJIMKsVd.mjs";
|
|
4
4
|
import { t as EMPTY_CONTRACT_HASH } from "./constants-CM-w38DQ-Cz_EXbOc.mjs";
|
|
5
5
|
import { c as spaceMigrationDirectory, l as spaceRefsDirectory } from "./verify-contract-spaces-CYjc343k-ClHHEkJF.mjs";
|
|
6
|
-
import { $ as runCommandAction, C as
|
|
6
|
+
import { $ as runCommandAction, C as errorMigrationPlanningFailed, H as errorTargetMigrationNotSupported, J as readContractEnvelope, M as errorRunnerFailed, N as errorRuntime, P as errorSignRefsNotWritten, S as errorMigrationPackageNotFound, T as errorPathUnreachable, U as errorTargetMismatch, X as requireLiveDatabase, Y as redactUrlCredentials, _ as errorHashMismatch, a as closeQuietly, d as errorContractConfigMissing, et as targetSupportsMigrations, f as errorContractValidationFailed, g as errorFromCaught, h as errorFileNotFound, i as chooseAction, l as errorConfigValidation$1, m as errorDriverRequired, n as CliStructuredError$1$1, p as errorDatabaseConnectionRequired, q as maskConnectionUrl, s as errorAdvanceRefArgConflict, t as ActionableCliError, u as errorContractArgConflict, w as errorNoMigrations, x as errorMarkerMissing, y as errorLegendHumanOnly } from "./caught-errors-HFQjjQVE-b_GDV-6J.mjs";
|
|
7
7
|
import { r as getEmittedArtifactPaths } from "./exports-DaDckULH-JNQeM6Nn.mjs";
|
|
8
8
|
import { r as isInSpaceHistory } from "./graph-membership-C_ZO26nT-B7C4CJsh.mjs";
|
|
9
9
|
import { d as writeRef, r as readRef } from "./refs-qwvw4_dV-DNg_7WTD.mjs";
|
|
10
|
-
import { a as contractHashAtMarker } from "./aggregate-
|
|
10
|
+
import { a as contractHashAtMarker } from "./aggregate-DlfOyErc.mjs";
|
|
11
11
|
import { i as createScaffoldSpecifierResolver } from "./import-roots-BeAYfehL.mjs";
|
|
12
12
|
import { o as isLiveMarkerRef } from "./ref-resolution-Be_zewf7.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, 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
|
|
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 toDeclaredExtensionsFromRaw, 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 shellQuoted, g as deriveStatusEdgeAnnotations, gt as statusForMigrationHash, h as createControlClient, ht as statementFlag, i as RECORDED_CONTRACT_REF_FORMS, j as executeRefSetCommand, k as executeRefDeleteCommand, m as computeRefAdvancementName, mt as sourceWarningDiagnostic, n as DB_UPDATE_POLICY, nt as resolveContractRef$1, o as advanceRefSafely, p as checkSingleTarget, pt as snapshotVerifierFor, 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 validateLoadedContract, y as enumerateCheckSpaces, z as loadContractSource } from "./ref-Cc_CTagE-C070Ym7p.mjs";
|
|
14
14
|
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
15
|
import { createRequire } from "node:module";
|
|
16
16
|
import { ifDefined } from "@prisma/orm-framework/utils/defined";
|
|
17
17
|
import { CliStructuredError } from "@prisma/orm-framework/errors/control";
|
|
18
|
-
import { APP_SPACE_ID, VERIFY_CODE_HASH_MISMATCH, VERIFY_CODE_MARKER_MISSING, VERIFY_CODE_SCHEMA_FAILURE, VERIFY_CODE_TARGET_MISMATCH, createControlStack, hasPslContractBuild, issueOutcome } from "@prisma/orm-framework/components/control";
|
|
18
|
+
import { APP_SPACE_ID, VERIFY_CODE_HASH_MISMATCH, VERIFY_CODE_MARKER_MISSING, VERIFY_CODE_SCHEMA_FAILURE, VERIFY_CODE_TARGET_MISMATCH, createControlStack, hasPslContractBuild, issueOutcome, migrationSubjectJson } from "@prisma/orm-framework/components/control";
|
|
19
19
|
import { InternalError, assertNever, isInternalError } from "@prisma/orm-framework/utils/internal-error";
|
|
20
20
|
import { DOCS_BASE, docsUrlFor, isStructuredError, isStructuredErrorCode } from "@prisma/orm-framework/utils/structured-error";
|
|
21
21
|
import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "pathe";
|
|
@@ -39,7 +39,7 @@ import { applyEdits, modify, parse, printParseErrorCode } from "jsonc-parser";
|
|
|
39
39
|
import stringWidth from "string-width";
|
|
40
40
|
import { bold, createColors, cyan, cyanBright, dim, green, yellow } from "colorette";
|
|
41
41
|
import { build } from "esbuild";
|
|
42
|
-
//#region ../../../1-framework/3-tooling/cli/dist/load-config-
|
|
42
|
+
//#region ../../../1-framework/3-tooling/cli/dist/load-config-BoV4P1CO.mjs
|
|
43
43
|
/**
|
|
44
44
|
* `isStructuredError` is the repo's own check, and it is the one that matters here: it holds the
|
|
45
45
|
* regular expression for a dotted `NAMESPACE.SUBCODE`, so only a code the protocol accepts
|
|
@@ -800,7 +800,7 @@ function createContractPrintCommand({ printPsl }) {
|
|
|
800
800
|
});
|
|
801
801
|
}
|
|
802
802
|
const contractPrintCommand = createContractPrintCommand({ printPsl });
|
|
803
|
-
const DB_INIT_ADDITIVE_ONLY_FIX = "`db init` applies only additive changes. Run `{bin} db update`, which also applies widening and destructive ones
|
|
803
|
+
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`.";
|
|
804
804
|
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`.";
|
|
805
805
|
/**
|
|
806
806
|
* What to do instead of `db init` when its additive-only policy refused operations of the given classes: `db update` when its policy allows all of them, otherwise a planned migration.
|
|
@@ -813,7 +813,7 @@ function adviceForRefusedClasses(refused) {
|
|
|
813
813
|
};
|
|
814
814
|
return {
|
|
815
815
|
fix: DB_INIT_ADDITIVE_ONLY_FIX,
|
|
816
|
-
nextAction: runCommandAction(refused.has("destructive") ? "Apply the change with db update, which
|
|
816
|
+
nextAction: runCommandAction(refused.has("destructive") ? "Apply the change with db update, which asks what each operation that would lose data means" : "Apply the change with db update", "{bin} db update")
|
|
817
817
|
};
|
|
818
818
|
}
|
|
819
819
|
function markerMismatchDetail(failure) {
|
|
@@ -1020,6 +1020,30 @@ function applySummaryText(result) {
|
|
|
1020
1020
|
if (executed === 0) return `Database already matches contract${across}`;
|
|
1021
1021
|
return `Applied ${executed} operation(s)${across}`;
|
|
1022
1022
|
}
|
|
1023
|
+
/**
|
|
1024
|
+
* The questions an apply would ask, as a dry run lists them: each operation that would lose data,
|
|
1025
|
+
* answered by `--delete` or `--rename`, and each that would widen access, answered by `--allow`.
|
|
1026
|
+
*/
|
|
1027
|
+
function questionBlocks(result) {
|
|
1028
|
+
const entries = [...(result.dataLoss ?? []).map((entry) => ({
|
|
1029
|
+
entry,
|
|
1030
|
+
verb: "delete"
|
|
1031
|
+
})), ...(result.accessWidening ?? []).map((entry) => ({
|
|
1032
|
+
entry,
|
|
1033
|
+
verb: "allow"
|
|
1034
|
+
}))];
|
|
1035
|
+
if (entries.length === 0) return [];
|
|
1036
|
+
return [{
|
|
1037
|
+
kind: "tree",
|
|
1038
|
+
roots: [{
|
|
1039
|
+
label: "An apply asks about",
|
|
1040
|
+
children: entries.map(({ entry, verb }) => ({ label: `${result.plan.operations[entry.operationIndex]?.label ?? "an operation"}: ${statementFlag({
|
|
1041
|
+
verb,
|
|
1042
|
+
text: entry.text
|
|
1043
|
+
})}${entry.answered ? " (answered)" : ""}` }))
|
|
1044
|
+
}]
|
|
1045
|
+
}];
|
|
1046
|
+
}
|
|
1023
1047
|
function planBlocks$1(result) {
|
|
1024
1048
|
const planned = result.plannedAdvanceRef;
|
|
1025
1049
|
return [
|
|
@@ -1031,6 +1055,7 @@ function planBlocks$1(result) {
|
|
|
1031
1055
|
...plannerWarningBlocks(result),
|
|
1032
1056
|
...operationBlocks$2(result),
|
|
1033
1057
|
...appliedStatementBlocks(result.appliedStatements ?? []),
|
|
1058
|
+
...questionBlocks(result),
|
|
1034
1059
|
{
|
|
1035
1060
|
kind: "fields",
|
|
1036
1061
|
rows: [{
|
|
@@ -1143,7 +1168,7 @@ async function prepareMigrationRun(inputs) {
|
|
|
1143
1168
|
why: `Database connection is required for ${commandName} (set db.connection in prisma.config.ts, or pass --db <url>)`,
|
|
1144
1169
|
commandName,
|
|
1145
1170
|
missingFlags: ["--db"],
|
|
1146
|
-
...ifDefined("retryCommand", inputs.retryCommand)
|
|
1171
|
+
...ifDefined("retryCommand", typeof inputs.retryCommand === "function" ? inputs.retryCommand() : inputs.retryCommand)
|
|
1147
1172
|
})));
|
|
1148
1173
|
if (config.driver === void 0) return notOk$1(normalizeError(errorDriverRequired({ why: `Config.driver is required for ${commandName}` })));
|
|
1149
1174
|
if (!targetSupportsMigrations(config.target)) return notOk$1(normalizeError(errorTargetMigrationNotSupported({ why: `Target "${config.target.id}" does not support migrations` })));
|
|
@@ -2113,20 +2138,9 @@ function createDbSignCommand(createClient = createControlClient) {
|
|
|
2113
2138
|
});
|
|
2114
2139
|
}
|
|
2115
2140
|
const dbSignCommand = createDbSignCommand();
|
|
2116
|
-
/** The `--rename` texts a command was given, as statements, in the order given. */
|
|
2117
|
-
function renameStatements(texts) {
|
|
2118
|
-
return (texts ?? []).map((text) => ({
|
|
2119
|
-
verb: "rename",
|
|
2120
|
-
text
|
|
2121
|
-
}));
|
|
2122
|
-
}
|
|
2123
2141
|
/**
|
|
2124
2142
|
* A `db update` failure as the CLI's structured error.
|
|
2125
2143
|
*
|
|
2126
|
-
* `DESTRUCTIVE_CHANGES` is handled by the command, which asks for consent and
|
|
2127
|
-
* calls again; it is mapped here for the case the control API returns it from a
|
|
2128
|
-
* call that already carried consent, which would otherwise degrade silently.
|
|
2129
|
-
*
|
|
2130
2144
|
* The `assertNever` is deliberate: a control-API failure code this does not
|
|
2131
2145
|
* handle must stop the command rather than degrade into a generic message.
|
|
2132
2146
|
*/
|
|
@@ -2144,55 +2158,46 @@ function mapDbUpdateFailure(failure) {
|
|
|
2144
2158
|
...ifDefined("cause", failure.cause)
|
|
2145
2159
|
});
|
|
2146
2160
|
}
|
|
2147
|
-
if (failure.code === "DESTRUCTIVE_CHANGES") return errorDestructiveChanges(failure.summary, {
|
|
2148
|
-
...ifDefined("why", failure.why),
|
|
2149
|
-
fix: "Re-run `{bin} db update` and type the database name when asked, or pass `--no-interactive --confirm <database>` where there is nobody to ask. Use `--dry-run` to preview the operations first.",
|
|
2150
|
-
...failure.destructiveChanges ? { meta: {
|
|
2151
|
-
destructiveOperations: failure.destructiveChanges.destructiveOperations,
|
|
2152
|
-
databaseName: failure.destructiveChanges.databaseName,
|
|
2153
|
-
planHash: failure.destructiveChanges.planHash
|
|
2154
|
-
} } : {}
|
|
2155
|
-
});
|
|
2156
|
-
if (failure.code === "CONSENT_PLAN_MISMATCH") return errorConsentPlanMismatch({
|
|
2157
|
-
consentedPlanHash: failure.consentPlanMismatch?.consentedPlanHash ?? "",
|
|
2158
|
-
planHash: failure.consentPlanMismatch?.planHash ?? "",
|
|
2159
|
-
...ifDefined("why", failure.why)
|
|
2160
|
-
});
|
|
2161
2161
|
const exhaustive = failure.code;
|
|
2162
2162
|
return assertNever(exhaustive, `Unhandled DbUpdateFailure code: ${String(exhaustive)}`);
|
|
2163
2163
|
}
|
|
2164
2164
|
/**
|
|
2165
|
-
*
|
|
2166
|
-
*
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
kind: "run-command",
|
|
2183
|
-
label: "Preview the plan",
|
|
2184
|
-
command: options?.previewCommand ?? "{bin} db update --dry-run"
|
|
2185
|
-
}]
|
|
2186
|
-
});
|
|
2187
|
-
}
|
|
2188
|
-
/** The indented per-operation list every destructive-consent question renders. */
|
|
2189
|
-
function destructiveOperationList(operations) {
|
|
2190
|
-
return operations.map((operation) => ` - ${operation.label}`).join("\n");
|
|
2191
|
-
}
|
|
2192
|
-
/** The question the user answers before anything is dropped. */
|
|
2193
|
-
function destructiveConsentQuestion(operations, token) {
|
|
2194
|
-
return [`Apply ${operations.length} destructive operation(s) to ${token}? Data they remove cannot be recovered:`, destructiveOperationList(operations)].join("\n");
|
|
2165
|
+
* Asks a plan's questions through the engine's statement prompt, all in one batch that refuses a
|
|
2166
|
+
* statement nothing consumed before the command acts. Flags answer first; where nobody can answer,
|
|
2167
|
+
* the engine refuses and lists every question.
|
|
2168
|
+
*/
|
|
2169
|
+
function promptPlanQuestions(prompt) {
|
|
2170
|
+
return async (questions) => {
|
|
2171
|
+
return (await prompt.statements(questions.map((question) => ({
|
|
2172
|
+
question: question.question,
|
|
2173
|
+
subject: question.subject,
|
|
2174
|
+
verbs: question.verbs,
|
|
2175
|
+
forms: question.forms,
|
|
2176
|
+
validate: question.validate
|
|
2177
|
+
})), { last: true })).map(({ verb, text }) => ({
|
|
2178
|
+
verb,
|
|
2179
|
+
text
|
|
2180
|
+
}));
|
|
2181
|
+
};
|
|
2195
2182
|
}
|
|
2183
|
+
/**
|
|
2184
|
+
* The statement verbs the ORM commands declare. Each command declares the verbs its questions
|
|
2185
|
+
* use: `migration plan` takes `rename` and `delete`, and `db update` also `allow`.
|
|
2186
|
+
*/
|
|
2187
|
+
const ormStatementVerbs = {
|
|
2188
|
+
rename: {
|
|
2189
|
+
arity: 1,
|
|
2190
|
+
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"
|
|
2191
|
+
},
|
|
2192
|
+
delete: {
|
|
2193
|
+
arity: 1,
|
|
2194
|
+
brief: "Let the command lose the data of a model, field or storage name the refusal lists: --delete Model"
|
|
2195
|
+
},
|
|
2196
|
+
allow: {
|
|
2197
|
+
arity: 1,
|
|
2198
|
+
brief: "Let the command widen who can read or write the rows of a model: --allow Model"
|
|
2199
|
+
}
|
|
2200
|
+
};
|
|
2196
2201
|
function updatePresentations(inputs) {
|
|
2197
2202
|
const { document, database, dryRun } = inputs;
|
|
2198
2203
|
return {
|
|
@@ -2220,9 +2225,33 @@ function updatePresentations(inputs) {
|
|
|
2220
2225
|
]
|
|
2221
2226
|
}, ...migrationResultBlocks(document)],
|
|
2222
2227
|
json: () => document,
|
|
2223
|
-
next: () => migrationResultNextActions(document,
|
|
2228
|
+
next: () => migrationResultNextActions(document, [
|
|
2229
|
+
"{bin} db update",
|
|
2230
|
+
...inputs.to === void 0 ? [] : [`--to ${shellQuoted(inputs.to)}`],
|
|
2231
|
+
...inputs.dbGiven ? ["--db <url>"] : [],
|
|
2232
|
+
...inputs.advanceRef === void 0 ? [] : [`--advance-ref ${shellQuoted(inputs.advanceRef)}`],
|
|
2233
|
+
...inputs.statements.map(statementFlag)
|
|
2234
|
+
].join(" "))
|
|
2224
2235
|
};
|
|
2225
2236
|
}
|
|
2237
|
+
/**
|
|
2238
|
+
* The entries a dry run lists, each marked answered when a flag it was given answers its question:
|
|
2239
|
+
* a `--delete` answers every loss of its subject, and an `--allow` one operation, in order.
|
|
2240
|
+
*/
|
|
2241
|
+
function subjectEntriesJson(entries, verb, given) {
|
|
2242
|
+
const flagsLeft = /* @__PURE__ */ new Map();
|
|
2243
|
+
for (const statement of given) if (statement.verb === verb) flagsLeft.set(statement.text, (flagsLeft.get(statement.text) ?? 0) + 1);
|
|
2244
|
+
return entries.map((entry) => {
|
|
2245
|
+
const left = flagsLeft.get(entry.text) ?? 0;
|
|
2246
|
+
if (left > 0 && verb === "allow") flagsLeft.set(entry.text, left - 1);
|
|
2247
|
+
return {
|
|
2248
|
+
operationIndex: entry.operationIndex,
|
|
2249
|
+
subject: migrationSubjectJson(entry.subject),
|
|
2250
|
+
text: entry.text,
|
|
2251
|
+
answered: left > 0
|
|
2252
|
+
};
|
|
2253
|
+
});
|
|
2254
|
+
}
|
|
2226
2255
|
function updateDocument(inputs) {
|
|
2227
2256
|
const { value } = inputs;
|
|
2228
2257
|
return {
|
|
@@ -2251,6 +2280,10 @@ function updateDocument(inputs) {
|
|
|
2251
2280
|
} },
|
|
2252
2281
|
...ifDefined("perSpace", value.perSpace),
|
|
2253
2282
|
appliedStatements: value.appliedStatements,
|
|
2283
|
+
...value.mode === "plan" ? {
|
|
2284
|
+
dataLoss: subjectEntriesJson(value.dataLoss, "delete", inputs.statements),
|
|
2285
|
+
accessWidening: subjectEntriesJson(value.accessWidening, "allow", inputs.statements)
|
|
2286
|
+
} : {},
|
|
2254
2287
|
...ifDefined("warnings", value.warnings),
|
|
2255
2288
|
advancedRef: inputs.advancedRef,
|
|
2256
2289
|
plannedAdvanceRef: inputs.plannedAdvanceRef,
|
|
@@ -2258,15 +2291,23 @@ function updateDocument(inputs) {
|
|
|
2258
2291
|
timings: { total: Date.now() - inputs.startedAt }
|
|
2259
2292
|
};
|
|
2260
2293
|
}
|
|
2294
|
+
/** The delete and allow values the engine still holds for the questions, read without taking them. */
|
|
2295
|
+
function unansweredConsents(statements) {
|
|
2296
|
+
return statements.values().flatMap(({ verb, text }) => verb === "delete" || verb === "allow" ? [{
|
|
2297
|
+
verb,
|
|
2298
|
+
text
|
|
2299
|
+
}] : []);
|
|
2300
|
+
}
|
|
2261
2301
|
function createDbUpdateCommand(createClient) {
|
|
2262
2302
|
return defineOrmCommand({
|
|
2263
2303
|
help: {
|
|
2264
2304
|
summary: "Update your database schema to match your contract",
|
|
2265
|
-
description: "Compares the database to the emitted contract and applies the changes that\nclose the gap, whether or not the database was bootstrapped with `db init`.\
|
|
2305
|
+
description: "Compares the database to the emitted contract and applies the changes that\nclose the gap, whether or not the database was bootstrapped with `db init`.\nBefore it applies an operation that would lose data, it asks what the\noperation means: --rename keeps the data under a new name, --delete lets it\ngo. Before it widens who can read or write rows, it asks for --allow. Where\nnobody can answer, it refuses and lists every question. Use --dry-run to see\nthe operations and the questions without applying anything.",
|
|
2266
2306
|
examples: [
|
|
2267
2307
|
"db update",
|
|
2268
2308
|
"db update --dry-run",
|
|
2269
|
-
"db update --
|
|
2309
|
+
"db update --delete Legacy",
|
|
2310
|
+
"db update --rename Profile:User --allow User",
|
|
2270
2311
|
"db update --to production"
|
|
2271
2312
|
]
|
|
2272
2313
|
},
|
|
@@ -2280,15 +2321,23 @@ function createDbUpdateCommand(createClient) {
|
|
|
2280
2321
|
advanceRef: flag.string({
|
|
2281
2322
|
brief: "Advance the named ref to the post-command contract hash",
|
|
2282
2323
|
placeholder: "name"
|
|
2283
|
-
}),
|
|
2284
|
-
rename: flag.repeated({
|
|
2285
|
-
brief: "Rename a model or field: Model, namespace.Model, Model.field or namespace.Model.field on each side; repeat for several, applied in order",
|
|
2286
|
-
placeholder: "old:new"
|
|
2287
2324
|
})
|
|
2288
2325
|
} },
|
|
2326
|
+
statements: ormStatementVerbs,
|
|
2289
2327
|
needs: { config: ormConfigSection },
|
|
2290
2328
|
handler: async (args, ctx) => {
|
|
2291
2329
|
const startedAt = Date.now();
|
|
2330
|
+
const renames = ctx.statements.take("rename").map(({ text }) => ({
|
|
2331
|
+
verb: "rename",
|
|
2332
|
+
text
|
|
2333
|
+
}));
|
|
2334
|
+
const previewConsents = args.flags.dryRun ? [...ctx.statements.take("delete").map(({ text }) => ({
|
|
2335
|
+
verb: "delete",
|
|
2336
|
+
text
|
|
2337
|
+
})), ...ctx.statements.take("allow").map(({ text }) => ({
|
|
2338
|
+
verb: "allow",
|
|
2339
|
+
text
|
|
2340
|
+
}))] : [];
|
|
2292
2341
|
let destination;
|
|
2293
2342
|
if (args.flags.to !== void 0) {
|
|
2294
2343
|
const resolved = await resolveContractRefToSnapshot({
|
|
@@ -2307,11 +2356,15 @@ function createDbUpdateCommand(createClient) {
|
|
|
2307
2356
|
db: args.flags.db,
|
|
2308
2357
|
commandName: "db update",
|
|
2309
2358
|
createClient,
|
|
2310
|
-
retryCommand: retryCommandFor({
|
|
2359
|
+
retryCommand: () => retryCommandFor({
|
|
2311
2360
|
commandName: args.flags.dryRun ? "db update --dry-run" : "db update",
|
|
2312
2361
|
to: args.flags.to,
|
|
2313
2362
|
advanceRef: args.flags.advanceRef,
|
|
2314
|
-
|
|
2363
|
+
statements: [
|
|
2364
|
+
...renames,
|
|
2365
|
+
...previewConsents,
|
|
2366
|
+
...unansweredConsents(ctx.statements)
|
|
2367
|
+
],
|
|
2315
2368
|
canRunOffline: false
|
|
2316
2369
|
})
|
|
2317
2370
|
});
|
|
@@ -2342,35 +2395,21 @@ function createDbUpdateCommand(createClient) {
|
|
|
2342
2395
|
let document;
|
|
2343
2396
|
try {
|
|
2344
2397
|
await client.connect(dbConnection);
|
|
2345
|
-
const
|
|
2398
|
+
const reportPlannerWarnings = (warnings) => {
|
|
2399
|
+
for (const warning of warnings) ctx.report({
|
|
2400
|
+
kind: "message",
|
|
2401
|
+
severity: "warn",
|
|
2402
|
+
text: warning.summary
|
|
2403
|
+
});
|
|
2404
|
+
};
|
|
2405
|
+
const result = await client.dbUpdate({
|
|
2346
2406
|
contract: contractJson,
|
|
2347
2407
|
mode,
|
|
2348
2408
|
migrationsDir,
|
|
2349
|
-
statements:
|
|
2350
|
-
|
|
2409
|
+
statements: [...renames, ...previewConsents],
|
|
2410
|
+
answerQuestions: promptPlanQuestions(ctx.prompt),
|
|
2351
2411
|
onProgress: controlProgressReporter(ctx.report)
|
|
2352
2412
|
});
|
|
2353
|
-
const reported = /* @__PURE__ */ new Set();
|
|
2354
|
-
const reportPlannerWarnings = (warnings) => {
|
|
2355
|
-
for (const warning of warnings) if (!reported.has(warning.summary)) {
|
|
2356
|
-
reported.add(warning.summary);
|
|
2357
|
-
ctx.report({
|
|
2358
|
-
kind: "message",
|
|
2359
|
-
severity: "warn",
|
|
2360
|
-
text: warning.summary
|
|
2361
|
-
});
|
|
2362
|
-
}
|
|
2363
|
-
};
|
|
2364
|
-
let result = await update();
|
|
2365
|
-
if (mode === "apply" && !result.ok && result.failure.code === "DESTRUCTIVE_CHANGES") {
|
|
2366
|
-
reportPlannerWarnings(result.failure.warnings ?? []);
|
|
2367
|
-
const refusal = result.failure.destructiveChanges;
|
|
2368
|
-
if (refusal === void 0 || refusal.destructiveOperations.length === 0) return notOk$1(normalizeError(errorConsentOperationsMissing()));
|
|
2369
|
-
const token = refusal.databaseName ?? "";
|
|
2370
|
-
if (token.trim().length === 0) return notOk$1(normalizeError(errorConsentTokenUnresolved(ctx.config.target.targetId)));
|
|
2371
|
-
if (!await ctx.prompt.consent(destructiveConsentQuestion(refusal.destructiveOperations, token), { token })) return notOk$1(normalizeError(mapDbUpdateFailure(result.failure)));
|
|
2372
|
-
result = await update({ planHash: refusal.planHash });
|
|
2373
|
-
}
|
|
2374
2413
|
if (!result.ok) {
|
|
2375
2414
|
reportPlannerWarnings(result.failure.warnings ?? []);
|
|
2376
2415
|
return notOk$1(normalizeError(mapDbUpdateFailure(result.failure)));
|
|
@@ -2390,7 +2429,8 @@ function createDbUpdateCommand(createClient) {
|
|
|
2390
2429
|
targetId: ctx.config.target.targetId,
|
|
2391
2430
|
advancedRef: advanced.value.advancedRef,
|
|
2392
2431
|
plannedAdvanceRef: advanced.value.plannedAdvanceRef,
|
|
2393
|
-
startedAt
|
|
2432
|
+
startedAt,
|
|
2433
|
+
statements: previewConsents
|
|
2394
2434
|
});
|
|
2395
2435
|
} catch (error) {
|
|
2396
2436
|
if (error instanceof CliStructuredError$1) throw error;
|
|
@@ -2409,7 +2449,10 @@ function createDbUpdateCommand(createClient) {
|
|
|
2409
2449
|
contractPath: prepared.value.contractDisplayPath,
|
|
2410
2450
|
database: prepared.value.database,
|
|
2411
2451
|
to: args.flags.to,
|
|
2412
|
-
dryRun: args.flags.dryRun
|
|
2452
|
+
dryRun: args.flags.dryRun,
|
|
2453
|
+
dbGiven: args.flags.db !== void 0,
|
|
2454
|
+
advanceRef: args.flags.advanceRef,
|
|
2455
|
+
statements: [...renames, ...previewConsents]
|
|
2413
2456
|
})));
|
|
2414
2457
|
}
|
|
2415
2458
|
});
|
|
@@ -10462,19 +10505,16 @@ function planPresentations(inputs) {
|
|
|
10462
10505
|
next: () => planNextActions(inputs.document, inputs.migrationsRelative)
|
|
10463
10506
|
};
|
|
10464
10507
|
}
|
|
10465
|
-
/** The question the user answers before a destructive baseline is written. */
|
|
10466
|
-
function destructiveBaselineQuestion(operations) {
|
|
10467
|
-
return [`Write a baseline migration containing ${operations.length} destructive operation(s)? Applying it would remove data that cannot be recovered:`, destructiveOperationList(operations)].join("\n");
|
|
10468
|
-
}
|
|
10469
10508
|
function createMigrationPlanCommand(createClient) {
|
|
10470
10509
|
return defineOrmCommand({
|
|
10471
10510
|
help: {
|
|
10472
10511
|
summary: "Plan a migration from contract changes",
|
|
10473
|
-
description: "Compares the emitted contract against the latest on-disk migration state\nand produces a new migration package with the required operations.\nOn an empty migrations directory a baseline package is derived from the\n`db` ref first
|
|
10512
|
+
description: "Compares the emitted contract against the latest on-disk migration state\nand produces a new migration package with the required operations.\nOn an empty migrations directory a baseline package is derived from the\n`db` ref first. A plan that would lose data is written only once you say\nwhat each such operation means: --rename to keep the data under a new\nname, or --delete to let it go. Where nobody can answer, the command\nrefuses and lists every question. Offline — does not consult the database.",
|
|
10474
10513
|
examples: [
|
|
10475
10514
|
"migration plan",
|
|
10476
10515
|
"migration plan --name add-users-table",
|
|
10477
10516
|
"migration plan --to <migration-dir>^ --name rollback",
|
|
10517
|
+
"migration plan --rename Profile:User --delete Legacy",
|
|
10478
10518
|
"migration plan --json"
|
|
10479
10519
|
]
|
|
10480
10520
|
},
|
|
@@ -10490,21 +10530,16 @@ function createMigrationPlanCommand(createClient) {
|
|
|
10490
10530
|
to: flag.string({
|
|
10491
10531
|
brief: `Destination contract reference (${RECORDED_CONTRACT_REF_FORMS}); defaults to the emitted contract`,
|
|
10492
10532
|
placeholder: "contract"
|
|
10493
|
-
}),
|
|
10494
|
-
rename: flag.repeated({
|
|
10495
|
-
brief: "Rename a model or field: Model, namespace.Model, Model.field or namespace.Model.field on each side; repeat for several, applied in order",
|
|
10496
|
-
placeholder: "old:new"
|
|
10497
10533
|
})
|
|
10498
10534
|
} },
|
|
10535
|
+
statements: {
|
|
10536
|
+
rename: ormStatementVerbs.rename,
|
|
10537
|
+
delete: ormStatementVerbs.delete
|
|
10538
|
+
},
|
|
10499
10539
|
needs: { config: ormConfigSection },
|
|
10500
10540
|
handler: async (args, ctx) => {
|
|
10501
|
-
const seededDirs = [];
|
|
10502
10541
|
const seeded = (record) => {
|
|
10503
10542
|
if (record.action !== "updated") return;
|
|
10504
|
-
for (const dirName of record.newMigrationDirs) seededDirs.push({
|
|
10505
|
-
spaceId: record.spaceId,
|
|
10506
|
-
dirName
|
|
10507
|
-
});
|
|
10508
10543
|
const step = `Seed contract space ${record.spaceId}`;
|
|
10509
10544
|
ctx.report({
|
|
10510
10545
|
kind: "step-started",
|
|
@@ -10522,16 +10557,18 @@ function createMigrationPlanCommand(createClient) {
|
|
|
10522
10557
|
}
|
|
10523
10558
|
});
|
|
10524
10559
|
};
|
|
10525
|
-
const
|
|
10560
|
+
const planned = await executeMigrationPlanCommand({
|
|
10526
10561
|
config: ctx.config,
|
|
10527
10562
|
cwd: ctx.cwd,
|
|
10528
10563
|
projectDir: baseDirFor(ctx.config),
|
|
10529
10564
|
...ifDefined("name", args.flags.name),
|
|
10530
10565
|
...ifDefined("from", args.flags.from),
|
|
10531
10566
|
...ifDefined("to", args.flags.to),
|
|
10532
|
-
statements:
|
|
10533
|
-
|
|
10534
|
-
|
|
10567
|
+
statements: ctx.statements.take("rename").map(({ text }) => ({
|
|
10568
|
+
verb: "rename",
|
|
10569
|
+
text
|
|
10570
|
+
})),
|
|
10571
|
+
answerQuestions: promptPlanQuestions(ctx.prompt),
|
|
10535
10572
|
client: createClient({
|
|
10536
10573
|
family: ctx.config.family,
|
|
10537
10574
|
target: ctx.config.target,
|
|
@@ -10540,14 +10577,6 @@ function createMigrationPlanCommand(createClient) {
|
|
|
10540
10577
|
extensions: ctx.config.extensions ?? []
|
|
10541
10578
|
})
|
|
10542
10579
|
}, Date.now(), { onSeeded: seeded });
|
|
10543
|
-
let planned = await plan();
|
|
10544
|
-
if (!planned.ok && planned.failure.code === ERROR_CODE_DESTRUCTIVE_CHANGES) {
|
|
10545
|
-
const verdict = blindCast(planned.failure.meta ?? {});
|
|
10546
|
-
if (verdict.destructiveOperations === void 0 || verdict.destructiveOperations.length === 0 || verdict.planHash === void 0) return notOk$1(normalizeError(errorConsentOperationsMissing({ previewCommand: "{bin} migration plan" })));
|
|
10547
|
-
const token = consentToken(ctx.cwd);
|
|
10548
|
-
if (!await ctx.prompt.consent(destructiveBaselineQuestion(verdict.destructiveOperations), { token })) return notOk$1(normalizeError(planned.failure));
|
|
10549
|
-
planned = await plan({ planHash: verdict.planHash });
|
|
10550
|
-
}
|
|
10551
10580
|
if (!planned.ok) return notOk$1(normalizeError(planned.failure));
|
|
10552
10581
|
ctx.report({
|
|
10553
10582
|
kind: "message",
|