@prisma-next/cli 0.3.0-dev.7 → 0.3.0-dev.71
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/LICENSE +201 -0
- package/README.md +314 -80
- package/dist/cli-errors-JlPTsazx.mjs +3 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.js +1 -2376
- package/dist/cli.mjs +198 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/client-PimzSD1f.mjs +981 -0
- package/dist/client-PimzSD1f.mjs.map +1 -0
- package/dist/commands/contract-emit.d.mts +7 -0
- package/dist/commands/contract-emit.d.mts.map +1 -0
- package/dist/commands/contract-emit.mjs +150 -0
- package/dist/commands/contract-emit.mjs.map +1 -0
- package/dist/commands/db-init.d.mts +7 -0
- package/dist/commands/db-init.d.mts.map +1 -0
- package/dist/commands/db-init.mjs +132 -0
- package/dist/commands/db-init.mjs.map +1 -0
- package/dist/commands/db-introspect.d.mts +7 -0
- package/dist/commands/db-introspect.d.mts.map +1 -0
- package/dist/commands/db-introspect.mjs +117 -0
- package/dist/commands/db-introspect.mjs.map +1 -0
- package/dist/commands/db-schema-verify.d.mts +7 -0
- package/dist/commands/db-schema-verify.d.mts.map +1 -0
- package/dist/commands/db-schema-verify.mjs +119 -0
- package/dist/commands/db-schema-verify.mjs.map +1 -0
- package/dist/commands/db-sign.d.mts +7 -0
- package/dist/commands/db-sign.d.mts.map +1 -0
- package/dist/commands/db-sign.mjs +141 -0
- package/dist/commands/db-sign.mjs.map +1 -0
- package/dist/commands/db-update.d.mts +7 -0
- package/dist/commands/db-update.d.mts.map +1 -0
- package/dist/commands/db-update.mjs +121 -0
- package/dist/commands/db-update.mjs.map +1 -0
- package/dist/commands/db-verify.d.mts +7 -0
- package/dist/commands/db-verify.d.mts.map +1 -0
- package/dist/commands/db-verify.mjs +132 -0
- package/dist/commands/db-verify.mjs.map +1 -0
- package/dist/commands/migration-apply.d.mts +23 -0
- package/dist/commands/migration-apply.d.mts.map +1 -0
- package/dist/commands/migration-apply.mjs +249 -0
- package/dist/commands/migration-apply.mjs.map +1 -0
- package/dist/commands/migration-plan.d.mts +25 -0
- package/dist/commands/migration-plan.d.mts.map +1 -0
- package/dist/commands/migration-plan.mjs +266 -0
- package/dist/commands/migration-plan.mjs.map +1 -0
- package/dist/commands/migration-show.d.mts +28 -0
- package/dist/commands/migration-show.d.mts.map +1 -0
- package/dist/commands/migration-show.mjs +138 -0
- package/dist/commands/migration-show.mjs.map +1 -0
- package/dist/commands/migration-status.d.mts +35 -0
- package/dist/commands/migration-status.d.mts.map +1 -0
- package/dist/commands/migration-status.mjs +259 -0
- package/dist/commands/migration-status.mjs.map +1 -0
- package/dist/commands/migration-verify.d.mts +16 -0
- package/dist/commands/migration-verify.d.mts.map +1 -0
- package/dist/commands/migration-verify.mjs +86 -0
- package/dist/commands/migration-verify.mjs.map +1 -0
- package/dist/config-loader-PPf4CtDj.mjs +43 -0
- package/dist/config-loader-PPf4CtDj.mjs.map +1 -0
- package/dist/{config-loader.d.ts → config-loader.d.mts} +8 -3
- package/dist/config-loader.d.mts.map +1 -0
- package/dist/config-loader.mjs +3 -0
- package/dist/exports/config-types.d.mts +2 -0
- package/dist/exports/config-types.mjs +3 -0
- package/dist/exports/control-api.d.mts +621 -0
- package/dist/exports/control-api.d.mts.map +1 -0
- package/dist/exports/control-api.mjs +97 -0
- package/dist/exports/control-api.mjs.map +1 -0
- package/dist/{load-ts-contract.d.ts → exports/index.d.mts} +10 -5
- package/dist/exports/index.d.mts.map +1 -0
- package/dist/exports/index.mjs +130 -0
- package/dist/exports/index.mjs.map +1 -0
- package/dist/extract-sql-ddl-BmlKvk4o.mjs +26 -0
- package/dist/extract-sql-ddl-BmlKvk4o.mjs.map +1 -0
- package/dist/framework-components-CjV_jD8f.mjs +59 -0
- package/dist/framework-components-CjV_jD8f.mjs.map +1 -0
- package/dist/migration-command-scaffold-DfY_F3ev.mjs +97 -0
- package/dist/migration-command-scaffold-DfY_F3ev.mjs.map +1 -0
- package/dist/progress-adapter-DENrzF6I.mjs +49 -0
- package/dist/progress-adapter-DENrzF6I.mjs.map +1 -0
- package/dist/result-handler-iA9JtUC7.mjs +1186 -0
- package/dist/result-handler-iA9JtUC7.mjs.map +1 -0
- package/package.json +75 -38
- package/src/cli.ts +43 -0
- package/src/commands/contract-emit.ts +221 -111
- package/src/commands/db-init.ts +217 -426
- package/src/commands/db-introspect.ts +148 -185
- package/src/commands/db-schema-verify.ts +162 -149
- package/src/commands/db-sign.ts +215 -202
- package/src/commands/db-update.ts +220 -0
- package/src/commands/db-verify.ts +193 -156
- package/src/commands/migration-apply.ts +431 -0
- package/src/commands/migration-plan.ts +446 -0
- package/src/commands/migration-show.ts +255 -0
- package/src/commands/migration-status.ts +436 -0
- package/src/commands/migration-verify.ts +151 -0
- package/src/config-loader.ts +13 -3
- package/src/control-api/client.ts +605 -0
- package/src/control-api/errors.ts +9 -0
- package/src/control-api/operations/contract-emit.ts +161 -0
- package/src/control-api/operations/db-init.ts +286 -0
- package/src/control-api/operations/db-update.ts +221 -0
- package/src/control-api/operations/extract-sql-ddl.ts +47 -0
- package/src/control-api/operations/migration-apply.ts +195 -0
- package/src/control-api/operations/migration-helpers.ts +49 -0
- package/src/control-api/types.ts +687 -0
- package/src/exports/config-types.ts +3 -3
- package/src/exports/control-api.ts +53 -0
- package/src/load-ts-contract.ts +16 -11
- package/src/utils/cli-errors.ts +3 -1
- package/src/utils/command-helpers.ts +92 -3
- package/src/utils/framework-components.ts +11 -30
- package/src/utils/migration-command-scaffold.ts +190 -0
- package/src/utils/output.ts +363 -25
- package/src/utils/progress-adapter.ts +86 -0
- package/dist/chunk-464LNZCE.js +0 -134
- package/dist/chunk-464LNZCE.js.map +0 -1
- package/dist/chunk-BZMBKEEQ.js +0 -997
- package/dist/chunk-BZMBKEEQ.js.map +0 -1
- package/dist/chunk-HWYQOCAJ.js +0 -47
- package/dist/chunk-HWYQOCAJ.js.map +0 -1
- package/dist/chunk-ZKYEJROM.js +0 -94
- package/dist/chunk-ZKYEJROM.js.map +0 -1
- package/dist/cli.d.ts +0 -2
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/commands/contract-emit.d.ts +0 -3
- package/dist/commands/contract-emit.d.ts.map +0 -1
- package/dist/commands/contract-emit.js +0 -9
- package/dist/commands/contract-emit.js.map +0 -1
- package/dist/commands/db-init.d.ts +0 -3
- package/dist/commands/db-init.d.ts.map +0 -1
- package/dist/commands/db-init.js +0 -341
- package/dist/commands/db-init.js.map +0 -1
- package/dist/commands/db-introspect.d.ts +0 -3
- package/dist/commands/db-introspect.d.ts.map +0 -1
- package/dist/commands/db-introspect.js +0 -190
- package/dist/commands/db-introspect.js.map +0 -1
- package/dist/commands/db-schema-verify.d.ts +0 -3
- package/dist/commands/db-schema-verify.d.ts.map +0 -1
- package/dist/commands/db-schema-verify.js +0 -164
- package/dist/commands/db-schema-verify.js.map +0 -1
- package/dist/commands/db-sign.d.ts +0 -3
- package/dist/commands/db-sign.d.ts.map +0 -1
- package/dist/commands/db-sign.js +0 -199
- package/dist/commands/db-sign.js.map +0 -1
- package/dist/commands/db-verify.d.ts +0 -3
- package/dist/commands/db-verify.d.ts.map +0 -1
- package/dist/commands/db-verify.js +0 -173
- package/dist/commands/db-verify.js.map +0 -1
- package/dist/config-loader.d.ts.map +0 -1
- package/dist/config-loader.js +0 -7
- package/dist/config-loader.js.map +0 -1
- package/dist/exports/config-types.d.ts +0 -3
- package/dist/exports/config-types.d.ts.map +0 -1
- package/dist/exports/config-types.js +0 -6
- package/dist/exports/config-types.js.map +0 -1
- package/dist/exports/index.d.ts +0 -4
- package/dist/exports/index.d.ts.map +0 -1
- package/dist/exports/index.js +0 -175
- package/dist/exports/index.js.map +0 -1
- package/dist/load-ts-contract.d.ts.map +0 -1
- package/dist/utils/action.d.ts +0 -16
- package/dist/utils/action.d.ts.map +0 -1
- package/dist/utils/cli-errors.d.ts +0 -7
- package/dist/utils/cli-errors.d.ts.map +0 -1
- package/dist/utils/command-helpers.d.ts +0 -12
- package/dist/utils/command-helpers.d.ts.map +0 -1
- package/dist/utils/framework-components.d.ts +0 -81
- package/dist/utils/framework-components.d.ts.map +0 -1
- package/dist/utils/global-flags.d.ts +0 -25
- package/dist/utils/global-flags.d.ts.map +0 -1
- package/dist/utils/output.d.ts +0 -142
- package/dist/utils/output.d.ts.map +0 -1
- package/dist/utils/result-handler.d.ts +0 -15
- package/dist/utils/result-handler.d.ts.map +0 -1
- package/dist/utils/spinner.d.ts +0 -29
- package/dist/utils/spinner.d.ts.map +0 -1
- package/src/utils/action.ts +0 -43
- package/src/utils/spinner.ts +0 -67
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import type { ContractIR } from '@prisma-next/contract/ir';
|
|
3
|
+
import { EMPTY_CONTRACT_HASH } from '@prisma-next/core-control-plane/constants';
|
|
4
|
+
import { createControlPlaneStack } from '@prisma-next/core-control-plane/stack';
|
|
5
|
+
import type {
|
|
6
|
+
ControlTargetDescriptor,
|
|
7
|
+
MigrationPlanOperation,
|
|
8
|
+
} from '@prisma-next/core-control-plane/types';
|
|
9
|
+
import { attestMigration } from '@prisma-next/migration-tools/attestation';
|
|
10
|
+
import { findLatestMigration, reconstructGraph } from '@prisma-next/migration-tools/dag';
|
|
11
|
+
import {
|
|
12
|
+
formatMigrationDirName,
|
|
13
|
+
readMigrationsDir,
|
|
14
|
+
writeMigrationPackage,
|
|
15
|
+
} from '@prisma-next/migration-tools/io';
|
|
16
|
+
import { type MigrationManifest, MigrationToolsError } from '@prisma-next/migration-tools/types';
|
|
17
|
+
import { notOk, ok, type Result } from '@prisma-next/utils/result';
|
|
18
|
+
import { Command } from 'commander';
|
|
19
|
+
import { join, relative, resolve } from 'pathe';
|
|
20
|
+
import { loadConfig } from '../config-loader';
|
|
21
|
+
import { extractSqlDdl } from '../control-api/operations/extract-sql-ddl';
|
|
22
|
+
import {
|
|
23
|
+
type CliErrorConflict,
|
|
24
|
+
type CliStructuredError,
|
|
25
|
+
errorContractValidationFailed,
|
|
26
|
+
errorFileNotFound,
|
|
27
|
+
errorMigrationPlanningFailed,
|
|
28
|
+
errorRuntime,
|
|
29
|
+
errorTargetMigrationNotSupported,
|
|
30
|
+
errorUnexpected,
|
|
31
|
+
} from '../utils/cli-errors';
|
|
32
|
+
import { resolveContractPath, setCommandDescriptions } from '../utils/command-helpers';
|
|
33
|
+
import { assertFrameworkComponentsCompatible } from '../utils/framework-components';
|
|
34
|
+
import { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';
|
|
35
|
+
import { formatCommandHelp, formatStyledHeader } from '../utils/output';
|
|
36
|
+
import { handleResult } from '../utils/result-handler';
|
|
37
|
+
|
|
38
|
+
interface MigrationPlanOptions {
|
|
39
|
+
readonly config?: string;
|
|
40
|
+
readonly name?: string;
|
|
41
|
+
readonly from?: string;
|
|
42
|
+
readonly json?: string | boolean;
|
|
43
|
+
readonly quiet?: boolean;
|
|
44
|
+
readonly q?: boolean;
|
|
45
|
+
readonly verbose?: boolean;
|
|
46
|
+
readonly v?: boolean;
|
|
47
|
+
readonly vv?: boolean;
|
|
48
|
+
readonly trace?: boolean;
|
|
49
|
+
readonly timestamps?: boolean;
|
|
50
|
+
readonly color?: boolean;
|
|
51
|
+
readonly 'no-color'?: boolean;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface MigrationPlanResult {
|
|
55
|
+
readonly ok: boolean;
|
|
56
|
+
readonly noOp: boolean;
|
|
57
|
+
readonly from: string;
|
|
58
|
+
readonly to: string;
|
|
59
|
+
readonly migrationId?: string;
|
|
60
|
+
readonly dir?: string;
|
|
61
|
+
readonly operations: readonly {
|
|
62
|
+
readonly id: string;
|
|
63
|
+
readonly label: string;
|
|
64
|
+
readonly operationClass: string;
|
|
65
|
+
}[];
|
|
66
|
+
readonly sql?: readonly string[];
|
|
67
|
+
readonly summary: string;
|
|
68
|
+
readonly timings: {
|
|
69
|
+
readonly total: number;
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function mapMigrationToolsError(error: unknown): CliStructuredError {
|
|
74
|
+
if (MigrationToolsError.is(error)) {
|
|
75
|
+
return errorRuntime(error.message, {
|
|
76
|
+
why: error.why,
|
|
77
|
+
fix: error.fix,
|
|
78
|
+
meta: { code: error.code, ...(error.details ?? {}) },
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
return errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
82
|
+
why: `Unexpected error during migration plan: ${error instanceof Error ? error.message : String(error)}`,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function executeMigrationPlanCommand(
|
|
87
|
+
options: MigrationPlanOptions,
|
|
88
|
+
flags: GlobalFlags,
|
|
89
|
+
startTime: number,
|
|
90
|
+
): Promise<Result<MigrationPlanResult, CliStructuredError>> {
|
|
91
|
+
const config = await loadConfig(options.config);
|
|
92
|
+
const configPath = options.config
|
|
93
|
+
? relative(process.cwd(), resolve(options.config))
|
|
94
|
+
: 'prisma-next.config.ts';
|
|
95
|
+
|
|
96
|
+
const migrationsDir = resolve(
|
|
97
|
+
options.config ? resolve(options.config, '..') : process.cwd(),
|
|
98
|
+
config.migrations?.dir ?? 'migrations',
|
|
99
|
+
);
|
|
100
|
+
const migrationsRelative = relative(process.cwd(), migrationsDir);
|
|
101
|
+
|
|
102
|
+
const contractPathAbsolute = resolveContractPath(config);
|
|
103
|
+
const contractPath = relative(process.cwd(), contractPathAbsolute);
|
|
104
|
+
|
|
105
|
+
if (flags.json !== 'object' && !flags.quiet) {
|
|
106
|
+
const details: Array<{ label: string; value: string }> = [
|
|
107
|
+
{ label: 'config', value: configPath },
|
|
108
|
+
{ label: 'contract', value: contractPath },
|
|
109
|
+
{ label: 'migrations', value: migrationsRelative },
|
|
110
|
+
];
|
|
111
|
+
if (options.from) {
|
|
112
|
+
details.push({ label: 'from', value: options.from });
|
|
113
|
+
}
|
|
114
|
+
if (options.name) {
|
|
115
|
+
details.push({ label: 'name', value: options.name });
|
|
116
|
+
}
|
|
117
|
+
const header = formatStyledHeader({
|
|
118
|
+
command: 'migration plan',
|
|
119
|
+
description: 'Plan a migration from contract changes',
|
|
120
|
+
url: 'https://pris.ly/migration-plan',
|
|
121
|
+
details,
|
|
122
|
+
flags,
|
|
123
|
+
});
|
|
124
|
+
console.log(header);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Load contract file (the "to" contract)
|
|
128
|
+
let contractJsonContent: string;
|
|
129
|
+
try {
|
|
130
|
+
contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
|
|
131
|
+
} catch (error) {
|
|
132
|
+
if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
|
|
133
|
+
return notOk(
|
|
134
|
+
errorFileNotFound(contractPathAbsolute, {
|
|
135
|
+
why: `Contract file not found at ${contractPathAbsolute}`,
|
|
136
|
+
fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`,
|
|
137
|
+
}),
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
return notOk(
|
|
141
|
+
errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
142
|
+
why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
|
|
143
|
+
}),
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
let toContractJson: ContractIR;
|
|
148
|
+
try {
|
|
149
|
+
toContractJson = JSON.parse(contractJsonContent) as ContractIR;
|
|
150
|
+
} catch (error) {
|
|
151
|
+
return notOk(
|
|
152
|
+
errorContractValidationFailed(
|
|
153
|
+
`Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
|
|
154
|
+
{ where: { path: contractPathAbsolute } },
|
|
155
|
+
),
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const toStorageHash = (toContractJson as unknown as Record<string, unknown>)['storageHash'] as
|
|
160
|
+
| string
|
|
161
|
+
| undefined;
|
|
162
|
+
if (!toStorageHash) {
|
|
163
|
+
return notOk(
|
|
164
|
+
errorContractValidationFailed('Contract is missing storageHash', {
|
|
165
|
+
where: { path: contractPathAbsolute },
|
|
166
|
+
}),
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Read existing migrations and determine "from" contract
|
|
171
|
+
let fromContract: ContractIR | null = null;
|
|
172
|
+
let fromHash: string = EMPTY_CONTRACT_HASH;
|
|
173
|
+
let parentMigrationId: string | null = null;
|
|
174
|
+
|
|
175
|
+
try {
|
|
176
|
+
const allPackages = await readMigrationsDir(migrationsDir);
|
|
177
|
+
const packages = allPackages.filter((p) => typeof p.manifest.migrationId === 'string');
|
|
178
|
+
const graph = reconstructGraph(packages);
|
|
179
|
+
const latestMigration = findLatestMigration(graph);
|
|
180
|
+
const leafHash = latestMigration ? latestMigration.to : EMPTY_CONTRACT_HASH;
|
|
181
|
+
|
|
182
|
+
if (options.from) {
|
|
183
|
+
fromHash = options.from;
|
|
184
|
+
const sourcePkg = packages.find((p) => p.manifest.to === fromHash);
|
|
185
|
+
if (!sourcePkg) {
|
|
186
|
+
return notOk(
|
|
187
|
+
errorRuntime('Starting contract not found', {
|
|
188
|
+
why: `No migration with to="${fromHash}" exists in ${migrationsRelative}`,
|
|
189
|
+
fix: 'Check that the --from hash matches a known migration target hash, or omit --from to use the latest migration leaf.',
|
|
190
|
+
}),
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
fromContract = sourcePkg.manifest.toContract;
|
|
194
|
+
parentMigrationId = sourcePkg.manifest.migrationId;
|
|
195
|
+
} else if (leafHash !== EMPTY_CONTRACT_HASH && latestMigration) {
|
|
196
|
+
fromHash = leafHash;
|
|
197
|
+
parentMigrationId = latestMigration.migrationId;
|
|
198
|
+
const leafPkg = packages.find((p) => p.manifest.migrationId === latestMigration.migrationId);
|
|
199
|
+
if (leafPkg) {
|
|
200
|
+
fromContract = leafPkg.manifest.toContract;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
} catch (error) {
|
|
204
|
+
if (MigrationToolsError.is(error)) {
|
|
205
|
+
return notOk(mapMigrationToolsError(error));
|
|
206
|
+
}
|
|
207
|
+
throw error;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Check for no-op (same hash means no changes)
|
|
211
|
+
if (fromHash === toStorageHash) {
|
|
212
|
+
const result: MigrationPlanResult = {
|
|
213
|
+
ok: true,
|
|
214
|
+
noOp: true,
|
|
215
|
+
from: fromHash,
|
|
216
|
+
to: toStorageHash,
|
|
217
|
+
operations: [],
|
|
218
|
+
summary: 'No changes detected between contracts',
|
|
219
|
+
timings: { total: Date.now() - startTime },
|
|
220
|
+
};
|
|
221
|
+
return ok(result);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Check target supports migrations
|
|
225
|
+
const targetWithMigrations = config.target as ControlTargetDescriptor<string, string>;
|
|
226
|
+
if (!targetWithMigrations.migrations) {
|
|
227
|
+
return notOk(
|
|
228
|
+
errorTargetMigrationNotSupported({
|
|
229
|
+
why: `Target "${config.target.id}" does not support migrations`,
|
|
230
|
+
}),
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// Plan migration using the same planner as db init
|
|
235
|
+
const { migrations } = targetWithMigrations;
|
|
236
|
+
const stack = createControlPlaneStack({
|
|
237
|
+
target: config.target,
|
|
238
|
+
adapter: config.adapter,
|
|
239
|
+
extensionPacks: config.extensionPacks ?? [],
|
|
240
|
+
});
|
|
241
|
+
const familyInstance = config.family.create(stack);
|
|
242
|
+
const frameworkComponents = assertFrameworkComponentsCompatible(
|
|
243
|
+
config.family.familyId,
|
|
244
|
+
config.target.targetId,
|
|
245
|
+
[config.target, config.adapter, ...(config.extensionPacks ?? [])],
|
|
246
|
+
);
|
|
247
|
+
const planner = migrations.createPlanner(familyInstance);
|
|
248
|
+
const fromSchemaIR = migrations.contractToSchema(fromContract);
|
|
249
|
+
const plannerResult = planner.plan({
|
|
250
|
+
contract: toContractJson,
|
|
251
|
+
schema: fromSchemaIR,
|
|
252
|
+
policy: { allowedOperationClasses: ['additive', 'widening', 'destructive'] },
|
|
253
|
+
frameworkComponents,
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
if (plannerResult.kind === 'failure') {
|
|
257
|
+
return notOk(
|
|
258
|
+
errorMigrationPlanningFailed({
|
|
259
|
+
conflicts: plannerResult.conflicts as readonly CliErrorConflict[],
|
|
260
|
+
}),
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const ops: readonly MigrationPlanOperation[] = plannerResult.plan.operations;
|
|
265
|
+
|
|
266
|
+
if (ops.length === 0) {
|
|
267
|
+
return notOk(
|
|
268
|
+
errorMigrationPlanningFailed({
|
|
269
|
+
conflicts: [
|
|
270
|
+
{
|
|
271
|
+
kind: 'unsupportedChange',
|
|
272
|
+
summary:
|
|
273
|
+
'Contract changed but planner produced no operations. ' +
|
|
274
|
+
'This indicates unsupported or ignored changes (e.g. removals, type changes, or a planner/contract mismatch).',
|
|
275
|
+
},
|
|
276
|
+
],
|
|
277
|
+
}),
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Build manifest and write migration package
|
|
282
|
+
const timestamp = new Date();
|
|
283
|
+
const slug = options.name ?? 'migration';
|
|
284
|
+
const dirName = formatMigrationDirName(timestamp, slug);
|
|
285
|
+
const packageDir = join(migrationsDir, dirName);
|
|
286
|
+
|
|
287
|
+
const manifest: MigrationManifest = {
|
|
288
|
+
from: fromHash,
|
|
289
|
+
to: toStorageHash,
|
|
290
|
+
migrationId: null,
|
|
291
|
+
parentMigrationId,
|
|
292
|
+
kind: 'regular',
|
|
293
|
+
fromContract,
|
|
294
|
+
toContract: toContractJson,
|
|
295
|
+
hints: {
|
|
296
|
+
used: [],
|
|
297
|
+
applied: [],
|
|
298
|
+
plannerVersion: '1.0.0',
|
|
299
|
+
planningStrategy: 'diff',
|
|
300
|
+
},
|
|
301
|
+
labels: [],
|
|
302
|
+
createdAt: timestamp.toISOString(),
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
try {
|
|
306
|
+
await writeMigrationPackage(packageDir, manifest, ops);
|
|
307
|
+
const migrationId = await attestMigration(packageDir);
|
|
308
|
+
|
|
309
|
+
const sql = extractSqlDdl(ops);
|
|
310
|
+
const result: MigrationPlanResult = {
|
|
311
|
+
ok: true,
|
|
312
|
+
noOp: false,
|
|
313
|
+
from: fromHash,
|
|
314
|
+
to: toStorageHash,
|
|
315
|
+
migrationId,
|
|
316
|
+
dir: relative(process.cwd(), packageDir),
|
|
317
|
+
operations: ops.map((op) => ({
|
|
318
|
+
id: op.id,
|
|
319
|
+
label: op.label,
|
|
320
|
+
operationClass: op.operationClass,
|
|
321
|
+
})),
|
|
322
|
+
sql,
|
|
323
|
+
summary: `Planned ${ops.length} operation(s)`,
|
|
324
|
+
timings: { total: Date.now() - startTime },
|
|
325
|
+
};
|
|
326
|
+
return ok(result);
|
|
327
|
+
} catch (error) {
|
|
328
|
+
return notOk(mapMigrationToolsError(error));
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export function createMigrationPlanCommand(): Command {
|
|
333
|
+
const command = new Command('plan');
|
|
334
|
+
setCommandDescriptions(
|
|
335
|
+
command,
|
|
336
|
+
'Plan a migration from contract changes',
|
|
337
|
+
'Compares the emitted contract against the latest on-disk migration state and\n' +
|
|
338
|
+
'produces a new migration package with the required operations. No database\n' +
|
|
339
|
+
'connection is needed — this is a fully offline operation.',
|
|
340
|
+
);
|
|
341
|
+
command
|
|
342
|
+
.configureHelp({
|
|
343
|
+
formatHelp: (cmd) => {
|
|
344
|
+
const flags = parseGlobalFlags({});
|
|
345
|
+
return formatCommandHelp({ command: cmd, flags });
|
|
346
|
+
},
|
|
347
|
+
})
|
|
348
|
+
.option('--config <path>', 'Path to prisma-next.config.ts')
|
|
349
|
+
.option('--name <slug>', 'Name slug for the migration directory', 'migration')
|
|
350
|
+
.option('--from <hash>', 'Explicit starting contract hash (overrides migration chain leaf)')
|
|
351
|
+
.option('--json [format]', 'Output as JSON (object)', false)
|
|
352
|
+
.option('-q, --quiet', 'Quiet mode: errors only')
|
|
353
|
+
.option('-v, --verbose', 'Verbose output: debug info, timings')
|
|
354
|
+
.option('-vv, --trace', 'Trace output: deep internals, stack traces')
|
|
355
|
+
.option('--timestamps', 'Add timestamps to output')
|
|
356
|
+
.option('--color', 'Force color output')
|
|
357
|
+
.option('--no-color', 'Disable color output')
|
|
358
|
+
.action(async (options: MigrationPlanOptions) => {
|
|
359
|
+
const flags = parseGlobalFlags(options);
|
|
360
|
+
const startTime = Date.now();
|
|
361
|
+
|
|
362
|
+
const result = await executeMigrationPlanCommand(options, flags, startTime);
|
|
363
|
+
|
|
364
|
+
const exitCode = handleResult(result, flags, (planResult) => {
|
|
365
|
+
if (flags.json === 'object') {
|
|
366
|
+
console.log(JSON.stringify(planResult, null, 2));
|
|
367
|
+
} else if (!flags.quiet) {
|
|
368
|
+
console.log(formatMigrationPlanOutput(planResult, flags));
|
|
369
|
+
}
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
process.exit(exitCode);
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
return command;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function formatMigrationPlanOutput(result: MigrationPlanResult, flags: GlobalFlags): string {
|
|
379
|
+
const lines: string[] = [];
|
|
380
|
+
const useColor = flags.color !== false;
|
|
381
|
+
|
|
382
|
+
const green_ = useColor ? (s: string) => `\x1b[32m${s}\x1b[0m` : (s: string) => s;
|
|
383
|
+
const yellow_ = useColor ? (s: string) => `\x1b[33m${s}\x1b[0m` : (s: string) => s;
|
|
384
|
+
const dim_ = useColor ? (s: string) => `\x1b[2m${s}\x1b[0m` : (s: string) => s;
|
|
385
|
+
|
|
386
|
+
if (result.noOp) {
|
|
387
|
+
lines.push(`${green_('✔')} No changes detected`);
|
|
388
|
+
lines.push(dim_(` from: ${result.from}`));
|
|
389
|
+
lines.push(dim_(` to: ${result.to}`));
|
|
390
|
+
return lines.join('\n');
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
lines.push(`${green_('✔')} ${result.summary}`);
|
|
394
|
+
lines.push('');
|
|
395
|
+
|
|
396
|
+
if (result.operations.length > 0) {
|
|
397
|
+
lines.push(dim_('│'));
|
|
398
|
+
for (let i = 0; i < result.operations.length; i++) {
|
|
399
|
+
const op = result.operations[i]!;
|
|
400
|
+
const isLast = i === result.operations.length - 1;
|
|
401
|
+
const treeChar = isLast ? '└' : '├';
|
|
402
|
+
const opClassLabel =
|
|
403
|
+
op.operationClass === 'destructive'
|
|
404
|
+
? yellow_(`[${op.operationClass}]`)
|
|
405
|
+
: dim_(`[${op.operationClass}]`);
|
|
406
|
+
lines.push(`${dim_(treeChar)}─ ${op.label} ${opClassLabel}`);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
const hasDestructive = result.operations.some((op) => op.operationClass === 'destructive');
|
|
410
|
+
if (hasDestructive) {
|
|
411
|
+
lines.push('');
|
|
412
|
+
lines.push(
|
|
413
|
+
`${yellow_('⚠')} This migration contains destructive operations that may cause data loss.`,
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
lines.push('');
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
lines.push(dim_(`from: ${result.from}`));
|
|
420
|
+
lines.push(dim_(`to: ${result.to}`));
|
|
421
|
+
if (result.migrationId) {
|
|
422
|
+
lines.push(dim_(`migrationId: ${result.migrationId}`));
|
|
423
|
+
}
|
|
424
|
+
if (result.dir) {
|
|
425
|
+
lines.push(dim_(`dir: ${result.dir}`));
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
if (result.sql && result.sql.length > 0) {
|
|
429
|
+
lines.push('');
|
|
430
|
+
lines.push(dim_('DDL preview'));
|
|
431
|
+
lines.push('');
|
|
432
|
+
for (const statement of result.sql) {
|
|
433
|
+
const trimmed = statement.trim();
|
|
434
|
+
if (!trimmed) continue;
|
|
435
|
+
const line = trimmed.endsWith(';') ? trimmed : `${trimmed};`;
|
|
436
|
+
lines.push(line);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
if (flags.verbose && result.timings) {
|
|
441
|
+
lines.push('');
|
|
442
|
+
lines.push(dim_(`Total time: ${result.timings.total}ms`));
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
return lines.join('\n');
|
|
446
|
+
}
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
import type { MigrationPlanOperation } from '@prisma-next/core-control-plane/types';
|
|
2
|
+
import { findLatestMigration, reconstructGraph } from '@prisma-next/migration-tools/dag';
|
|
3
|
+
import { readMigrationPackage, readMigrationsDir } from '@prisma-next/migration-tools/io';
|
|
4
|
+
import type { MigrationPackage } from '@prisma-next/migration-tools/types';
|
|
5
|
+
import { MigrationToolsError } from '@prisma-next/migration-tools/types';
|
|
6
|
+
import { notOk, ok, type Result } from '@prisma-next/utils/result';
|
|
7
|
+
import { Command } from 'commander';
|
|
8
|
+
import { relative, resolve } from 'pathe';
|
|
9
|
+
import { loadConfig } from '../config-loader';
|
|
10
|
+
import { extractSqlDdl } from '../control-api/operations/extract-sql-ddl';
|
|
11
|
+
import { type CliStructuredError, errorRuntime, errorUnexpected } from '../utils/cli-errors';
|
|
12
|
+
import { setCommandDescriptions } from '../utils/command-helpers';
|
|
13
|
+
import { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';
|
|
14
|
+
import { formatCommandHelp, formatMigrationShowOutput, formatStyledHeader } from '../utils/output';
|
|
15
|
+
import { handleResult } from '../utils/result-handler';
|
|
16
|
+
|
|
17
|
+
interface MigrationShowOptions {
|
|
18
|
+
readonly config?: string;
|
|
19
|
+
readonly json?: string | boolean;
|
|
20
|
+
readonly quiet?: boolean;
|
|
21
|
+
readonly q?: boolean;
|
|
22
|
+
readonly verbose?: boolean;
|
|
23
|
+
readonly v?: boolean;
|
|
24
|
+
readonly vv?: boolean;
|
|
25
|
+
readonly trace?: boolean;
|
|
26
|
+
readonly timestamps?: boolean;
|
|
27
|
+
readonly color?: boolean;
|
|
28
|
+
readonly 'no-color'?: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface MigrationShowResult {
|
|
32
|
+
readonly ok: true;
|
|
33
|
+
readonly dirName: string;
|
|
34
|
+
readonly dirPath: string;
|
|
35
|
+
readonly from: string;
|
|
36
|
+
readonly to: string;
|
|
37
|
+
readonly migrationId: string | null;
|
|
38
|
+
readonly kind: string;
|
|
39
|
+
readonly createdAt: string;
|
|
40
|
+
readonly operations: readonly {
|
|
41
|
+
readonly id: string;
|
|
42
|
+
readonly label: string;
|
|
43
|
+
readonly operationClass: string;
|
|
44
|
+
}[];
|
|
45
|
+
readonly sql: readonly string[];
|
|
46
|
+
readonly summary: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function looksLikePath(target: string): boolean {
|
|
50
|
+
return target.includes('/') || target.includes('\\');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function resolveByHashPrefix(
|
|
54
|
+
packages: readonly MigrationPackage[],
|
|
55
|
+
prefix: string,
|
|
56
|
+
): Result<MigrationPackage, CliStructuredError> {
|
|
57
|
+
const normalizedPrefix = prefix.startsWith('sha256:') ? prefix : `sha256:${prefix}`;
|
|
58
|
+
const attested = packages.filter((p) => typeof p.manifest.migrationId === 'string');
|
|
59
|
+
const matches = attested.filter((p) => p.manifest.migrationId!.startsWith(normalizedPrefix));
|
|
60
|
+
|
|
61
|
+
if (matches.length === 1) {
|
|
62
|
+
return ok(matches[0]!);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (matches.length === 0) {
|
|
66
|
+
return notOk(
|
|
67
|
+
errorRuntime('No migration found matching prefix', {
|
|
68
|
+
why: `No attested migration has a migrationId starting with "${normalizedPrefix}"`,
|
|
69
|
+
fix: 'Run `prisma-next migration show` (no argument) to see the latest migration, or check the migrations directory for available packages.',
|
|
70
|
+
}),
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const candidates = matches.map((p) => ` ${p.dirName} ${p.manifest.migrationId}`).join('\n');
|
|
75
|
+
return notOk(
|
|
76
|
+
errorRuntime('Ambiguous hash prefix', {
|
|
77
|
+
why: `Multiple migrations match prefix "${normalizedPrefix}":\n${candidates}`,
|
|
78
|
+
fix: 'Provide a longer prefix to uniquely identify the migration.',
|
|
79
|
+
}),
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function executeMigrationShowCommand(
|
|
84
|
+
target: string | undefined,
|
|
85
|
+
options: MigrationShowOptions,
|
|
86
|
+
flags: GlobalFlags,
|
|
87
|
+
): Promise<Result<MigrationShowResult, CliStructuredError>> {
|
|
88
|
+
const config = await loadConfig(options.config);
|
|
89
|
+
const configPath = options.config
|
|
90
|
+
? relative(process.cwd(), resolve(options.config))
|
|
91
|
+
: 'prisma-next.config.ts';
|
|
92
|
+
|
|
93
|
+
const migrationsDir = resolve(
|
|
94
|
+
options.config ? resolve(options.config, '..') : process.cwd(),
|
|
95
|
+
config.migrations?.dir ?? 'migrations',
|
|
96
|
+
);
|
|
97
|
+
const migrationsRelative = relative(process.cwd(), migrationsDir);
|
|
98
|
+
|
|
99
|
+
if (flags.json !== 'object' && !flags.quiet) {
|
|
100
|
+
const details: Array<{ label: string; value: string }> = [
|
|
101
|
+
{ label: 'config', value: configPath },
|
|
102
|
+
{ label: 'migrations', value: migrationsRelative },
|
|
103
|
+
];
|
|
104
|
+
if (target) {
|
|
105
|
+
details.push({ label: 'target', value: target });
|
|
106
|
+
}
|
|
107
|
+
const header = formatStyledHeader({
|
|
108
|
+
command: 'migration show',
|
|
109
|
+
description: 'Display migration package contents',
|
|
110
|
+
details,
|
|
111
|
+
flags,
|
|
112
|
+
});
|
|
113
|
+
console.log(header);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
let pkg: MigrationPackage;
|
|
117
|
+
|
|
118
|
+
try {
|
|
119
|
+
if (target && looksLikePath(target)) {
|
|
120
|
+
pkg = await readMigrationPackage(resolve(target));
|
|
121
|
+
} else {
|
|
122
|
+
const allPackages = await readMigrationsDir(migrationsDir);
|
|
123
|
+
if (allPackages.length === 0) {
|
|
124
|
+
return notOk(
|
|
125
|
+
errorRuntime('No migrations found', {
|
|
126
|
+
why: `No migration packages found in ${migrationsRelative}`,
|
|
127
|
+
fix: 'Run `prisma-next migration plan` to create a migration first.',
|
|
128
|
+
}),
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (target) {
|
|
133
|
+
const resolved = resolveByHashPrefix(allPackages, target);
|
|
134
|
+
if (!resolved.ok) return resolved;
|
|
135
|
+
pkg = resolved.value;
|
|
136
|
+
} else {
|
|
137
|
+
const attested = allPackages.filter((p) => typeof p.manifest.migrationId === 'string');
|
|
138
|
+
if (attested.length === 0) {
|
|
139
|
+
return notOk(
|
|
140
|
+
errorRuntime('No attested migrations found', {
|
|
141
|
+
why: `All migrations in ${migrationsRelative} are drafts (migrationId: null)`,
|
|
142
|
+
fix: 'Run `prisma-next migration verify --dir <path>` to attest a draft migration.',
|
|
143
|
+
}),
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
const graph = reconstructGraph(attested);
|
|
147
|
+
const latestMigration = findLatestMigration(graph);
|
|
148
|
+
if (!latestMigration) {
|
|
149
|
+
return notOk(
|
|
150
|
+
errorRuntime('Could not resolve latest migration', {
|
|
151
|
+
why: 'No latest migration found in the migration chain',
|
|
152
|
+
fix: 'The migrations directory may be corrupted. Inspect the migration.json files.',
|
|
153
|
+
}),
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
const leafPkg = attested.find(
|
|
157
|
+
(p) => p.manifest.migrationId === latestMigration.migrationId,
|
|
158
|
+
);
|
|
159
|
+
if (!leafPkg) {
|
|
160
|
+
return notOk(
|
|
161
|
+
errorRuntime('Could not resolve latest migration', {
|
|
162
|
+
why: `Latest migration ${latestMigration.dirName} does not match any package`,
|
|
163
|
+
fix: 'The migrations directory may be corrupted. Inspect the migration.json files.',
|
|
164
|
+
}),
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
pkg = leafPkg;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
} catch (error) {
|
|
171
|
+
if (MigrationToolsError.is(error)) {
|
|
172
|
+
return notOk(
|
|
173
|
+
errorRuntime(error.message, {
|
|
174
|
+
why: error.why,
|
|
175
|
+
fix: error.fix,
|
|
176
|
+
meta: { code: error.code, ...(error.details ?? {}) },
|
|
177
|
+
}),
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
return notOk(
|
|
181
|
+
errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
182
|
+
why: `Failed to read migration: ${error instanceof Error ? error.message : String(error)}`,
|
|
183
|
+
}),
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const ops = pkg.ops as readonly MigrationPlanOperation[];
|
|
188
|
+
const sql = extractSqlDdl(ops);
|
|
189
|
+
|
|
190
|
+
const result: MigrationShowResult = {
|
|
191
|
+
ok: true,
|
|
192
|
+
dirName: pkg.dirName,
|
|
193
|
+
dirPath: relative(process.cwd(), pkg.dirPath),
|
|
194
|
+
from: pkg.manifest.from,
|
|
195
|
+
to: pkg.manifest.to,
|
|
196
|
+
migrationId: pkg.manifest.migrationId,
|
|
197
|
+
kind: pkg.manifest.kind,
|
|
198
|
+
createdAt: pkg.manifest.createdAt,
|
|
199
|
+
operations: ops.map((op) => ({
|
|
200
|
+
id: op.id,
|
|
201
|
+
label: op.label,
|
|
202
|
+
operationClass: op.operationClass,
|
|
203
|
+
})),
|
|
204
|
+
sql,
|
|
205
|
+
summary: `${ops.length} operation(s)`,
|
|
206
|
+
};
|
|
207
|
+
return ok(result);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export function createMigrationShowCommand(): Command {
|
|
211
|
+
const command = new Command('show');
|
|
212
|
+
setCommandDescriptions(
|
|
213
|
+
command,
|
|
214
|
+
'Display migration package contents',
|
|
215
|
+
'Shows the operations, DDL preview, and metadata for a migration package.\n' +
|
|
216
|
+
'Accepts a directory path, a hash prefix (git-style), or defaults to the\n' +
|
|
217
|
+
'latest migration.',
|
|
218
|
+
);
|
|
219
|
+
command
|
|
220
|
+
.configureHelp({
|
|
221
|
+
formatHelp: (cmd) => {
|
|
222
|
+
const defaultFlags = parseGlobalFlags({});
|
|
223
|
+
return formatCommandHelp({ command: cmd, flags: defaultFlags });
|
|
224
|
+
},
|
|
225
|
+
})
|
|
226
|
+
.argument(
|
|
227
|
+
'[target]',
|
|
228
|
+
'Migration directory path or migrationId hash prefix (defaults to latest)',
|
|
229
|
+
)
|
|
230
|
+
.option('--config <path>', 'Path to prisma-next.config.ts')
|
|
231
|
+
.option('--json [format]', 'Output as JSON (object)', false)
|
|
232
|
+
.option('-q, --quiet', 'Quiet mode: errors only')
|
|
233
|
+
.option('-v, --verbose', 'Verbose output')
|
|
234
|
+
.option('-vv, --trace', 'Trace output')
|
|
235
|
+
.option('--timestamps', 'Add timestamps to output')
|
|
236
|
+
.option('--color', 'Force color output')
|
|
237
|
+
.option('--no-color', 'Disable color output')
|
|
238
|
+
.action(async (target: string | undefined, options: MigrationShowOptions) => {
|
|
239
|
+
const flags = parseGlobalFlags(options);
|
|
240
|
+
|
|
241
|
+
const result = await executeMigrationShowCommand(target, options, flags);
|
|
242
|
+
|
|
243
|
+
const exitCode = handleResult(result, flags, (showResult) => {
|
|
244
|
+
if (flags.json === 'object') {
|
|
245
|
+
console.log(JSON.stringify(showResult, null, 2));
|
|
246
|
+
} else if (!flags.quiet) {
|
|
247
|
+
console.log(formatMigrationShowOutput(showResult, flags));
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
process.exit(exitCode);
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
return command;
|
|
255
|
+
}
|