@prisma-next/cli 0.3.0-dev.11 → 0.3.0-dev.114

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 (215) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +470 -134
  3. package/dist/cli-errors-ByGuoqNj.mjs +3 -0
  4. package/dist/cli-errors-D6HxRn3A.d.mts +2 -0
  5. package/dist/cli.d.mts +1 -0
  6. package/dist/cli.js +1 -2350
  7. package/dist/cli.mjs +235 -0
  8. package/dist/cli.mjs.map +1 -0
  9. package/dist/client-612RJJD_.mjs +1069 -0
  10. package/dist/client-612RJJD_.mjs.map +1 -0
  11. package/dist/commands/contract-emit.d.mts +7 -0
  12. package/dist/commands/contract-emit.d.mts.map +1 -0
  13. package/dist/commands/contract-emit.mjs +4 -0
  14. package/dist/commands/contract-infer.d.mts +7 -0
  15. package/dist/commands/contract-infer.d.mts.map +1 -0
  16. package/dist/commands/contract-infer.mjs +4 -0
  17. package/dist/commands/db-init.d.mts +7 -0
  18. package/dist/commands/db-init.d.mts.map +1 -0
  19. package/dist/commands/db-init.mjs +124 -0
  20. package/dist/commands/db-init.mjs.map +1 -0
  21. package/dist/commands/db-schema.d.mts +7 -0
  22. package/dist/commands/db-schema.d.mts.map +1 -0
  23. package/dist/commands/db-schema.mjs +52 -0
  24. package/dist/commands/db-schema.mjs.map +1 -0
  25. package/dist/commands/db-sign.d.mts +7 -0
  26. package/dist/commands/db-sign.d.mts.map +1 -0
  27. package/dist/commands/db-sign.mjs +135 -0
  28. package/dist/commands/db-sign.mjs.map +1 -0
  29. package/dist/commands/db-update.d.mts +7 -0
  30. package/dist/commands/db-update.d.mts.map +1 -0
  31. package/dist/commands/db-update.mjs +121 -0
  32. package/dist/commands/db-update.mjs.map +1 -0
  33. package/dist/commands/db-verify.d.mts +7 -0
  34. package/dist/commands/db-verify.d.mts.map +1 -0
  35. package/dist/commands/db-verify.mjs +310 -0
  36. package/dist/commands/db-verify.mjs.map +1 -0
  37. package/dist/commands/migration-apply.d.mts +36 -0
  38. package/dist/commands/migration-apply.d.mts.map +1 -0
  39. package/dist/commands/migration-apply.mjs +240 -0
  40. package/dist/commands/migration-apply.mjs.map +1 -0
  41. package/dist/commands/migration-plan.d.mts +47 -0
  42. package/dist/commands/migration-plan.d.mts.map +1 -0
  43. package/dist/commands/migration-plan.mjs +288 -0
  44. package/dist/commands/migration-plan.mjs.map +1 -0
  45. package/dist/commands/migration-ref.d.mts +43 -0
  46. package/dist/commands/migration-ref.d.mts.map +1 -0
  47. package/dist/commands/migration-ref.mjs +194 -0
  48. package/dist/commands/migration-ref.mjs.map +1 -0
  49. package/dist/commands/migration-show.d.mts +28 -0
  50. package/dist/commands/migration-show.d.mts.map +1 -0
  51. package/dist/commands/migration-show.mjs +139 -0
  52. package/dist/commands/migration-show.mjs.map +1 -0
  53. package/dist/commands/migration-status.d.mts +85 -0
  54. package/dist/commands/migration-status.d.mts.map +1 -0
  55. package/dist/commands/migration-status.mjs +4 -0
  56. package/dist/commands/migration-verify.d.mts +16 -0
  57. package/dist/commands/migration-verify.d.mts.map +1 -0
  58. package/dist/commands/migration-verify.mjs +87 -0
  59. package/dist/commands/migration-verify.mjs.map +1 -0
  60. package/dist/config-loader-d_KF19Tw.mjs +43 -0
  61. package/dist/config-loader-d_KF19Tw.mjs.map +1 -0
  62. package/dist/{config-loader.d.ts → config-loader.d.mts} +8 -3
  63. package/dist/config-loader.d.mts.map +1 -0
  64. package/dist/config-loader.mjs +3 -0
  65. package/dist/contract-emit-CVv7dbQ9.mjs +187 -0
  66. package/dist/contract-emit-CVv7dbQ9.mjs.map +1 -0
  67. package/dist/contract-infer-Bvw8u8Eu.mjs +83 -0
  68. package/dist/contract-infer-Bvw8u8Eu.mjs.map +1 -0
  69. package/dist/exports/config-types.d.mts +2 -0
  70. package/dist/exports/config-types.mjs +3 -0
  71. package/dist/exports/control-api.d.mts +626 -0
  72. package/dist/exports/control-api.d.mts.map +1 -0
  73. package/dist/exports/control-api.mjs +107 -0
  74. package/dist/exports/control-api.mjs.map +1 -0
  75. package/dist/{load-ts-contract.d.ts → exports/index.d.mts} +10 -5
  76. package/dist/exports/index.d.mts.map +1 -0
  77. package/dist/exports/index.mjs +130 -0
  78. package/dist/exports/index.mjs.map +1 -0
  79. package/dist/extract-sql-ddl-Jf5blEO0.mjs +26 -0
  80. package/dist/extract-sql-ddl-Jf5blEO0.mjs.map +1 -0
  81. package/dist/framework-components-M2j-qPfr.mjs +59 -0
  82. package/dist/framework-components-M2j-qPfr.mjs.map +1 -0
  83. package/dist/inspect-live-schema-BQe5i4YE.mjs +90 -0
  84. package/dist/inspect-live-schema-BQe5i4YE.mjs.map +1 -0
  85. package/dist/migration-command-scaffold-SLrjcKXS.mjs +104 -0
  86. package/dist/migration-command-scaffold-SLrjcKXS.mjs.map +1 -0
  87. package/dist/migration-status-B7OVZ-Ka.mjs +1576 -0
  88. package/dist/migration-status-B7OVZ-Ka.mjs.map +1 -0
  89. package/dist/migrations-Db_ea9eE.mjs +173 -0
  90. package/dist/migrations-Db_ea9eE.mjs.map +1 -0
  91. package/dist/progress-adapter-DRNe2idZ.mjs +43 -0
  92. package/dist/progress-adapter-DRNe2idZ.mjs.map +1 -0
  93. package/dist/terminal-ui-DAcMBRKf.mjs +980 -0
  94. package/dist/terminal-ui-DAcMBRKf.mjs.map +1 -0
  95. package/dist/verify-DXKxBFvU.mjs +385 -0
  96. package/dist/verify-DXKxBFvU.mjs.map +1 -0
  97. package/package.json +88 -43
  98. package/src/cli.ts +109 -58
  99. package/src/commands/contract-emit.ts +236 -143
  100. package/src/commands/contract-infer-paths.ts +32 -0
  101. package/src/commands/contract-infer.ts +131 -0
  102. package/src/commands/db-init.ts +211 -425
  103. package/src/commands/db-schema.ts +77 -0
  104. package/src/commands/db-sign.ts +207 -228
  105. package/src/commands/db-update.ts +236 -0
  106. package/src/commands/db-verify.ts +484 -186
  107. package/src/commands/inspect-live-schema.ts +171 -0
  108. package/src/commands/migration-apply.ts +416 -0
  109. package/src/commands/migration-plan.ts +451 -0
  110. package/src/commands/migration-ref.ts +305 -0
  111. package/src/commands/migration-show.ts +246 -0
  112. package/src/commands/migration-status.ts +838 -0
  113. package/src/commands/migration-verify.ts +134 -0
  114. package/src/config-loader.ts +13 -3
  115. package/src/control-api/client.ts +614 -0
  116. package/src/control-api/contract-enrichment.ts +135 -0
  117. package/src/control-api/errors.ts +9 -0
  118. package/src/control-api/operations/contract-emit.ts +173 -0
  119. package/src/control-api/operations/db-init.ts +286 -0
  120. package/src/control-api/operations/db-update.ts +221 -0
  121. package/src/control-api/operations/extract-sql-ddl.ts +47 -0
  122. package/src/control-api/operations/migration-apply.ts +194 -0
  123. package/src/control-api/operations/migration-helpers.ts +49 -0
  124. package/src/control-api/types.ts +683 -0
  125. package/src/exports/config-types.ts +4 -3
  126. package/src/exports/control-api.ts +56 -0
  127. package/src/load-ts-contract.ts +16 -11
  128. package/src/utils/cli-errors.ts +5 -2
  129. package/src/utils/command-helpers.ts +293 -3
  130. package/src/utils/formatters/emit.ts +67 -0
  131. package/src/utils/formatters/errors.ts +82 -0
  132. package/src/utils/formatters/graph-migration-mapper.ts +220 -0
  133. package/src/utils/formatters/graph-render.ts +1317 -0
  134. package/src/utils/formatters/graph-types.ts +114 -0
  135. package/src/utils/formatters/help.ts +380 -0
  136. package/src/utils/formatters/helpers.ts +28 -0
  137. package/src/utils/formatters/migrations.ts +346 -0
  138. package/src/utils/formatters/styled.ts +212 -0
  139. package/src/utils/formatters/verify.ts +620 -0
  140. package/src/utils/global-flags.ts +41 -23
  141. package/src/utils/migration-command-scaffold.ts +187 -0
  142. package/src/utils/migration-types.ts +12 -0
  143. package/src/utils/progress-adapter.ts +75 -0
  144. package/src/utils/result-handler.ts +12 -13
  145. package/src/utils/shutdown.ts +92 -0
  146. package/src/utils/suggest-command.ts +31 -0
  147. package/src/utils/terminal-ui.ts +276 -0
  148. package/dist/chunk-BZMBKEEQ.js +0 -997
  149. package/dist/chunk-BZMBKEEQ.js.map +0 -1
  150. package/dist/chunk-CVNWLFXO.js +0 -91
  151. package/dist/chunk-CVNWLFXO.js.map +0 -1
  152. package/dist/chunk-HWYQOCAJ.js +0 -47
  153. package/dist/chunk-HWYQOCAJ.js.map +0 -1
  154. package/dist/chunk-QUPBU4KV.js +0 -131
  155. package/dist/chunk-QUPBU4KV.js.map +0 -1
  156. package/dist/cli.d.ts +0 -2
  157. package/dist/cli.d.ts.map +0 -1
  158. package/dist/cli.js.map +0 -1
  159. package/dist/commands/contract-emit.d.ts +0 -3
  160. package/dist/commands/contract-emit.d.ts.map +0 -1
  161. package/dist/commands/contract-emit.js +0 -9
  162. package/dist/commands/contract-emit.js.map +0 -1
  163. package/dist/commands/db-init.d.ts +0 -3
  164. package/dist/commands/db-init.d.ts.map +0 -1
  165. package/dist/commands/db-init.js +0 -337
  166. package/dist/commands/db-init.js.map +0 -1
  167. package/dist/commands/db-introspect.d.ts +0 -3
  168. package/dist/commands/db-introspect.d.ts.map +0 -1
  169. package/dist/commands/db-introspect.js +0 -186
  170. package/dist/commands/db-introspect.js.map +0 -1
  171. package/dist/commands/db-schema-verify.d.ts +0 -3
  172. package/dist/commands/db-schema-verify.d.ts.map +0 -1
  173. package/dist/commands/db-schema-verify.js +0 -160
  174. package/dist/commands/db-schema-verify.js.map +0 -1
  175. package/dist/commands/db-sign.d.ts +0 -3
  176. package/dist/commands/db-sign.d.ts.map +0 -1
  177. package/dist/commands/db-sign.js +0 -195
  178. package/dist/commands/db-sign.js.map +0 -1
  179. package/dist/commands/db-verify.d.ts +0 -3
  180. package/dist/commands/db-verify.d.ts.map +0 -1
  181. package/dist/commands/db-verify.js +0 -169
  182. package/dist/commands/db-verify.js.map +0 -1
  183. package/dist/config-loader.d.ts.map +0 -1
  184. package/dist/config-loader.js +0 -7
  185. package/dist/config-loader.js.map +0 -1
  186. package/dist/exports/config-types.d.ts +0 -3
  187. package/dist/exports/config-types.d.ts.map +0 -1
  188. package/dist/exports/config-types.js +0 -6
  189. package/dist/exports/config-types.js.map +0 -1
  190. package/dist/exports/index.d.ts +0 -4
  191. package/dist/exports/index.d.ts.map +0 -1
  192. package/dist/exports/index.js +0 -175
  193. package/dist/exports/index.js.map +0 -1
  194. package/dist/load-ts-contract.d.ts.map +0 -1
  195. package/dist/utils/action.d.ts +0 -16
  196. package/dist/utils/action.d.ts.map +0 -1
  197. package/dist/utils/cli-errors.d.ts +0 -7
  198. package/dist/utils/cli-errors.d.ts.map +0 -1
  199. package/dist/utils/command-helpers.d.ts +0 -12
  200. package/dist/utils/command-helpers.d.ts.map +0 -1
  201. package/dist/utils/framework-components.d.ts +0 -70
  202. package/dist/utils/framework-components.d.ts.map +0 -1
  203. package/dist/utils/global-flags.d.ts +0 -25
  204. package/dist/utils/global-flags.d.ts.map +0 -1
  205. package/dist/utils/output.d.ts +0 -142
  206. package/dist/utils/output.d.ts.map +0 -1
  207. package/dist/utils/result-handler.d.ts +0 -15
  208. package/dist/utils/result-handler.d.ts.map +0 -1
  209. package/dist/utils/spinner.d.ts +0 -29
  210. package/dist/utils/spinner.d.ts.map +0 -1
  211. package/src/commands/db-introspect.ts +0 -256
  212. package/src/commands/db-schema-verify.ts +0 -232
  213. package/src/utils/action.ts +0 -43
  214. package/src/utils/output.ts +0 -1471
  215. package/src/utils/spinner.ts +0 -67
