@prisma-next/cli 0.3.0-dev.15 → 0.3.0-dev.16

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 (42) hide show
  1. package/dist/chunk-5MPKZYVI.js +47 -0
  2. package/dist/chunk-5MPKZYVI.js.map +1 -0
  3. package/dist/chunk-74IELXRA.js +371 -0
  4. package/dist/chunk-74IELXRA.js.map +1 -0
  5. package/dist/{chunk-MG7PBERL.js → chunk-U6QI3AZ3.js} +7 -5
  6. package/dist/{chunk-MG7PBERL.js.map → chunk-U6QI3AZ3.js.map} +1 -1
  7. package/dist/{chunk-DIJPT5TZ.js → chunk-ZG5T6OB5.js} +2 -46
  8. package/dist/chunk-ZG5T6OB5.js.map +1 -0
  9. package/dist/cli.js +593 -268
  10. package/dist/cli.js.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 +238 -275
  14. package/dist/commands/db-init.js.map +1 -1
  15. package/dist/commands/db-introspect.js +6 -4
  16. package/dist/commands/db-introspect.js.map +1 -1
  17. package/dist/commands/db-schema-verify.js +6 -4
  18. package/dist/commands/db-schema-verify.js.map +1 -1
  19. package/dist/commands/db-sign.js +6 -4
  20. package/dist/commands/db-sign.js.map +1 -1
  21. package/dist/commands/db-verify.js +6 -4
  22. package/dist/commands/db-verify.js.map +1 -1
  23. package/dist/control-api/operations/db-init.d.ts +3 -1
  24. package/dist/control-api/operations/db-init.d.ts.map +1 -1
  25. package/dist/control-api/types.d.ts +54 -1
  26. package/dist/control-api/types.d.ts.map +1 -1
  27. package/dist/exports/control-api.d.ts +1 -1
  28. package/dist/exports/control-api.d.ts.map +1 -1
  29. package/dist/exports/control-api.js +3 -234
  30. package/dist/exports/control-api.js.map +1 -1
  31. package/dist/exports/index.js +3 -2
  32. package/dist/exports/index.js.map +1 -1
  33. package/dist/utils/progress-adapter.d.ts +26 -0
  34. package/dist/utils/progress-adapter.d.ts.map +1 -0
  35. package/package.json +11 -11
  36. package/src/commands/db-init.ts +262 -355
  37. package/src/control-api/client.ts +30 -0
  38. package/src/control-api/operations/db-init.ts +116 -2
  39. package/src/control-api/types.ts +63 -1
  40. package/src/exports/control-api.ts +3 -0
  41. package/src/utils/progress-adapter.ts +86 -0
  42. package/dist/chunk-DIJPT5TZ.js.map +0 -1
@@ -1,17 +1,12 @@
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
11
  errorDatabaseConnectionRequired,
17
12
  errorDriverRequired,
