@prisma-next/cli 0.3.0-dev.8 → 0.3.0-pr.100.1

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