@prisma-next/cli 0.3.0-dev.5 → 0.3.0-dev.53

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 (130) hide show
  1. package/README.md +145 -74
  2. package/dist/cli.d.mts +1 -0
  3. package/dist/cli.js +1 -2376
  4. package/dist/cli.mjs +169 -0
  5. package/dist/cli.mjs.map +1 -0
  6. package/dist/client-BSZKpZTF.mjs +711 -0
  7. package/dist/client-BSZKpZTF.mjs.map +1 -0
  8. package/dist/commands/contract-emit.d.mts +7 -0
  9. package/dist/commands/contract-emit.d.mts.map +1 -0
  10. package/dist/commands/contract-emit.mjs +147 -0
  11. package/dist/commands/contract-emit.mjs.map +1 -0
  12. package/dist/commands/db-init.d.mts +7 -0
  13. package/dist/commands/db-init.d.mts.map +1 -0
  14. package/dist/commands/db-init.mjs +179 -0
  15. package/dist/commands/db-init.mjs.map +1 -0
  16. package/dist/commands/db-introspect.d.mts +7 -0
  17. package/dist/commands/db-introspect.d.mts.map +1 -0
  18. package/dist/commands/db-introspect.mjs +120 -0
  19. package/dist/commands/db-introspect.mjs.map +1 -0
  20. package/dist/commands/db-schema-verify.d.mts +7 -0
  21. package/dist/commands/db-schema-verify.d.mts.map +1 -0
  22. package/dist/commands/db-schema-verify.mjs +116 -0
  23. package/dist/commands/db-schema-verify.mjs.map +1 -0
  24. package/dist/commands/db-sign.d.mts +7 -0
  25. package/dist/commands/db-sign.d.mts.map +1 -0
  26. package/dist/commands/db-sign.mjs +138 -0
  27. package/dist/commands/db-sign.mjs.map +1 -0
  28. package/dist/commands/db-verify.d.mts +7 -0
  29. package/dist/commands/db-verify.d.mts.map +1 -0
  30. package/dist/commands/db-verify.mjs +129 -0
  31. package/dist/commands/db-verify.mjs.map +1 -0
  32. package/dist/config-loader-BJ8HsEdA.mjs +42 -0
  33. package/dist/config-loader-BJ8HsEdA.mjs.map +1 -0
  34. package/dist/{config-loader.d.ts → config-loader.d.mts} +8 -3
  35. package/dist/config-loader.d.mts.map +1 -0
  36. package/dist/config-loader.mjs +3 -0
  37. package/dist/exports/config-types.d.mts +2 -0
  38. package/dist/exports/config-types.mjs +3 -0
  39. package/dist/exports/control-api.d.mts +433 -0
  40. package/dist/exports/control-api.d.mts.map +1 -0
  41. package/dist/exports/control-api.mjs +96 -0
  42. package/dist/exports/control-api.mjs.map +1 -0
  43. package/dist/{load-ts-contract.d.ts → exports/index.d.mts} +10 -5
  44. package/dist/exports/index.d.mts.map +1 -0
  45. package/dist/exports/index.mjs +132 -0
  46. package/dist/exports/index.mjs.map +1 -0
  47. package/dist/result-handler-BZPY7HX4.mjs +1029 -0
  48. package/dist/result-handler-BZPY7HX4.mjs.map +1 -0
  49. package/package.json +48 -37
  50. package/src/commands/contract-emit.ts +205 -111
  51. package/src/commands/db-init.ts +258 -359
  52. package/src/commands/db-introspect.ts +151 -184
  53. package/src/commands/db-schema-verify.ts +151 -149
  54. package/src/commands/db-sign.ts +202 -200
  55. package/src/commands/db-verify.ts +181 -155
  56. package/src/control-api/client.ts +610 -0
  57. package/src/control-api/operations/contract-emit.ts +161 -0
  58. package/src/control-api/operations/db-init.ts +281 -0
  59. package/src/control-api/types.ts +475 -0
  60. package/src/exports/control-api.ts +48 -0
  61. package/src/load-ts-contract.ts +16 -11
  62. package/src/utils/cli-errors.ts +1 -1
  63. package/src/utils/framework-components.ts +11 -30
  64. package/src/utils/output.ts +16 -10
  65. package/src/utils/progress-adapter.ts +86 -0
  66. package/dist/chunk-464LNZCE.js +0 -134
  67. package/dist/chunk-464LNZCE.js.map +0 -1
  68. package/dist/chunk-BZMBKEEQ.js +0 -997
  69. package/dist/chunk-BZMBKEEQ.js.map +0 -1
  70. package/dist/chunk-HWYQOCAJ.js +0 -47
  71. package/dist/chunk-HWYQOCAJ.js.map +0 -1
  72. package/dist/chunk-ZKYEJROM.js +0 -94
  73. package/dist/chunk-ZKYEJROM.js.map +0 -1
  74. package/dist/cli.d.ts +0 -2
  75. package/dist/cli.d.ts.map +0 -1
  76. package/dist/cli.js.map +0 -1
  77. package/dist/commands/contract-emit.d.ts +0 -3
  78. package/dist/commands/contract-emit.d.ts.map +0 -1
  79. package/dist/commands/contract-emit.js +0 -9
  80. package/dist/commands/contract-emit.js.map +0 -1
  81. package/dist/commands/db-init.d.ts +0 -3
  82. package/dist/commands/db-init.d.ts.map +0 -1
  83. package/dist/commands/db-init.js +0 -341
  84. package/dist/commands/db-init.js.map +0 -1
  85. package/dist/commands/db-introspect.d.ts +0 -3
  86. package/dist/commands/db-introspect.d.ts.map +0 -1
  87. package/dist/commands/db-introspect.js +0 -190
  88. package/dist/commands/db-introspect.js.map +0 -1
  89. package/dist/commands/db-schema-verify.d.ts +0 -3
  90. package/dist/commands/db-schema-verify.d.ts.map +0 -1
  91. package/dist/commands/db-schema-verify.js +0 -164
  92. package/dist/commands/db-schema-verify.js.map +0 -1
  93. package/dist/commands/db-sign.d.ts +0 -3
  94. package/dist/commands/db-sign.d.ts.map +0 -1
  95. package/dist/commands/db-sign.js +0 -199
  96. package/dist/commands/db-sign.js.map +0 -1
  97. package/dist/commands/db-verify.d.ts +0 -3
  98. package/dist/commands/db-verify.d.ts.map +0 -1
  99. package/dist/commands/db-verify.js +0 -173
  100. package/dist/commands/db-verify.js.map +0 -1
  101. package/dist/config-loader.d.ts.map +0 -1
  102. package/dist/config-loader.js +0 -7
  103. package/dist/config-loader.js.map +0 -1
  104. package/dist/exports/config-types.d.ts +0 -3
  105. package/dist/exports/config-types.d.ts.map +0 -1
  106. package/dist/exports/config-types.js +0 -6
  107. package/dist/exports/config-types.js.map +0 -1
  108. package/dist/exports/index.d.ts +0 -4
  109. package/dist/exports/index.d.ts.map +0 -1
  110. package/dist/exports/index.js +0 -175
  111. package/dist/exports/index.js.map +0 -1
  112. package/dist/load-ts-contract.d.ts.map +0 -1
  113. package/dist/utils/action.d.ts +0 -16
  114. package/dist/utils/action.d.ts.map +0 -1
  115. package/dist/utils/cli-errors.d.ts +0 -7
  116. package/dist/utils/cli-errors.d.ts.map +0 -1
  117. package/dist/utils/command-helpers.d.ts +0 -12
  118. package/dist/utils/command-helpers.d.ts.map +0 -1
  119. package/dist/utils/framework-components.d.ts +0 -81
  120. package/dist/utils/framework-components.d.ts.map +0 -1
  121. package/dist/utils/global-flags.d.ts +0 -25
  122. package/dist/utils/global-flags.d.ts.map +0 -1
  123. package/dist/utils/output.d.ts +0 -142
  124. package/dist/utils/output.d.ts.map +0 -1
  125. package/dist/utils/result-handler.d.ts +0 -15
  126. package/dist/utils/result-handler.d.ts.map +0 -1
  127. package/dist/utils/spinner.d.ts +0 -29
  128. package/dist/utils/spinner.d.ts.map +0 -1
  129. package/src/utils/action.ts +0 -43
  130. package/src/utils/spinner.ts +0 -67