@@ -1,452 +1,238 @@
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 { createControlPlaneStack } from '@prisma-next/core-control-plane/types';
10
- 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';
11
3
  import { Command } from 'commander';
12
- import { loadConfig } from '../config-loader';
13
- import { performAction } from '../utils/action';
4
+ import { ContractValidationError } from '../control-api/errors';
5
+ import type { DbInitFailure } from '../control-api/types';
14
6
  import {
7
+ CliStructuredError,
15
8
  errorContractValidationFailed,
16
- errorDatabaseUrlRequired,
17
- errorDriverRequired,
18
- errorFileNotFound,
19
- errorJsonFormatNotSupported,
20
9
  errorMigrationPlanningFailed,
10
+ errorRunnerFailed,
21
11
  errorRuntime,
22
- errorTargetMigrationNotSupported,
23
12
  errorUnexpected,
24
13
  } from '../utils/cli-errors';
25
- import { setCommandDescriptions } from '../utils/command-helpers';
14
+ import type { MigrationCommandOptions } from '../utils/command-helpers';
26
15
  import {
27
- assertContractRequirementsSatisfied,
28
- assertFrameworkComponentsCompatible,
29
- } from '../utils/framework-components';
30
- import { parseGlobalFlags } from '../utils/global-flags';
16
+ sanitizeErrorMessage,
17
+ setCommandDescriptions,
18
+ setCommandExamples,
19
+ } from '../utils/command-helpers';
31
20
  import {
32
- type DbInitResult,
33
- formatCommandHelp,
34
- formatDbInitApplyOutput,
35
- formatDbInitJson,
36
- formatDbInitPlanOutput,
37
- formatStyledHeader,
38
- } from '../utils/output';
21
+ formatMigrationApplyOutput,
22
+ formatMigrationJson,
23
+ formatMigrationPlanOutput,
24
+ type MigrationCommandResult,
25
+ } from '../utils/formatters/migrations';
26
+ import { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';
27
+ import {
28
+ addMigrationCommandOptions,
29
+ prepareMigrationContext,
30
+ } from '../utils/migration-command-scaffold';
39
31
  import { handleResult } from '../utils/result-handler';
40
- import { withSpinner } from '../utils/spinner';
32
+ import { TerminalUI } from '../utils/terminal-ui';
33
+
34
+ type DbInitOptions = MigrationCommandOptions;
35
+
36
+ /**
37
+ * Maps a DbInitFailure to a CliStructuredError for consistent error handling.
38
+ */
39
+ function mapDbInitFailure(failure: DbInitFailure): CliStructuredError {
40
+ if (failure.code === 'PLANNING_FAILED') {
41
+ return errorMigrationPlanningFailed({ conflicts: failure.conflicts ?? [] });
42
+ }
43
+
44
+ if (failure.code === 'MARKER_ORIGIN_MISMATCH') {
45
+ const mismatchParts: string[] = [];
46
+ if (
47
+ failure.marker?.storageHash !== failure.destination?.storageHash &&
48
+ failure.marker?.storageHash &&
49
+ failure.destination?.storageHash
50
+ ) {
51
+ mismatchParts.push(
52
+ `storageHash (marker: ${failure.marker.storageHash}, destination: ${failure.destination.storageHash})`,
53
+ );
54
+ }
55
+ if (
56
+ failure.marker?.profileHash !== failure.destination?.profileHash &&
57
+ failure.marker?.profileHash &&
58
+ failure.destination?.profileHash
59
+ ) {
60
+ mismatchParts.push(
61
+ `profileHash (marker: ${failure.marker.profileHash}, destination: ${failure.destination.profileHash})`,
62
+ );
63
+ }
64
+
65
+ return errorRuntime(
66
+ `Existing database signature does not match plan destination.${mismatchParts.length > 0 ? ` Mismatch in ${mismatchParts.join(' and ')}.` : ''}`,
67
+ {
68
+ why: 'Database has an existing signature (marker) that does not match the target contract',
69
+ fix: 'If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow',
70
+ meta: {
71
+ code: 'MARKER_ORIGIN_MISMATCH',
72
+ ...ifDefined('markerStorageHash', failure.marker?.storageHash),
73
+ ...ifDefined('destinationStorageHash', failure.destination?.storageHash),
74
+ ...ifDefined('markerProfileHash', failure.marker?.profileHash),
75
+ ...ifDefined('destinationProfileHash', failure.destination?.profileHash),
76
+ },
77
+ },
78
+ );
79
+ }
80
+
81
+ if (failure.code === 'RUNNER_FAILED') {
82
+ return errorRunnerFailed(failure.summary, {
83
+ why: failure.why ?? 'Migration runner failed',
84
+ fix: 'Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`',
85
+ ...(failure.meta
86
+ ? { meta: { code: 'RUNNER_FAILED', ...failure.meta } }
87
+ : { meta: { code: 'RUNNER_FAILED' } }),
88
+ });
89
+ }
41
90
 
42
- interface DbInitOptions {
43
- readonly db?: string;
44
- readonly config?: string;
45
- readonly plan?: boolean;
46
- readonly json?: string | boolean;
47
- readonly quiet?: boolean;
48
- readonly q?: boolean;
49
- readonly verbose?: boolean;
50
- readonly v?: boolean;
51
- readonly vv?: boolean;
52
- readonly trace?: boolean;
53
- readonly timestamps?: boolean;
54
- readonly color?: boolean;
55
- readonly 'no-color'?: boolean;
91
+ // Exhaustive check - TypeScript will error if a new code is added but not handled
92
+ const exhaustive: never = failure.code;
93
+ throw new Error(`Unhandled DbInitFailure code: ${exhaustive}`);
94
+ }
95
+
96
+ /**
97
+ * Executes the db init command and returns a structured Result.
98
+ */
99
+ async function executeDbInitCommand(
100
+ options: DbInitOptions,
101
+ flags: GlobalFlags,
102
+ ui: TerminalUI,
103
+ startTime: number,
104
+ ): Promise<Result<MigrationCommandResult, CliStructuredError>> {
105
+ // Prepare shared migration context (config, contract, connection, client)
106
+ const ctxResult = await prepareMigrationContext(options, flags, ui, {
107
+ commandName: 'db init',
108
+ description: 'Bootstrap a database to match the current contract',
109
+ url: 'https://pris.ly/db-init',
110
+ });
111
+ if (!ctxResult.ok) {
112
+ return ctxResult;
113
+ }
114
+ const { client, contractJson, dbConnection, onProgress, contractPathAbsolute } = ctxResult.value;
115
+
116
+ try {
117
+ // Call dbInit with connection and progress callback
118
+ const result = await client.dbInit({
119
+ contractIR: contractJson,
120
+ mode: options.dryRun ? 'plan' : 'apply',
121
+ connection: dbConnection,
122
+ onProgress,
123
+ });
124
+
125
+ // Handle failures by mapping to CLI structured error
126
+ if (!result.ok) {
127
+ return notOk(mapDbInitFailure(result.failure));
128
+ }
129
+
130
+ // Convert success result to CLI output format
131
+ const dbInitResult: MigrationCommandResult = {
132
+ ok: true,
133
+ mode: result.value.mode,
134
+ plan: {
135
+ targetId: ctxResult.value.config.target.targetId,
136
+ destination: {
137
+ storageHash: result.value.destination.storageHash,
138
+ ...ifDefined('profileHash', result.value.destination.profileHash),
139
+ },
140
+ operations: result.value.plan.operations.map((op) => ({
141
+ id: op.id,
142
+ label: op.label,
143
+ operationClass: op.operationClass,
144
+ })),
145
+ },
146
+ ...(result.value.execution
147
+ ? {
148
+ execution: {
149
+ operationsPlanned: result.value.execution.operationsPlanned,
150
+ operationsExecuted: result.value.execution.operationsExecuted,
151
+ },
152
+ }
153
+ : {}),
154
+ ...(result.value.marker
155
+ ? {
156
+ marker: {
157
+ storageHash: result.value.marker.storageHash,
158
+ ...ifDefined('profileHash', result.value.marker.profileHash),
159
+ },
160
+ }
161
+ : {}),
162
+ summary: result.value.summary,
163
+ timings: { total: Date.now() - startTime },
164
+ };
165
+
166
+ return ok(dbInitResult);
167
+ } catch (error) {
168
+ // Driver already throws CliStructuredError for connection failures
169
+ if (CliStructuredError.is(error)) {
170
+ return notOk(error);
171
+ }
172
+
173
+ if (error instanceof ContractValidationError) {
174
+ return notOk(
175
+ errorContractValidationFailed(`Contract validation failed: ${error.message}`, {
176
+ where: { path: contractPathAbsolute },
177
+ }),
178
+ );
179
+ }
180
+
181
+ const rawMessage = error instanceof Error ? error.message : String(error);
182
+ const safeMessage = sanitizeErrorMessage(
183
+ rawMessage,
184
+ typeof dbConnection === 'string' ? dbConnection : undefined,
185
+ );
186
+ return notOk(
187
+ errorUnexpected(safeMessage, {
188
+ why: `Unexpected error during db init: ${safeMessage}`,
189
+ }),
190
+ );
191
+ } finally {
192
+ await client.close();
193
+ }
56
194
  }
57
195
 
58
196
  export function createDbInitCommand(): Command {
59
197
  const command = new Command('init');
60
198
  setCommandDescriptions(
61
199
  command,
62
- 'Bootstrap a database to match the current contract and write the contract marker',
200
+ 'Bootstrap a database to match the current contract and sign it',
63
201
  'Initializes a database to match your emitted contract using additive-only operations.\n' +
64
202
  'Creates any missing tables, columns, indexes, and constraints defined in your contract.\n' +
65
203
  'Leaves existing compatible structures in place, surfaces conflicts when destructive changes\n' +
66
- 'would be required, and writes a contract marker to track the database state. Use --plan to\n' +
204
+ 'would be required, and signs the database to track contract state. Use --dry-run to\n' +
67
205
  'preview changes without applying.',
68
206
  );
69
- command
70
- .configureHelp({
71
- formatHelp: (cmd) => {
72
- const flags = parseGlobalFlags({});
73
- return formatCommandHelp({ command: cmd, flags });
74
- },
75
- })
76
- .option('--db <url>', 'Database connection string')
77
- .option('--config <path>', 'Path to prisma-next.config.ts')
78
- .option('--plan', 'Preview planned operations without applying', false)
79
- .option('--json [format]', 'Output as JSON (object)', false)
80
- .option('-q, --quiet', 'Quiet mode: errors only')
81
- .option('-v, --verbose', 'Verbose output: debug info, timings')
82
- .option('-vv, --trace', 'Trace output: deep internals, stack traces')
83
- .option('--timestamps', 'Add timestamps to output')
84
- .option('--color', 'Force color output')
85
- .option('--no-color', 'Disable color output')
86
- .action(async (options: DbInitOptions) => {
87
- const flags = parseGlobalFlags(options);
88
- const startTime = Date.now();
89
-
90
- const result = await performAction(async () => {
91
- if (flags.json === 'ndjson') {
92
- throw errorJsonFormatNotSupported({
93
- command: 'db init',
94
- format: 'ndjson',
95
- supportedFormats: ['object'],
96
- });
207
+ setCommandExamples(command, [
208
+ 'prisma-next db init --db $DATABASE_URL',
209
+ 'prisma-next db init --db $DATABASE_URL --dry-run',
210
+ ]);
211
+ addMigrationCommandOptions(command);
212
+ command.action(async (options: DbInitOptions) => {
213
+ const flags = parseGlobalFlags(options);
214
+ const startTime = Date.now();
215
+
216
+ const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });
217
+
218
+ const result = await executeDbInitCommand(options, flags, ui, startTime);
219
+
220
+ const exitCode = handleResult(result, flags, ui, (dbInitResult) => {
221
+ if (flags.json) {
222
+ ui.output(formatMigrationJson(dbInitResult));
223
+ } else {
224
+ const output =
225
+ dbInitResult.mode === 'plan'
226
+ ? formatMigrationPlanOutput(dbInitResult, flags)
227
+ : formatMigrationApplyOutput(dbInitResult, flags);
228
+ if (output) {
229
+ ui.log(output);
97
230
  }
98
-
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
- });
432
-
433
- // Handle result
434
- const exitCode = handleResult(result, flags, (dbInitResult) => {
435
- if (flags.json === 'object') {
436
- console.log(formatDbInitJson(dbInitResult));
437
- } else {
438
- const output =
439
- dbInitResult.mode === 'plan'
440
- ? formatDbInitPlanOutput(dbInitResult, flags)
441
- : formatDbInitApplyOutput(dbInitResult, flags);
442
- if (output) {
443
- console.log(output);
444
- }
445
- }
446
- });
447
-
448
- process.exit(exitCode);
231
+ }
449
232
  });
450
233
 
234
+ process.exit(exitCode);
235
+ });
236
+
451
237
  return command;
452
238
  }