@prisma-next/cli 0.3.0-dev.6 → 0.3.0-dev.63

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 (180) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +314 -80
  3. package/dist/cli-errors-JlPTsazx.mjs +3 -0
  4. package/dist/cli.d.mts +1 -0
  5. package/dist/cli.js +1 -2376
  6. package/dist/cli.mjs +198 -0
  7. package/dist/cli.mjs.map +1 -0
  8. package/dist/client-PimzSD1f.mjs +981 -0
  9. package/dist/client-PimzSD1f.mjs.map +1 -0
  10. package/dist/commands/contract-emit.d.mts +7 -0
  11. package/dist/commands/contract-emit.d.mts.map +1 -0
  12. package/dist/commands/contract-emit.mjs +150 -0
  13. package/dist/commands/contract-emit.mjs.map +1 -0
  14. package/dist/commands/db-init.d.mts +7 -0
  15. package/dist/commands/db-init.d.mts.map +1 -0
  16. package/dist/commands/db-init.mjs +132 -0
  17. package/dist/commands/db-init.mjs.map +1 -0
  18. package/dist/commands/db-introspect.d.mts +7 -0
  19. package/dist/commands/db-introspect.d.mts.map +1 -0
  20. package/dist/commands/db-introspect.mjs +117 -0
  21. package/dist/commands/db-introspect.mjs.map +1 -0
  22. package/dist/commands/db-schema-verify.d.mts +7 -0
  23. package/dist/commands/db-schema-verify.d.mts.map +1 -0
  24. package/dist/commands/db-schema-verify.mjs +119 -0
  25. package/dist/commands/db-schema-verify.mjs.map +1 -0
  26. package/dist/commands/db-sign.d.mts +7 -0
  27. package/dist/commands/db-sign.d.mts.map +1 -0
  28. package/dist/commands/db-sign.mjs +141 -0
  29. package/dist/commands/db-sign.mjs.map +1 -0
  30. package/dist/commands/db-update.d.mts +7 -0
  31. package/dist/commands/db-update.d.mts.map +1 -0
  32. package/dist/commands/db-update.mjs +121 -0
  33. package/dist/commands/db-update.mjs.map +1 -0
  34. package/dist/commands/db-verify.d.mts +7 -0
  35. package/dist/commands/db-verify.d.mts.map +1 -0
  36. package/dist/commands/db-verify.mjs +132 -0
  37. package/dist/commands/db-verify.mjs.map +1 -0
  38. package/dist/commands/migration-apply.d.mts +23 -0
  39. package/dist/commands/migration-apply.d.mts.map +1 -0
  40. package/dist/commands/migration-apply.mjs +249 -0
  41. package/dist/commands/migration-apply.mjs.map +1 -0
  42. package/dist/commands/migration-plan.d.mts +25 -0
  43. package/dist/commands/migration-plan.d.mts.map +1 -0
  44. package/dist/commands/migration-plan.mjs +266 -0
  45. package/dist/commands/migration-plan.mjs.map +1 -0
  46. package/dist/commands/migration-show.d.mts +28 -0
  47. package/dist/commands/migration-show.d.mts.map +1 -0
  48. package/dist/commands/migration-show.mjs +138 -0
  49. package/dist/commands/migration-show.mjs.map +1 -0
  50. package/dist/commands/migration-status.d.mts +35 -0
  51. package/dist/commands/migration-status.d.mts.map +1 -0
  52. package/dist/commands/migration-status.mjs +259 -0
  53. package/dist/commands/migration-status.mjs.map +1 -0
  54. package/dist/commands/migration-verify.d.mts +16 -0
  55. package/dist/commands/migration-verify.d.mts.map +1 -0
  56. package/dist/commands/migration-verify.mjs +86 -0
  57. package/dist/commands/migration-verify.mjs.map +1 -0
  58. package/dist/config-loader-PPf4CtDj.mjs +43 -0
  59. package/dist/config-loader-PPf4CtDj.mjs.map +1 -0
  60. package/dist/{config-loader.d.ts → config-loader.d.mts} +8 -3
  61. package/dist/config-loader.d.mts.map +1 -0
  62. package/dist/config-loader.mjs +3 -0
  63. package/dist/exports/config-types.d.mts +2 -0
  64. package/dist/exports/config-types.mjs +3 -0
  65. package/dist/exports/control-api.d.mts +621 -0
  66. package/dist/exports/control-api.d.mts.map +1 -0
  67. package/dist/exports/control-api.mjs +97 -0
  68. package/dist/exports/control-api.mjs.map +1 -0
  69. package/dist/{load-ts-contract.d.ts → exports/index.d.mts} +10 -5
  70. package/dist/exports/index.d.mts.map +1 -0
  71. package/dist/exports/index.mjs +130 -0
  72. package/dist/exports/index.mjs.map +1 -0
  73. package/dist/extract-sql-ddl-BmlKvk4o.mjs +26 -0
  74. package/dist/extract-sql-ddl-BmlKvk4o.mjs.map +1 -0
  75. package/dist/framework-components-CjV_jD8f.mjs +59 -0
  76. package/dist/framework-components-CjV_jD8f.mjs.map +1 -0
  77. package/dist/migration-command-scaffold-DfY_F3ev.mjs +97 -0
  78. package/dist/migration-command-scaffold-DfY_F3ev.mjs.map +1 -0
  79. package/dist/progress-adapter-DENrzF6I.mjs +49 -0
  80. package/dist/progress-adapter-DENrzF6I.mjs.map +1 -0
  81. package/dist/result-handler-iA9JtUC7.mjs +1186 -0
  82. package/dist/result-handler-iA9JtUC7.mjs.map +1 -0
  83. package/package.json +75 -38
  84. package/src/cli.ts +43 -0
  85. package/src/commands/contract-emit.ts +221 -111
  86. package/src/commands/db-init.ts +217 -426
  87. package/src/commands/db-introspect.ts +148 -185
  88. package/src/commands/db-schema-verify.ts +162 -149
  89. package/src/commands/db-sign.ts +215 -202
  90. package/src/commands/db-update.ts +220 -0
  91. package/src/commands/db-verify.ts +193 -156
  92. package/src/commands/migration-apply.ts +431 -0
  93. package/src/commands/migration-plan.ts +446 -0
  94. package/src/commands/migration-show.ts +255 -0
  95. package/src/commands/migration-status.ts +436 -0
  96. package/src/commands/migration-verify.ts +151 -0
  97. package/src/config-loader.ts +13 -3
  98. package/src/control-api/client.ts +605 -0
  99. package/src/control-api/errors.ts +9 -0
  100. package/src/control-api/operations/contract-emit.ts +161 -0
  101. package/src/control-api/operations/db-init.ts +286 -0
  102. package/src/control-api/operations/db-update.ts +221 -0
  103. package/src/control-api/operations/extract-sql-ddl.ts +47 -0
  104. package/src/control-api/operations/migration-apply.ts +195 -0
  105. package/src/control-api/operations/migration-helpers.ts +49 -0
  106. package/src/control-api/types.ts +687 -0
  107. package/src/exports/config-types.ts +3 -3
  108. package/src/exports/control-api.ts +53 -0
  109. package/src/load-ts-contract.ts +16 -11
  110. package/src/utils/cli-errors.ts +3 -1
  111. package/src/utils/command-helpers.ts +92 -3
  112. package/src/utils/framework-components.ts +11 -30
  113. package/src/utils/migration-command-scaffold.ts +190 -0
  114. package/src/utils/output.ts +363 -25
  115. package/src/utils/progress-adapter.ts +86 -0
  116. package/dist/chunk-464LNZCE.js +0 -134
  117. package/dist/chunk-464LNZCE.js.map +0 -1
  118. package/dist/chunk-BZMBKEEQ.js +0 -997
  119. package/dist/chunk-BZMBKEEQ.js.map +0 -1
  120. package/dist/chunk-HWYQOCAJ.js +0 -47
  121. package/dist/chunk-HWYQOCAJ.js.map +0 -1
  122. package/dist/chunk-ZKYEJROM.js +0 -94
  123. package/dist/chunk-ZKYEJROM.js.map +0 -1
  124. package/dist/cli.d.ts +0 -2
  125. package/dist/cli.d.ts.map +0 -1
  126. package/dist/cli.js.map +0 -1
  127. package/dist/commands/contract-emit.d.ts +0 -3
  128. package/dist/commands/contract-emit.d.ts.map +0 -1
  129. package/dist/commands/contract-emit.js +0 -9
  130. package/dist/commands/contract-emit.js.map +0 -1
  131. package/dist/commands/db-init.d.ts +0 -3
  132. package/dist/commands/db-init.d.ts.map +0 -1
  133. package/dist/commands/db-init.js +0 -341
  134. package/dist/commands/db-init.js.map +0 -1
  135. package/dist/commands/db-introspect.d.ts +0 -3
  136. package/dist/commands/db-introspect.d.ts.map +0 -1
  137. package/dist/commands/db-introspect.js +0 -190
  138. package/dist/commands/db-introspect.js.map +0 -1
  139. package/dist/commands/db-schema-verify.d.ts +0 -3
  140. package/dist/commands/db-schema-verify.d.ts.map +0 -1
  141. package/dist/commands/db-schema-verify.js +0 -164
  142. package/dist/commands/db-schema-verify.js.map +0 -1
  143. package/dist/commands/db-sign.d.ts +0 -3
  144. package/dist/commands/db-sign.d.ts.map +0 -1
  145. package/dist/commands/db-sign.js +0 -199
  146. package/dist/commands/db-sign.js.map +0 -1
  147. package/dist/commands/db-verify.d.ts +0 -3
  148. package/dist/commands/db-verify.d.ts.map +0 -1
  149. package/dist/commands/db-verify.js +0 -173
  150. package/dist/commands/db-verify.js.map +0 -1
  151. package/dist/config-loader.d.ts.map +0 -1
  152. package/dist/config-loader.js +0 -7
  153. package/dist/config-loader.js.map +0 -1
  154. package/dist/exports/config-types.d.ts +0 -3
  155. package/dist/exports/config-types.d.ts.map +0 -1
  156. package/dist/exports/config-types.js +0 -6
  157. package/dist/exports/config-types.js.map +0 -1
  158. package/dist/exports/index.d.ts +0 -4
  159. package/dist/exports/index.d.ts.map +0 -1
  160. package/dist/exports/index.js +0 -175
  161. package/dist/exports/index.js.map +0 -1
  162. package/dist/load-ts-contract.d.ts.map +0 -1
  163. package/dist/utils/action.d.ts +0 -16
  164. package/dist/utils/action.d.ts.map +0 -1
  165. package/dist/utils/cli-errors.d.ts +0 -7
  166. package/dist/utils/cli-errors.d.ts.map +0 -1
  167. package/dist/utils/command-helpers.d.ts +0 -12
  168. package/dist/utils/command-helpers.d.ts.map +0 -1
  169. package/dist/utils/framework-components.d.ts +0 -81
  170. package/dist/utils/framework-components.d.ts.map +0 -1
  171. package/dist/utils/global-flags.d.ts +0 -25
  172. package/dist/utils/global-flags.d.ts.map +0 -1
  173. package/dist/utils/output.d.ts +0 -142
  174. package/dist/utils/output.d.ts.map +0 -1
  175. package/dist/utils/result-handler.d.ts +0 -15
  176. package/dist/utils/result-handler.d.ts.map +0 -1
  177. package/dist/utils/spinner.d.ts +0 -29
  178. package/dist/utils/spinner.d.ts.map +0 -1
  179. package/src/utils/action.ts +0 -43
  180. package/src/utils/spinner.ts +0 -67
