@prisma-next/cli 0.3.0-dev.7 → 0.3.0-dev.70
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 +203 -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 +151 -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 +134 -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 +118 -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 +120 -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 +142 -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 +123 -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 +133 -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 +250 -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 +260 -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 +98 -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 +135 -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 +74 -37
- 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
package/src/commands/db-init.ts
CHANGED
|
@@ -1,456 +1,247 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import type {
|
|
4
|
-
MigrationPlan,
|
|
5
|
-
MigrationPlannerResult,
|
|
6
|
-
MigrationPlanOperation,
|
|
7
|
-
MigrationRunnerResult,
|
|
8
|
-
} from '@prisma-next/core-control-plane/types';
|
|
9
|
-
import { redactDatabaseUrl } from '@prisma-next/utils/redact-db-url';
|
|
1
|
+
import { ifDefined } from '@prisma-next/utils/defined';
|
|
2
|
+
import { notOk, ok, type Result } from '@prisma-next/utils/result';
|
|
10
3
|
import { Command } from 'commander';
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
4
|
+
import { ContractValidationError } from '../control-api/errors';
|
|
5
|
+
import type { DbInitFailure } from '../control-api/types';
|
|
13
6
|
import {
|
|
7
|
+
CliStructuredError,
|
|
14
8
|
errorContractValidationFailed,
|
|
15
|
-
errorDatabaseUrlRequired,
|
|
16
|
-
errorDriverRequired,
|
|
17
|
-
errorFileNotFound,
|
|
18
9
|
errorJsonFormatNotSupported,
|
|
19
10
|
errorMigrationPlanningFailed,
|
|
11
|
+
errorRunnerFailed,
|
|
20
12
|
errorRuntime,
|
|
21
|
-
errorTargetMigrationNotSupported,
|
|
22
13
|
errorUnexpected,
|
|
23
14
|
} from '../utils/cli-errors';
|
|
24
|
-
import {
|
|
15
|
+
import type { MigrationCommandOptions } from '../utils/command-helpers';
|
|
16
|
+
import { sanitizeErrorMessage, setCommandDescriptions } from '../utils/command-helpers';
|
|
17
|
+
import { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';
|
|
25
18
|
import {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
} from '../utils/
|
|
29
|
-
import { parseGlobalFlags } from '../utils/global-flags';
|
|
19
|
+
addMigrationCommandOptions,
|
|
20
|
+
prepareMigrationContext,
|
|
21
|
+
} from '../utils/migration-command-scaffold';
|
|
30
22
|
import {
|
|
31
|
-
type DbInitResult,
|
|
32
23
|
formatCommandHelp,
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
24
|
+
formatMigrationApplyOutput,
|
|
25
|
+
formatMigrationJson,
|
|
26
|
+
formatMigrationPlanOutput,
|
|
27
|
+
type MigrationCommandResult,
|
|
37
28
|
} from '../utils/output';
|
|
38
29
|
import { handleResult } from '../utils/result-handler';
|
|
39
|
-
import { withSpinner } from '../utils/spinner';
|
|
40
30
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
31
|
+
type DbInitOptions = MigrationCommandOptions;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Maps a DbInitFailure to a CliStructuredError for consistent error handling.
|
|
35
|
+
*/
|
|
36
|
+
function mapDbInitFailure(failure: DbInitFailure): CliStructuredError {
|
|
37
|
+
if (failure.code === 'PLANNING_FAILED') {
|
|
38
|
+
return errorMigrationPlanningFailed({ conflicts: failure.conflicts ?? [] });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (failure.code === 'MARKER_ORIGIN_MISMATCH') {
|
|
42
|
+
const mismatchParts: string[] = [];
|
|
43
|
+
if (
|
|
44
|
+
failure.marker?.storageHash !== failure.destination?.storageHash &&
|
|
45
|
+
failure.marker?.storageHash &&
|
|
46
|
+
failure.destination?.storageHash
|
|
47
|
+
) {
|
|
48
|
+
mismatchParts.push(
|
|
49
|
+
`storageHash (marker: ${failure.marker.storageHash}, destination: ${failure.destination.storageHash})`,
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
if (
|
|
53
|
+
failure.marker?.profileHash !== failure.destination?.profileHash &&
|
|
54
|
+
failure.marker?.profileHash &&
|
|
55
|
+
failure.destination?.profileHash
|
|
56
|
+
) {
|
|
57
|
+
mismatchParts.push(
|
|
58
|
+
`profileHash (marker: ${failure.marker.profileHash}, destination: ${failure.destination.profileHash})`,
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return errorRuntime(
|
|
63
|
+
`Existing database signature does not match plan destination.${mismatchParts.length > 0 ? ` Mismatch in ${mismatchParts.join(' and ')}.` : ''}`,
|
|
64
|
+
{
|
|
65
|
+
why: 'Database has an existing signature (marker) that does not match the target contract',
|
|
66
|
+
fix: 'If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow',
|
|
67
|
+
meta: {
|
|
68
|
+
code: 'MARKER_ORIGIN_MISMATCH',
|
|
69
|
+
...ifDefined('markerStorageHash', failure.marker?.storageHash),
|
|
70
|
+
...ifDefined('destinationStorageHash', failure.destination?.storageHash),
|
|
71
|
+
...ifDefined('markerProfileHash', failure.marker?.profileHash),
|
|
72
|
+
...ifDefined('destinationProfileHash', failure.destination?.profileHash),
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (failure.code === 'RUNNER_FAILED') {
|
|
79
|
+
return errorRunnerFailed(failure.summary, {
|
|
80
|
+
why: failure.why ?? 'Migration runner failed',
|
|
81
|
+
fix: 'Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`',
|
|
82
|
+
...(failure.meta
|
|
83
|
+
? { meta: { code: 'RUNNER_FAILED', ...failure.meta } }
|
|
84
|
+
: { meta: { code: 'RUNNER_FAILED' } }),
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Exhaustive check - TypeScript will error if a new code is added but not handled
|
|
89
|
+
const exhaustive: never = failure.code;
|
|
90
|
+
throw new Error(`Unhandled DbInitFailure code: ${exhaustive}`);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Executes the db init command and returns a structured Result.
|
|
95
|
+
*/
|
|
96
|
+
async function executeDbInitCommand(
|
|
97
|
+
options: DbInitOptions,
|
|
98
|
+
flags: GlobalFlags,
|
|
99
|
+
startTime: number,
|
|
100
|
+
): Promise<Result<MigrationCommandResult, CliStructuredError>> {
|
|
101
|
+
// Prepare shared migration context (config, contract, connection, client)
|
|
102
|
+
const ctxResult = await prepareMigrationContext(options, flags, {
|
|
103
|
+
commandName: 'db init',
|
|
104
|
+
description: 'Bootstrap a database to match the current contract',
|
|
105
|
+
url: 'https://pris.ly/db-init',
|
|
106
|
+
});
|
|
107
|
+
if (!ctxResult.ok) {
|
|
108
|
+
return ctxResult;
|
|
109
|
+
}
|
|
110
|
+
const { client, contractJson, dbConnection, onProgress, contractPathAbsolute } = ctxResult.value;
|
|
111
|
+
|
|
112
|
+
try {
|
|
113
|
+
// Call dbInit with connection and progress callback
|
|
114
|
+
const result = await client.dbInit({
|
|
115
|
+
contractIR: contractJson,
|
|
116
|
+
mode: options.plan ? 'plan' : 'apply',
|
|
117
|
+
connection: dbConnection,
|
|
118
|
+
onProgress,
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
// Handle failures by mapping to CLI structured error
|
|
122
|
+
if (!result.ok) {
|
|
123
|
+
return notOk(mapDbInitFailure(result.failure));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Convert success result to CLI output format
|
|
127
|
+
const dbInitResult: MigrationCommandResult = {
|
|
128
|
+
ok: true,
|
|
129
|
+
mode: result.value.mode,
|
|
130
|
+
plan: {
|
|
131
|
+
targetId: ctxResult.value.config.target.targetId,
|
|
132
|
+
destination: {
|
|
133
|
+
storageHash: result.value.destination.storageHash,
|
|
134
|
+
...ifDefined('profileHash', result.value.destination.profileHash),
|
|
135
|
+
},
|
|
136
|
+
operations: result.value.plan.operations.map((op) => ({
|
|
137
|
+
id: op.id,
|
|
138
|
+
label: op.label,
|
|
139
|
+
operationClass: op.operationClass,
|
|
140
|
+
})),
|
|
141
|
+
},
|
|
142
|
+
...(result.value.execution
|
|
143
|
+
? {
|
|
144
|
+
execution: {
|
|
145
|
+
operationsPlanned: result.value.execution.operationsPlanned,
|
|
146
|
+
operationsExecuted: result.value.execution.operationsExecuted,
|
|
147
|
+
},
|
|
148
|
+
}
|
|
149
|
+
: {}),
|
|
150
|
+
...(result.value.marker
|
|
151
|
+
? {
|
|
152
|
+
marker: {
|
|
153
|
+
storageHash: result.value.marker.storageHash,
|
|
154
|
+
...ifDefined('profileHash', result.value.marker.profileHash),
|
|
155
|
+
},
|
|
156
|
+
}
|
|
157
|
+
: {}),
|
|
158
|
+
summary: result.value.summary,
|
|
159
|
+
timings: { total: Date.now() - startTime },
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
return ok(dbInitResult);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
// Driver already throws CliStructuredError for connection failures
|
|
165
|
+
if (CliStructuredError.is(error)) {
|
|
166
|
+
return notOk(error);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (error instanceof ContractValidationError) {
|
|
170
|
+
return notOk(
|
|
171
|
+
errorContractValidationFailed(`Contract validation failed: ${error.message}`, {
|
|
172
|
+
where: { path: contractPathAbsolute },
|
|
173
|
+
}),
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const rawMessage = error instanceof Error ? error.message : String(error);
|
|
178
|
+
const safeMessage = sanitizeErrorMessage(
|
|
179
|
+
rawMessage,
|
|
180
|
+
typeof dbConnection === 'string' ? dbConnection : undefined,
|
|
181
|
+
);
|
|
182
|
+
return notOk(
|
|
183
|
+
errorUnexpected(safeMessage, {
|
|
184
|
+
why: `Unexpected error during db init: ${safeMessage}`,
|
|
185
|
+
}),
|
|
186
|
+
);
|
|
187
|
+
} finally {
|
|
188
|
+
await client.close();
|
|
189
|
+
}
|
|
55
190
|
}
|
|
56
191
|
|
|
57
192
|
export function createDbInitCommand(): Command {
|
|
58
193
|
const command = new Command('init');
|
|
59
194
|
setCommandDescriptions(
|
|
60
195
|
command,
|
|
61
|
-
'Bootstrap a database to match the current contract and
|
|
196
|
+
'Bootstrap a database to match the current contract and sign it',
|
|
62
197
|
'Initializes a database to match your emitted contract using additive-only operations.\n' +
|
|
63
198
|
'Creates any missing tables, columns, indexes, and constraints defined in your contract.\n' +
|
|
64
199
|
'Leaves existing compatible structures in place, surfaces conflicts when destructive changes\n' +
|
|
65
|
-
'would be required, and
|
|
200
|
+
'would be required, and signs the database to track contract state. Use --plan to\n' +
|
|
66
201
|
'preview changes without applying.',
|
|
67
202
|
);
|
|
68
|
-
command
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
.
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
const result = await performAction(async () => {
|
|
90
|
-
if (flags.json === 'ndjson') {
|
|
91
|
-
throw errorJsonFormatNotSupported({
|
|
92
|
-
command: 'db init',
|
|
93
|
-
format: 'ndjson',
|
|
94
|
-
supportedFormats: ['object'],
|
|
95
|
-
});
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
// Load config
|
|
99
|
-
const config = await loadConfig(options.config);
|
|
100
|
-
const configPath = options.config
|
|
101
|
-
? relative(process.cwd(), resolve(options.config))
|
|
102
|
-
: 'prisma-next.config.ts';
|
|
103
|
-
const contractPathAbsolute = config.contract?.output
|
|
104
|
-
? resolve(config.contract.output)
|
|
105
|
-
: resolve('src/prisma/contract.json');
|
|
106
|
-
const contractPath = relative(process.cwd(), contractPathAbsolute);
|
|
107
|
-
|
|
108
|
-
// Output header
|
|
109
|
-
if (flags.json !== 'object' && !flags.quiet) {
|
|
110
|
-
const details: Array<{ label: string; value: string }> = [
|
|
111
|
-
{ label: 'config', value: configPath },
|
|
112
|
-
{ label: 'contract', value: contractPath },
|
|
113
|
-
];
|
|
114
|
-
if (options.db) {
|
|
115
|
-
details.push({ label: 'database', value: options.db });
|
|
116
|
-
}
|
|
117
|
-
if (options.plan) {
|
|
118
|
-
details.push({ label: 'mode', value: 'plan (dry run)' });
|
|
119
|
-
}
|
|
120
|
-
const header = formatStyledHeader({
|
|
121
|
-
command: 'db init',
|
|
122
|
-
description: 'Bootstrap a database to match the current contract',
|
|
123
|
-
url: 'https://pris.ly/db-init',
|
|
124
|
-
details,
|
|
125
|
-
flags,
|
|
126
|
-
});
|
|
127
|
-
console.log(header);
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
// Load contract file
|
|
131
|
-
let contractJsonContent: string;
|
|
132
|
-
try {
|
|
133
|
-
contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
|
|
134
|
-
} catch (error) {
|
|
135
|
-
if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
|
|
136
|
-
throw errorFileNotFound(contractPathAbsolute, {
|
|
137
|
-
why: `Contract file not found at ${contractPathAbsolute}`,
|
|
138
|
-
fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`,
|
|
139
|
-
});
|
|
140
|
-
}
|
|
141
|
-
throw 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
|
-
let contractJson: Record<string, unknown>;
|
|
147
|
-
try {
|
|
148
|
-
contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
|
|
149
|
-
} catch (error) {
|
|
150
|
-
throw errorContractValidationFailed(
|
|
151
|
-
`Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
|
|
152
|
-
{ where: { path: contractPathAbsolute } },
|
|
153
|
-
);
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
// Resolve database URL
|
|
157
|
-
const dbUrl = options.db ?? config.db?.url;
|
|
158
|
-
if (!dbUrl) {
|
|
159
|
-
throw errorDatabaseUrlRequired({
|
|
160
|
-
why: `Database URL is required for db init (set db.url in ${configPath}, or pass --db <url>)`,
|
|
161
|
-
});
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
// Check for driver
|
|
165
|
-
if (!config.driver) {
|
|
166
|
-
throw errorDriverRequired({ why: 'Config.driver is required for db init' });
|
|
167
|
-
}
|
|
168
|
-
const driverDescriptor = config.driver;
|
|
169
|
-
|
|
170
|
-
// Check target supports migrations via the migrations capability
|
|
171
|
-
if (!config.target.migrations) {
|
|
172
|
-
throw errorTargetMigrationNotSupported({
|
|
173
|
-
why: `Target "${config.target.id}" does not support migrations`,
|
|
174
|
-
});
|
|
175
|
-
}
|
|
176
|
-
const migrations = config.target.migrations;
|
|
177
|
-
|
|
178
|
-
// Create driver
|
|
179
|
-
let driver: Awaited<ReturnType<(typeof driverDescriptor)['create']>>;
|
|
180
|
-
try {
|
|
181
|
-
driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
|
|
182
|
-
message: 'Connecting to database...',
|
|
183
|
-
flags,
|
|
184
|
-
});
|
|
185
|
-
} catch (error) {
|
|
186
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
187
|
-
const code = (error as { code?: unknown }).code;
|
|
188
|
-
const redacted = redactDatabaseUrl(dbUrl);
|
|
189
|
-
throw errorRuntime('Database connection failed', {
|
|
190
|
-
why: message,
|
|
191
|
-
fix: 'Verify the database URL, ensure the database is reachable, and confirm credentials/permissions',
|
|
192
|
-
meta: {
|
|
193
|
-
...(typeof code !== 'undefined' ? { code } : {}),
|
|
194
|
-
...redacted,
|
|
195
|
-
},
|
|
196
|
-
});
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
try {
|
|
200
|
-
// Create family instance
|
|
201
|
-
const familyInstance = config.family.create({
|
|
202
|
-
target: config.target,
|
|
203
|
-
adapter: config.adapter,
|
|
204
|
-
driver: driverDescriptor,
|
|
205
|
-
extensionPacks: config.extensionPacks ?? [],
|
|
206
|
-
});
|
|
207
|
-
const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];
|
|
208
|
-
const frameworkComponents = assertFrameworkComponentsCompatible(
|
|
209
|
-
config.family.familyId,
|
|
210
|
-
config.target.targetId,
|
|
211
|
-
rawComponents,
|
|
212
|
-
);
|
|
213
|
-
|
|
214
|
-
// Validate contract
|
|
215
|
-
const contractIR = familyInstance.validateContractIR(contractJson);
|
|
216
|
-
assertContractRequirementsSatisfied({
|
|
217
|
-
contract: contractIR,
|
|
218
|
-
family: config.family,
|
|
219
|
-
target: config.target,
|
|
220
|
-
adapter: config.adapter,
|
|
221
|
-
extensionPacks: config.extensionPacks,
|
|
222
|
-
});
|
|
223
|
-
|
|
224
|
-
// Create planner and runner from target migrations capability
|
|
225
|
-
const planner = migrations.createPlanner(familyInstance);
|
|
226
|
-
const runner = migrations.createRunner(familyInstance);
|
|
227
|
-
|
|
228
|
-
// Introspect live schema
|
|
229
|
-
const schemaIR = await withSpinner(() => familyInstance.introspect({ driver }), {
|
|
230
|
-
message: 'Introspecting database schema...',
|
|
231
|
-
flags,
|
|
232
|
-
});
|
|
233
|
-
|
|
234
|
-
// Policy for init mode (additive only)
|
|
235
|
-
const policy = { allowedOperationClasses: ['additive'] as const };
|
|
236
|
-
|
|
237
|
-
// Plan migration
|
|
238
|
-
const plannerResult: MigrationPlannerResult = await withSpinner(
|
|
239
|
-
async () =>
|
|
240
|
-
planner.plan({
|
|
241
|
-
contract: contractIR,
|
|
242
|
-
schema: schemaIR,
|
|
243
|
-
policy,
|
|
244
|
-
frameworkComponents,
|
|
245
|
-
}),
|
|
246
|
-
{
|
|
247
|
-
message: 'Planning migration...',
|
|
248
|
-
flags,
|
|
249
|
-
},
|
|
250
|
-
);
|
|
251
|
-
|
|
252
|
-
if (plannerResult.kind === 'failure') {
|
|
253
|
-
throw errorMigrationPlanningFailed({ conflicts: plannerResult.conflicts });
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
const migrationPlan: MigrationPlan = plannerResult.plan;
|
|
257
|
-
|
|
258
|
-
// Check for existing marker - handle idempotency and mismatch errors
|
|
259
|
-
const existingMarker = await familyInstance.readMarker({ driver });
|
|
260
|
-
if (existingMarker) {
|
|
261
|
-
const markerMatchesDestination =
|
|
262
|
-
existingMarker.coreHash === migrationPlan.destination.coreHash &&
|
|
263
|
-
(!migrationPlan.destination.profileHash ||
|
|
264
|
-
existingMarker.profileHash === migrationPlan.destination.profileHash);
|
|
265
|
-
|
|
266
|
-
if (markerMatchesDestination) {
|
|
267
|
-
// Already at destination - return success with no operations
|
|
268
|
-
const dbInitResult: DbInitResult = {
|
|
269
|
-
ok: true,
|
|
270
|
-
mode: options.plan ? 'plan' : 'apply',
|
|
271
|
-
plan: {
|
|
272
|
-
targetId: migrationPlan.targetId,
|
|
273
|
-
destination: migrationPlan.destination,
|
|
274
|
-
operations: [],
|
|
275
|
-
},
|
|
276
|
-
...(options.plan
|
|
277
|
-
? {}
|
|
278
|
-
: {
|
|
279
|
-
execution: { operationsPlanned: 0, operationsExecuted: 0 },
|
|
280
|
-
marker: {
|
|
281
|
-
coreHash: existingMarker.coreHash,
|
|
282
|
-
profileHash: existingMarker.profileHash,
|
|
283
|
-
},
|
|
284
|
-
}),
|
|
285
|
-
summary: 'Database already at target contract state',
|
|
286
|
-
timings: { total: Date.now() - startTime },
|
|
287
|
-
};
|
|
288
|
-
return dbInitResult;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
// Marker exists but doesn't match destination - fail
|
|
292
|
-
const coreHashMismatch = existingMarker.coreHash !== migrationPlan.destination.coreHash;
|
|
293
|
-
const profileHashMismatch =
|
|
294
|
-
migrationPlan.destination.profileHash &&
|
|
295
|
-
existingMarker.profileHash !== migrationPlan.destination.profileHash;
|
|
296
|
-
|
|
297
|
-
const mismatchParts: string[] = [];
|
|
298
|
-
if (coreHashMismatch) {
|
|
299
|
-
mismatchParts.push(
|
|
300
|
-
`coreHash (marker: ${existingMarker.coreHash}, destination: ${migrationPlan.destination.coreHash})`,
|
|
301
|
-
);
|
|
302
|
-
}
|
|
303
|
-
if (profileHashMismatch) {
|
|
304
|
-
mismatchParts.push(
|
|
305
|
-
`profileHash (marker: ${existingMarker.profileHash}, destination: ${migrationPlan.destination.profileHash})`,
|
|
306
|
-
);
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
throw errorRuntime(
|
|
310
|
-
`Existing contract marker does not match plan destination. Mismatch in ${mismatchParts.join(' and ')}.`,
|
|
311
|
-
{
|
|
312
|
-
why: 'Database has an existing contract marker that does not match the target contract',
|
|
313
|
-
fix: 'If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow',
|
|
314
|
-
meta: {
|
|
315
|
-
code: 'MARKER_ORIGIN_MISMATCH',
|
|
316
|
-
markerCoreHash: existingMarker.coreHash,
|
|
317
|
-
destinationCoreHash: migrationPlan.destination.coreHash,
|
|
318
|
-
...(existingMarker.profileHash
|
|
319
|
-
? { markerProfileHash: existingMarker.profileHash }
|
|
320
|
-
: {}),
|
|
321
|
-
...(migrationPlan.destination.profileHash
|
|
322
|
-
? { destinationProfileHash: migrationPlan.destination.profileHash }
|
|
323
|
-
: {}),
|
|
324
|
-
},
|
|
325
|
-
},
|
|
326
|
-
);
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
// Plan mode - don't execute
|
|
330
|
-
if (options.plan) {
|
|
331
|
-
const dbInitResult: DbInitResult = {
|
|
332
|
-
ok: true,
|
|
333
|
-
mode: 'plan',
|
|
334
|
-
plan: {
|
|
335
|
-
targetId: migrationPlan.targetId,
|
|
336
|
-
destination: migrationPlan.destination,
|
|
337
|
-
operations: migrationPlan.operations.map((op) => ({
|
|
338
|
-
id: op.id,
|
|
339
|
-
label: op.label,
|
|
340
|
-
operationClass: op.operationClass,
|
|
341
|
-
})),
|
|
342
|
-
},
|
|
343
|
-
summary: `Planned ${migrationPlan.operations.length} operation(s)`,
|
|
344
|
-
timings: { total: Date.now() - startTime },
|
|
345
|
-
};
|
|
346
|
-
return dbInitResult;
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
// Apply mode - execute runner
|
|
350
|
-
// Log main message once, then show individual operations via callbacks
|
|
351
|
-
if (!flags.quiet && flags.json !== 'object') {
|
|
352
|
-
console.log('Applying migration plan and verifying schema...');
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
const callbacks = {
|
|
356
|
-
onOperationStart: (op: MigrationPlanOperation) => {
|
|
357
|
-
if (!flags.quiet && flags.json !== 'object') {
|
|
358
|
-
console.log(` → ${op.label}...`);
|
|
359
|
-
}
|
|
360
|
-
},
|
|
361
|
-
onOperationComplete: (_op: MigrationPlanOperation) => {
|
|
362
|
-
// Could log completion if needed
|
|
363
|
-
},
|
|
364
|
-
};
|
|
365
|
-
|
|
366
|
-
const runnerResult: MigrationRunnerResult = await runner.execute({
|
|
367
|
-
plan: migrationPlan,
|
|
368
|
-
driver,
|
|
369
|
-
destinationContract: contractIR,
|
|
370
|
-
policy,
|
|
371
|
-
callbacks,
|
|
372
|
-
// db init plans and applies back-to-back from a fresh introspection, so per-operation
|
|
373
|
-
// pre/postchecks and the idempotency probe are usually redundant overhead. We still
|
|
374
|
-
// enforce marker/origin compatibility and a full schema verification after apply.
|
|
375
|
-
executionChecks: {
|
|
376
|
-
prechecks: false,
|
|
377
|
-
postchecks: false,
|
|
378
|
-
idempotencyChecks: false,
|
|
379
|
-
},
|
|
380
|
-
frameworkComponents,
|
|
381
|
-
});
|
|
382
|
-
|
|
383
|
-
if (!runnerResult.ok) {
|
|
384
|
-
const meta: Record<string, unknown> = {
|
|
385
|
-
code: runnerResult.failure.code,
|
|
386
|
-
...(runnerResult.failure.meta ?? {}),
|
|
387
|
-
};
|
|
388
|
-
const sqlState = typeof meta['sqlState'] === 'string' ? meta['sqlState'] : undefined;
|
|
389
|
-
const fix =
|
|
390
|
-
sqlState === '42501'
|
|
391
|
-
? 'Grant the database user sufficient privileges (insufficient_privilege), or run db init as a more privileged role'
|
|
392
|
-
: runnerResult.failure.code === 'SCHEMA_VERIFY_FAILED'
|
|
393
|
-
? 'Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`'
|
|
394
|
-
: undefined;
|
|
395
|
-
|
|
396
|
-
throw errorRuntime(runnerResult.failure.summary, {
|
|
397
|
-
why:
|
|
398
|
-
runnerResult.failure.why ?? `Migration runner failed: ${runnerResult.failure.code}`,
|
|
399
|
-
...(fix ? { fix } : {}),
|
|
400
|
-
meta,
|
|
401
|
-
});
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
const execution = runnerResult.value;
|
|
405
|
-
|
|
406
|
-
const dbInitResult: DbInitResult = {
|
|
407
|
-
ok: true,
|
|
408
|
-
mode: 'apply',
|
|
409
|
-
plan: {
|
|
410
|
-
targetId: migrationPlan.targetId,
|
|
411
|
-
destination: migrationPlan.destination,
|
|
412
|
-
operations: migrationPlan.operations.map((op) => ({
|
|
413
|
-
id: op.id,
|
|
414
|
-
label: op.label,
|
|
415
|
-
operationClass: op.operationClass,
|
|
416
|
-
})),
|
|
417
|
-
},
|
|
418
|
-
execution: {
|
|
419
|
-
operationsPlanned: execution.operationsPlanned,
|
|
420
|
-
operationsExecuted: execution.operationsExecuted,
|
|
421
|
-
},
|
|
422
|
-
marker: migrationPlan.destination.profileHash
|
|
423
|
-
? {
|
|
424
|
-
coreHash: migrationPlan.destination.coreHash,
|
|
425
|
-
profileHash: migrationPlan.destination.profileHash,
|
|
426
|
-
}
|
|
427
|
-
: { coreHash: migrationPlan.destination.coreHash },
|
|
428
|
-
summary: `Applied ${execution.operationsExecuted} operation(s), marker written`,
|
|
429
|
-
timings: { total: Date.now() - startTime },
|
|
430
|
-
};
|
|
431
|
-
return dbInitResult;
|
|
432
|
-
} finally {
|
|
433
|
-
await driver.close();
|
|
434
|
-
}
|
|
435
|
-
});
|
|
436
|
-
|
|
437
|
-
// Handle result
|
|
438
|
-
const exitCode = handleResult(result, flags, (dbInitResult) => {
|
|
439
|
-
if (flags.json === 'object') {
|
|
440
|
-
console.log(formatDbInitJson(dbInitResult));
|
|
441
|
-
} else {
|
|
442
|
-
const output =
|
|
443
|
-
dbInitResult.mode === 'plan'
|
|
444
|
-
? formatDbInitPlanOutput(dbInitResult, flags)
|
|
445
|
-
: formatDbInitApplyOutput(dbInitResult, flags);
|
|
446
|
-
if (output) {
|
|
447
|
-
console.log(output);
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
});
|
|
451
|
-
|
|
203
|
+
addMigrationCommandOptions(command);
|
|
204
|
+
command.configureHelp({
|
|
205
|
+
formatHelp: (cmd) => {
|
|
206
|
+
const flags = parseGlobalFlags({});
|
|
207
|
+
return formatCommandHelp({ command: cmd, flags });
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
command.action(async (options: DbInitOptions) => {
|
|
211
|
+
const flags = parseGlobalFlags(options);
|
|
212
|
+
const startTime = Date.now();
|
|
213
|
+
|
|
214
|
+
// Validate JSON format option
|
|
215
|
+
if (flags.json === 'ndjson') {
|
|
216
|
+
const result = notOk(
|
|
217
|
+
errorJsonFormatNotSupported({
|
|
218
|
+
command: 'db init',
|
|
219
|
+
format: 'ndjson',
|
|
220
|
+
supportedFormats: ['object'],
|
|
221
|
+
}),
|
|
222
|
+
);
|
|
223
|
+
const exitCode = handleResult(result, flags);
|
|
452
224
|
process.exit(exitCode);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const result = await executeDbInitCommand(options, flags, startTime);
|
|
228
|
+
|
|
229
|
+
const exitCode = handleResult(result, flags, (dbInitResult) => {
|
|
230
|
+
if (flags.json === 'object') {
|
|
231
|
+
console.log(formatMigrationJson(dbInitResult));
|
|
232
|
+
} else {
|
|
233
|
+
const output =
|
|
234
|
+
dbInitResult.mode === 'plan'
|
|
235
|
+
? formatMigrationPlanOutput(dbInitResult, flags)
|
|
236
|
+
: formatMigrationApplyOutput(dbInitResult, flags);
|
|
237
|
+
if (output) {
|
|
238
|
+
console.log(output);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
453
241
|
});
|
|
454
242
|
|
|
243
|
+
process.exit(exitCode);
|
|
244
|
+
});
|
|
245
|
+
|
|
455
246
|
return command;
|
|
456
247
|
}
|