@@ -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,351 +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 connection (--db flag or config.db.connection)
158
- const dbConnection = options.db ?? config.db?.connection;
159
- if (!dbConnection) {
160
- throw errorDatabaseConnectionRequired({
161
- why: `Database connection is required for db init (set db.connection 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
- let driver: Awaited<ReturnType<(typeof driverDescriptor)['create']>>;
180
- try {
181
- driver = await withSpinner(() => driverDescriptor.create(dbConnection), {
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
- // Only redact if connection is a string (URL)
189
- const redacted =
190
- typeof dbConnection === 'string' ? redactDatabaseUrl(dbConnection) : undefined;
191
- throw errorRuntime('Database connection failed', {
192
- why: message,
193
- fix: 'Verify the database connection, ensure the database is reachable, and confirm credentials/permissions',
194
- meta: {
195
- ...(typeof code !== 'undefined' ? { code } : {}),
196
- ...(redacted ?? {}),
197
- },
198
- });
199
- }
200
-
201
- try {
202
- // Create family instance
203
- const stack = createControlPlaneStack({
204
- target: config.target,
205
- adapter: config.adapter,
206
- driver: driverDescriptor,
207
- extensionPacks: config.extensionPacks,
208
- });
209
- const familyInstance = config.family.create(stack);
210
- const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];
211
- const frameworkComponents = assertFrameworkComponentsCompatible(
212
- config.family.familyId,
213
- config.target.targetId,
214
- rawComponents,
215
- );
216
-
217
- // Validate contract
218
- const contractIR = familyInstance.validateContractIR(contractJson);
219
- assertContractRequirementsSatisfied({ contract: contractIR, stack });
220
-
221
- // Create planner and runner from target migrations capability
222
- const planner = migrations.createPlanner(familyInstance);
223
- const runner = migrations.createRunner(familyInstance);
224
-
225
- // Introspect live schema
226
- const schemaIR = await withSpinner(() => familyInstance.introspect({ driver }), {
227
- message: 'Introspecting database schema...',
228
- flags,
229
- });
230
-
231
- // Policy for init mode (additive only)
232
- const policy = { allowedOperationClasses: ['additive'] as const };
233
-
234
- // Plan migration
235
- const plannerResult: MigrationPlannerResult = await withSpinner(
236
- async () =>
237
- planner.plan({
238
- contract: contractIR,
239
- schema: schemaIR,
240
- policy,
241
- frameworkComponents,
242
- }),
243
- {
244
- message: 'Planning migration...',
245
- flags,
246
- },
247
- );
248
-
249
- if (plannerResult.kind === 'failure') {
250
- throw errorMigrationPlanningFailed({ conflicts: plannerResult.conflicts });
251
- }
252
-
253
- const migrationPlan: MigrationPlan = plannerResult.plan;
254
-
255
- // Check for existing marker - handle idempotency and mismatch errors
256
- const existingMarker = await familyInstance.readMarker({ driver });
257
- if (existingMarker) {
258
- const markerMatchesDestination =
259
- existingMarker.coreHash === migrationPlan.destination.coreHash &&
260
- (!migrationPlan.destination.profileHash ||
261
- existingMarker.profileHash === migrationPlan.destination.profileHash);
262
-
263
- if (markerMatchesDestination) {
264
- // Already at destination - return success with no operations
265
- const dbInitResult: DbInitResult = {
266
- ok: true,
267
- mode: options.plan ? 'plan' : 'apply',
268
- plan: {
269
- targetId: migrationPlan.targetId,
270
- destination: migrationPlan.destination,
271
- operations: [],
272
- },
273
- ...(options.plan
274
- ? {}
275
- : {
276
- execution: { operationsPlanned: 0, operationsExecuted: 0 },
277
- marker: {
278
- coreHash: existingMarker.coreHash,
279
- profileHash: existingMarker.profileHash,
280
- },
281
- }),
282
- summary: 'Database already at target contract state',
283
- timings: { total: Date.now() - startTime },
284
- };
285
- return dbInitResult;
286
- }
287
-
288
- // Marker exists but doesn't match destination - fail
289
- const coreHashMismatch = existingMarker.coreHash !== migrationPlan.destination.coreHash;
290
- const profileHashMismatch =
291
- migrationPlan.destination.profileHash &&
292
- existingMarker.profileHash !== migrationPlan.destination.profileHash;
293
-
294
- const mismatchParts: string[] = [];
295
- if (coreHashMismatch) {
296
- mismatchParts.push(
297
- `coreHash (marker: ${existingMarker.coreHash}, destination: ${migrationPlan.destination.coreHash})`,
298
- );
299
- }
300
- if (profileHashMismatch) {
301
- mismatchParts.push(
302
- `profileHash (marker: ${existingMarker.profileHash}, destination: ${migrationPlan.destination.profileHash})`,
303
- );
304
- }
305
-
306
- throw errorRuntime(
307
- `Existing contract marker does not match plan destination. Mismatch in ${mismatchParts.join(' and ')}.`,
308
- {
309
- why: 'Database has an existing contract marker that does not match the target contract',
310
- fix: 'If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow',
311
- meta: {
312
- code: 'MARKER_ORIGIN_MISMATCH',
313
- markerCoreHash: existingMarker.coreHash,
314
- destinationCoreHash: migrationPlan.destination.coreHash,
315
- ...(existingMarker.profileHash
316
- ? { markerProfileHash: existingMarker.profileHash }
317
- : {}),
318
- ...(migrationPlan.destination.profileHash
319
- ? { destinationProfileHash: migrationPlan.destination.profileHash }
320
- : {}),
321
- },
322
- },
323
- );
324
- }
325
-
326
- // Plan mode - don't execute
327
- if (options.plan) {
328
- const dbInitResult: DbInitResult = {
329
- ok: true,
330
- mode: 'plan',
331
- plan: {
332
- targetId: migrationPlan.targetId,
333
- destination: migrationPlan.destination,
334
- operations: migrationPlan.operations.map((op) => ({
335
- id: op.id,
336
- label: op.label,
337
- operationClass: op.operationClass,
338
- })),
339
- },
340
- summary: `Planned ${migrationPlan.operations.length} operation(s)`,
341
- timings: { total: Date.now() - startTime },
342
- };
343
- return dbInitResult;
344
- }
345
-
346
- // Apply mode - execute runner
347
- // Log main message once, then show individual operations via callbacks
348
- if (!flags.quiet && flags.json !== 'object') {
349
- console.log('Applying migration plan and verifying schema...');
350
- }
351
-
352
- const callbacks = {
353
- onOperationStart: (op: MigrationPlanOperation) => {
354
- if (!flags.quiet && flags.json !== 'object') {
355
- console.log(` → ${op.label}...`);
356
- }
357
- },
358
- onOperationComplete: (_op: MigrationPlanOperation) => {
359
- // Could log completion if needed
360
- },
361
- };
362
-
363
- const runnerResult: MigrationRunnerResult = await runner.execute({
364
- plan: migrationPlan,
365
- driver,
366
- destinationContract: contractIR,
367
- policy,
368
- callbacks,
369
- // db init plans and applies back-to-back from a fresh introspection, so per-operation
370
- // pre/postchecks and the idempotency probe are usually redundant overhead. We still
371
- // enforce marker/origin compatibility and a full schema verification after apply.
372
- executionChecks: {
373
- prechecks: false,
374
- postchecks: false,
375
- idempotencyChecks: false,
376
- },
377
- frameworkComponents,
378
- });
379
-
380
- if (!runnerResult.ok) {
381
- const meta: Record<string, unknown> = {
382
- code: runnerResult.failure.code,
383
- ...(runnerResult.failure.meta ?? {}),
384
- };
385
- const sqlState = typeof meta['sqlState'] === 'string' ? meta['sqlState'] : undefined;
386
- const fix =
387
- sqlState === '42501'
388
- ? 'Grant the database user sufficient privileges (insufficient_privilege), or run db init as a more privileged role'
389
- : runnerResult.failure.code === 'SCHEMA_VERIFY_FAILED'
390
- ? 'Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`'
391
- : undefined;
392
-
393
- throw errorRuntime(runnerResult.failure.summary, {
394
- why:
395
- runnerResult.failure.why ?? `Migration runner failed: ${runnerResult.failure.code}`,
396
- ...(fix ? { fix } : {}),
397
- meta,
398
- });
399
- }
400
-
401
- const execution = runnerResult.value;
402
-
403
- const dbInitResult: DbInitResult = {
404
- ok: true,
405
- mode: 'apply',
406
- plan: {
407
- targetId: migrationPlan.targetId,
408
- destination: migrationPlan.destination,
409
- operations: migrationPlan.operations.map((op) => ({
410
- id: op.id,
411
- label: op.label,
412
- operationClass: op.operationClass,
413
- })),
414
- },
415
- execution: {
416
- operationsPlanned: execution.operationsPlanned,
417
- operationsExecuted: execution.operationsExecuted,
418
- },
419
- marker: migrationPlan.destination.profileHash
420
- ? {
421
- coreHash: migrationPlan.destination.coreHash,
422
- profileHash: migrationPlan.destination.profileHash,
423
- }
424
- : { coreHash: migrationPlan.destination.coreHash },
425
- summary: `Applied ${execution.operationsExecuted} operation(s), marker written`,
426
- timings: { total: Date.now() - startTime },
427
- };
428
- return dbInitResult;
429
- } finally {
430
- await driver.close();
431
- }
432
- });
340
+ const result = await executeDbInitCommand(options, flags, startTime);
433
341
 