@@ -1,456 +1,247 @@
1
- import { readFile } from 'node:fs/promises';
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';
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 { loadConfig } from '../config-loader';
12
- import { performAction } from '../utils/action';
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 { setCommandDescriptions } from '../utils/command-helpers';
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
- assertContractRequirementsSatisfied,
27
- assertFrameworkComponentsCompatible,
28
- } from '../utils/framework-components';
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
- formatDbInitApplyOutput,
34
- formatDbInitJson,
35
- formatDbInitPlanOutput,
36
- formatStyledHeader,
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
- interface DbInitOptions {
42
- readonly db?: string;
43
- readonly config?: string;
44
- readonly plan?: boolean;
45
- readonly json?: string | boolean;
46
- readonly quiet?: boolean;
47
- readonly q?: boolean;
48
- readonly verbose?: boolean;
49
- readonly v?: boolean;
50
- readonly vv?: boolean;
51
- readonly trace?: boolean;
52
- readonly timestamps?: boolean;
53
- readonly color?: boolean;
54
- readonly 'no-color'?: boolean;
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 write the contract marker',
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 writes a contract marker to track the database state. Use --plan to\n' +
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
- .configureHelp({
70
- formatHelp: (cmd) => {
71
- const flags = parseGlobalFlags({});
72
- return formatCommandHelp({ command: cmd, flags });
73
- },
74
- })
75
- .option('--db <url>', 'Database connection string')
76
- .option('--config <path>', 'Path to prisma-next.config.ts')
77
- .option('--plan', 'Preview planned operations without applying', false)
78
- .option('--json [format]', 'Output as JSON (object)', false)
79
- .option('-q, --quiet', 'Quiet mode: errors only')
80
- .option('-v, --verbose', 'Verbose output: debug info, timings')
81
- .option('-vv, --trace', 'Trace output: deep internals, stack traces')
82
- .option('--timestamps', 'Add timestamps to output')
83
- .option('--color', 'Force color output')
84
- .option('--no-color', 'Disable color output')
85
- .action(async (options: DbInitOptions) => {
86
- const flags = parseGlobalFlags(options);
87
- const startTime = Date.now();
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
  }