@@ -1,18 +1,15 @@
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 { redactDatabaseUrl } from '@prisma-next/utils/redact-db-url';
3
+ import { ifDefined } from '@prisma-next/utils/defined';
4
+ import { notOk, ok, type Result } from '@prisma-next/utils/result';
10
5
  import { Command } from 'commander';
11
6
  import { loadConfig } from '../config-loader';
12
- import { performAction } from '../utils/action';
7
+ import { createControlClient } from '../control-api/client';
8
+ import type { DbInitFailure } from '../control-api/types';
13
9
  import {
10
+ CliStructuredError,
14
11
  errorContractValidationFailed,
15
- errorDatabaseUrlRequired,
12
+ errorDatabaseConnectionRequired,
16
13
  errorDriverRequired,
17
14
  errorFileNotFound,
18
15
  errorJsonFormatNotSupported,
@@ -22,11 +19,7 @@ import {
22
19
  errorUnexpected,
23
20
  } from '../utils/cli-errors';
24
21
  import { setCommandDescriptions } from '../utils/command-helpers';
25
- import {
26
- assertContractRequirementsSatisfied,
27
- assertFrameworkComponentsCompatible,
28
- } from '../utils/framework-components';
29
- import { parseGlobalFlags } from '../utils/global-flags';
22
+ import { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';
30
23
  import {
31
24
  type DbInitResult,
32
25
  formatCommandHelp,
@@ -35,8 +28,8 @@ import {
35
28
  formatDbInitPlanOutput,
36
29
  formatStyledHeader,
37
30
  } from '../utils/output';
31
+ import { createProgressAdapter } from '../utils/progress-adapter';
38
32
  import { handleResult } from '../utils/result-handler';
39
- import { withSpinner } from '../utils/spinner';
40
33
 
41
34
  interface DbInitOptions {
42
35
  readonly db?: string;
@@ -54,6 +47,246 @@ interface DbInitOptions {
54
47
  readonly 'no-color'?: boolean;
55
48
  }
56
49
 
50
+ /**
51
+ * Maps a DbInitFailure to a CliStructuredError for consistent error handling.
52
+ */
53
+ function mapDbInitFailure(failure: DbInitFailure): CliStructuredError {
54
+ if (failure.code === 'PLANNING_FAILED') {
55
+ return errorMigrationPlanningFailed({ conflicts: failure.conflicts ?? [] });
56
+ }
57
+
58
+ if (failure.code === 'MARKER_ORIGIN_MISMATCH') {
59
+ const mismatchParts: string[] = [];
60
+ if (
61
+ failure.marker?.storageHash !== failure.destination?.storageHash &&
62
+ failure.marker?.storageHash &&
63
+ failure.destination?.storageHash
64
+ ) {
65
+ mismatchParts.push(
66
+ `storageHash (marker: ${failure.marker.storageHash}, destination: ${failure.destination.storageHash})`,
67
+ );
68
+ }
69
+ if (
70
+ failure.marker?.profileHash !== failure.destination?.profileHash &&
71
+ failure.marker?.profileHash &&
72
+ failure.destination?.profileHash
73
+ ) {
74
+ mismatchParts.push(
75
+ `profileHash (marker: ${failure.marker.profileHash}, destination: ${failure.destination.profileHash})`,
76
+ );
77
+ }
78
+
79
+ return errorRuntime(
80
+ `Existing contract marker does not match plan destination.${mismatchParts.length > 0 ? ` Mismatch in ${mismatchParts.join(' and ')}.` : ''}`,
81
+ {
82
+ why: 'Database has an existing contract marker that does not match the target contract',
83
+ fix: 'If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow',
84
+ meta: {
85
+ code: 'MARKER_ORIGIN_MISMATCH',
86
+ ...ifDefined('markerStorageHash', failure.marker?.storageHash),
87
+ ...ifDefined('destinationStorageHash', failure.destination?.storageHash),
88
+ ...ifDefined('markerProfileHash', failure.marker?.profileHash),
89
+ ...ifDefined('destinationProfileHash', failure.destination?.profileHash),
90
+ },
91
+ },
92
+ );
93
+ }
94
+
95
+ if (failure.code === 'RUNNER_FAILED') {
96
+ return errorRuntime(failure.summary, {
97
+ why: failure.why ?? 'Migration runner failed',
98
+ fix: 'Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`',
99
+ meta: {
100
+ code: 'RUNNER_FAILED',
101
+ ...(failure.meta ?? {}),
102
+ },
103
+ });
104
+ }
105
+
106
+ // Exhaustive check - TypeScript will error if a new code is added but not handled
107
+ const exhaustive: never = failure.code;
108
+ throw new Error(`Unhandled DbInitFailure code: ${exhaustive}`);
109
+ }
110
+
111
+ /**
112
+ * Executes the db init command and returns a structured Result.
113
+ */
114
+ async function executeDbInitCommand(
115
+ options: DbInitOptions,
116
+ flags: GlobalFlags,
117
+ startTime: number,
118
+ ): Promise<Result<DbInitResult, CliStructuredError>> {
119
+ // Load config
120
+ const config = await loadConfig(options.config);
121
+ const configPath = options.config
122
+ ? relative(process.cwd(), resolve(options.config))
123
+ : 'prisma-next.config.ts';
124
+ const contractPathAbsolute = config.contract?.output
125
+ ? resolve(config.contract.output)
126
+ : resolve('src/prisma/contract.json');
127
+ const contractPath = relative(process.cwd(), contractPathAbsolute);
128
+
129
+ // Output header
130
+ if (flags.json !== 'object' && !flags.quiet) {
131
+ const details: Array<{ label: string; value: string }> = [
132
+ { label: 'config', value: configPath },
133
+ { label: 'contract', value: contractPath },
134
+ ];
135
+ if (options.db) {
136
+ details.push({ label: 'database', value: options.db });
137
+ }
138
+ if (options.plan) {
139
+ details.push({ label: 'mode', value: 'plan (dry run)' });
140
+ }
141
+ const header = formatStyledHeader({
142
+ command: 'db init',
143
+ description: 'Bootstrap a database to match the current contract',
144
+ url: 'https://pris.ly/db-init',
145
+ details,
146
+ flags,
147
+ });
148
+ console.log(header);
149
+ }
150
+
151
+ // Load contract file
152
+ let contractJsonContent: string;
153
+ try {
154
+ contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
155
+ } catch (error) {
156
+ if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
157
+ return notOk(
158
+ errorFileNotFound(contractPathAbsolute, {
159
+ why: `Contract file not found at ${contractPathAbsolute}`,
160
+ fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`,
161
+ }),
162
+ );
163
+ }
164
+ return notOk(
165
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
166
+ why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
167
+ }),
168
+ );
169
+ }
170
+
171
+ let contractJson: Record<string, unknown>;
172
+ try {
173
+ contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
174
+ } catch (error) {
175
+ return notOk(
176
+ errorContractValidationFailed(
177
+ `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
178
+ { where: { path: contractPathAbsolute } },
179
+ ),
180
+ );
181
+ }
182
+
183
+ // Resolve database connection (--db flag or config.db.connection)
184
+ const dbConnection = options.db ?? config.db?.connection;
185
+ if (!dbConnection) {
186
+ return notOk(
187
+ errorDatabaseConnectionRequired({
188
+ why: `Database connection is required for db init (set db.connection in ${configPath}, or pass --db <url>)`,
189
+ }),
190
+ );
191
+ }
192
+
193
+ // Check for driver
194
+ if (!config.driver) {
195
+ return notOk(errorDriverRequired({ why: 'Config.driver is required for db init' }));
196
+ }
197
+
198
+ // Check target supports migrations via the migrations capability
199
+ if (!config.target.migrations) {
200
+ return notOk(
201
+ errorTargetMigrationNotSupported({
202
+ why: `Target "${config.target.id}" does not support migrations`,
203
+ }),
204
+ );
205
+ }
206
+
207
+ // Create control client
208
+ const client = createControlClient({
209
+ family: config.family,
210
+ target: config.target,
211
+ adapter: config.adapter,
212
+ driver: config.driver,
213
+ extensionPacks: config.extensionPacks ?? [],
214
+ });
215
+
216
+ // Create progress adapter
217
+ const onProgress = createProgressAdapter({ flags });
218
+
219
+ try {
220
+ // Call dbInit with connection and progress callback
221
+ // Connection happens inside dbInit with a 'connect' progress span
222
+ const result = await client.dbInit({
223
+ contractIR: contractJson,
224
+ mode: options.plan ? 'plan' : 'apply',
225
+ connection: dbConnection,
226
+ onProgress,
227
+ });
228
+
229
+ // Handle failures by mapping to CLI structured error
230
+ if (!result.ok) {
231
+ return notOk(mapDbInitFailure(result.failure));
232
+ }
233
+
234
+ // Convert success result to CLI output format
235
+ const profileHash = result.value.marker?.profileHash;
236
+ const dbInitResult: DbInitResult = {
237
+ ok: true,
238
+ mode: result.value.mode,
239
+ plan: {
240
+ targetId: config.target.targetId,
241
+ destination: {
242
+ storageHash: result.value.marker?.storageHash ?? '',
243
+ ...ifDefined('profileHash', profileHash),
244
+ },
245
+ operations: result.value.plan.operations.map((op) => ({
246
+ id: op.id,
247
+ label: op.label,
248
+ operationClass: op.operationClass,
249
+ })),
250
+ },
251
+ ...(result.value.execution
252
+ ? {
253
+ execution: {
254
+ operationsPlanned: result.value.execution.operationsPlanned,
255
+ operationsExecuted: result.value.execution.operationsExecuted,
256
+ },
257
+ }
258
+ : {}),
259
+ ...(result.value.marker
260
+ ? {
261
+ marker: {
262
+ storageHash: result.value.marker.storageHash,
263
+ ...ifDefined('profileHash', result.value.marker.profileHash),
264
+ },
265
+ }
266
+ : {}),
267
+ summary: result.value.summary,
268
+ timings: { total: Date.now() - startTime },
269
+ };
270
+
271
+ return ok(dbInitResult);
272
+ } catch (error) {
273
+ // Driver already throws CliStructuredError for connection failures
274
+ // Use static type guard to work across module boundaries
275
+ if (CliStructuredError.is(error)) {
276
+ return notOk(error);
277
+ }
278
+
279
+ // Wrap unexpected errors
280
+ return notOk(
281
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
282
+ why: `Unexpected error during db init: ${error instanceof Error ? error.message : String(error)}`,
283
+ }),
284
+ );
285
+ } finally {
286
+ await client.close();
287
+ }
288
+ }
289
+
57
290
  export function createDbInitCommand(): Command {
58
291
  const command = new Command('init');
59
292
  setCommandDescriptions(
@@ -86,355 +319,21 @@ export function createDbInitCommand(): Command {
86
319
  const flags = parseGlobalFlags(options);
87
320
  const startTime = Date.now();
88
321
 
89
- const result = await performAction(async () => {
90
- if (flags.json === 'ndjson') {
91
- throw errorJsonFormatNotSupported({
322
+ // Validate JSON format option
323
+ if (flags.json === 'ndjson') {
324
+ const result = notOk(
325
+ errorJsonFormatNotSupported({
92
326
  command: 'db init',
93
327
  format: 'ndjson',
94
328
  supportedFormats: ['object'],
95
- });
96
- }
329
+ }),
330
+ );
331
+ const exitCode = handleResult(result, flags);
332
+ process.exit(exitCode);
333
+ }
97
334
 
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
- });
335
+ const result = await executeDbInitCommand(options, flags, startTime);
436
336
 
437
- // Handle result
438
337
  const exitCode = handleResult(result, flags, (dbInitResult) => {
439
338
  if (flags.json === 'object') {
440
339
  console.log(formatDbInitJson(dbInitResult));