434
- // Handle result
435
342
  const exitCode = handleResult(result, flags, (dbInitResult) => {
436
343
  if (flags.json === 'object') {
437
344
  console.log(formatDbInitJson(dbInitResult));
@@ -196,6 +196,35 @@ class ControlClientImpl implements ControlClient {
196
196
  }
197
197
 
198
198
  async dbInit(options: DbInitOptions): Promise<DbInitResult> {
199
+ const { onProgress } = options;
200
+
201
+ // Connect with progress span if connection provided
202
+ if (options.connection !== undefined) {
203
+ onProgress?.({
204
+ action: 'dbInit',
205
+ kind: 'spanStart',
206
+ spanId: 'connect',
207
+ label: 'Connecting to database...',
208
+ });
209
+ try {
210
+ await this.connect(options.connection);
211
+ onProgress?.({
212
+ action: 'dbInit',
213
+ kind: 'spanEnd',
214
+ spanId: 'connect',
215
+ outcome: 'ok',
216
+ });
217
+ } catch (error) {
218
+ onProgress?.({
219
+ action: 'dbInit',
220
+ kind: 'spanEnd',
221
+ spanId: 'connect',
222
+ outcome: 'error',
223
+ });
224
+ throw error;
225
+ }
226
+ }
227
+
199
228
  const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();
200
229
 
201
230
  // Check target supports migrations
@@ -214,6 +243,7 @@ class ControlClientImpl implements ControlClient {
214
243
  mode: options.mode,
215
244
  migrations: this.options.target.migrations,
216
245
  frameworkComponents,
246
+ ...(onProgress ? { onProgress } : {}),
217
247
  });
218
248
  }
219
249