@prisma-next/cli 0.3.0-dev.7 → 0.3.0-dev.70

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 +203 -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 +151 -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 +134 -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 +118 -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 +120 -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 +142 -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 +123 -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 +133 -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 +250 -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 +260 -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 +98 -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 +135 -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 +74 -37
  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,25 +1,29 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { relative, resolve } from 'node:path';
3
- import {
4
- errorDatabaseUrlRequired,
5
- errorDriverRequired,
6
- errorFileNotFound,
7
- errorRuntime,
8
- errorUnexpected,
9
- } from '@prisma-next/core-control-plane/errors';
10
3
  import type {
11
4
  SignDatabaseResult,
12
5
  VerifyDatabaseSchemaResult,
13
6
  } from '@prisma-next/core-control-plane/types';
7
+ import { notOk, ok, type Result } from '@prisma-next/utils/result';
14
8
  import { Command } from 'commander';
15
9
  import { loadConfig } from '../config-loader';
16
- import { performAction } from '../utils/action';
17
- import { setCommandDescriptions } from '../utils/command-helpers';
10
+ import { createControlClient } from '../control-api/client';
11
+ import { ContractValidationError } from '../control-api/errors';
12
+ import {
13
+ CliStructuredError,
14
+ errorContractValidationFailed,
15
+ errorDatabaseConnectionRequired,
16
+ errorDriverRequired,
17
+ errorFileNotFound,
18
+ errorJsonFormatNotSupported,
19
+ errorUnexpected,
20
+ } from '../utils/cli-errors';
18
21
  import {
19
- assertContractRequirementsSatisfied,
20
- assertFrameworkComponentsCompatible,
21
- } from '../utils/framework-components';
22
- import { parseGlobalFlags } from '../utils/global-flags';
22
+ maskConnectionUrl,
23
+ resolveContractPath,
24
+ setCommandDescriptions,
25
+ } from '../utils/command-helpers';
26
+ import { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';
23
27
  import {
24
28
  formatCommandHelp,
25
29
  formatSchemaVerifyJson,
@@ -28,8 +32,8 @@ import {
28
32
  formatSignOutput,
29
33
  formatStyledHeader,
30
34
  } from '../utils/output';
35
+ import { createProgressAdapter } from '../utils/progress-adapter';
31
36
  import { handleResult } from '../utils/result-handler';
32
- import { withSpinner } from '../utils/spinner';
33
37
 
34
38
  interface DbSignOptions {
35
39
  readonly db?: string;
@@ -46,14 +50,172 @@ interface DbSignOptions {
46
50
  readonly 'no-color'?: boolean;
47
51
  }
48
52
 
53
+ /**
54
+ * Failure type for db sign command.
55
+ * Either an infrastructure error (CliStructuredError) or a logical failure (schema verification failed).
56
+ */
57
+ type DbSignFailure = CliStructuredError | VerifyDatabaseSchemaResult;
58
+
59
+ /**
60
+ * Executes the db sign command and returns a structured Result.
61
+ * Success: SignDatabaseResult (sign happened)
62
+ * Failure: CliStructuredError (infra error) or VerifyDatabaseSchemaResult (schema mismatch)
63
+ */
64
+ async function executeDbSignCommand(
65
+ options: DbSignOptions,
66
+ flags: GlobalFlags,
67
+ ): Promise<Result<SignDatabaseResult, DbSignFailure>> {
68
+ // Load config
69
+ const config = await loadConfig(options.config);
70
+ const configPath = options.config
71
+ ? relative(process.cwd(), resolve(options.config))
72
+ : 'prisma-next.config.ts';
73
+ const contractPathAbsolute = resolveContractPath(config);
74
+ const contractPath = relative(process.cwd(), contractPathAbsolute);
75
+
76
+ // Output header
77
+ if (flags.json !== 'object' && !flags.quiet) {
78
+ const details: Array<{ label: string; value: string }> = [
79
+ { label: 'config', value: configPath },
80
+ { label: 'contract', value: contractPath },
81
+ ];
82
+ if (options.db) {
83
+ details.push({ label: 'database', value: maskConnectionUrl(options.db) });
84
+ }
85
+ const header = formatStyledHeader({
86
+ command: 'db sign',
87
+ description: 'Sign the database with your contract so you can safely run queries',
88
+ url: 'https://pris.ly/db-sign',
89
+ details,
90
+ flags,
91
+ });
92
+ console.log(header);
93
+ }
94
+
95
+ // Load contract file
96
+ let contractJsonContent: string;
97
+ try {
98
+ contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
99
+ } catch (error) {
100
+ if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
101
+ return notOk(
102
+ errorFileNotFound(contractPathAbsolute, {
103
+ why: `Contract file not found at ${contractPathAbsolute}`,
104
+ fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`,
105
+ }),
106
+ );
107
+ }
108
+ return notOk(
109
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
110
+ why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
111
+ }),
112
+ );
113
+ }
114
+
115
+ let contractJson: Record<string, unknown>;
116
+ try {
117
+ contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
118
+ } catch (error) {
119
+ return notOk(
120
+ errorContractValidationFailed(
121
+ `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
122
+ { where: { path: contractPathAbsolute } },
123
+ ),
124
+ );
125
+ }
126
+
127
+ // Resolve database connection (--db flag or config.db.connection)
128
+ const dbConnection = options.db ?? config.db?.connection;
129
+ if (!dbConnection) {
130
+ return notOk(
131
+ errorDatabaseConnectionRequired({
132
+ why: `Database connection is required for db sign (set db.connection in ${configPath}, or pass --db <url>)`,
133
+ }),
134
+ );
135
+ }
136
+
137
+ // Check for driver
138
+ if (!config.driver) {
139
+ return notOk(errorDriverRequired({ why: 'Config.driver is required for db sign' }));
140
+ }
141
+
142
+ // Create control client
143
+ const client = createControlClient({
144
+ family: config.family,
145
+ target: config.target,
146
+ adapter: config.adapter,
147
+ driver: config.driver,
148
+ extensionPacks: config.extensionPacks ?? [],
149
+ });
150
+
151
+ // Create progress adapter
152
+ const onProgress = createProgressAdapter({ flags });
153
+
154
+ try {
155
+ // Step 1: Schema verification - connect here
156
+ const schemaVerifyResult = await client.schemaVerify({
157
+ contractIR: contractJson,
158
+ strict: false,
159
+ connection: dbConnection,
160
+ onProgress,
161
+ });
162
+
163
+ // If schema verification failed, return as failure
164
+ if (!schemaVerifyResult.ok) {
165
+ // Add blank line after all async operations if spinners were shown
166
+ if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
167
+ console.log('');
168
+ }
169
+ return notOk(schemaVerifyResult);
170
+ }
171
+
172
+ // Step 2: Sign (already connected from schemaVerify)
173
+ const signResult = await client.sign({
174
+ contractIR: contractJson,
175
+ contractPath,
176
+ configPath,
177
+ onProgress,
178
+ });
179
+
180
+ // Add blank line after all async operations if spinners were shown
181
+ if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
182
+ console.log('');
183
+ }
184
+
185
+ return ok(signResult);
186
+ } catch (error) {
187
+ // Driver already throws CliStructuredError for connection failures
188
+ if (error instanceof CliStructuredError) {
189
+ return notOk(error);
190
+ }
191
+
192
+ if (error instanceof ContractValidationError) {
193
+ return notOk(
194
+ errorContractValidationFailed(`Contract validation failed: ${error.message}`, {
195
+ where: { path: contractPathAbsolute },
196
+ }),
197
+ );
198
+ }
199
+
200
+ // Wrap unexpected errors
201
+ return notOk(
202
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
203
+ why: `Unexpected error during db sign: ${error instanceof Error ? error.message : String(error)}`,
204
+ }),
205
+ );
206
+ } finally {
207
+ await client.close();
208
+ }
209
+ }
210
+
49
211
  export function createDbSignCommand(): Command {
50
212
  const command = new Command('sign');
51
213
  setCommandDescriptions(
52
214
  command,
53
215
  'Sign the database with your contract so you can safely run queries',
54
216
  'Verifies that your database schema satisfies the emitted contract, and if so, writes or\n' +
55
- 'updates the contract marker in the database. This command is idempotent and safe to run\n' +
56
- 'in CI/deployment pipelines. The marker records that this database instance is aligned\n' +
217
+ 'updates the database signature. This command is idempotent and safe to run\n' +
218
+ 'in CI/deployment pipelines. The signature records that this database instance is aligned\n' +
57
219
  'with a specific contract version.',
58
220
  );
59
221
  command
@@ -65,7 +227,7 @@ export function createDbSignCommand(): Command {
65
227
  })
66
228
  .option('--db <url>', 'Database connection string')
67
229
  .option('--config <path>', 'Path to prisma-next.config.ts')
68
- .option('--json [format]', 'Output as JSON (object or ndjson)', false)
230
+ .option('--json [format]', 'Output as JSON (object)', false)
69
231
  .option('-q, --quiet', 'Quiet mode: errors only')
70
232
  .option('-v, --verbose', 'Verbose output: debug info, timings')
71
233
  .option('-vv, --trace', 'Trace output: deep internals, stack traces')
@@ -75,202 +237,53 @@ export function createDbSignCommand(): Command {
75
237
  .action(async (options: DbSignOptions) => {
76
238
  const flags = parseGlobalFlags(options);
77
239
 
78
- const result = await performAction(async () => {
79
- // Load config (file I/O)
80
- const config = await loadConfig(options.config);
81
- // Normalize config path for display (match contract path format - no ./ prefix)
82
- const configPath = options.config
83
- ? relative(process.cwd(), resolve(options.config))
84
- : 'prisma-next.config.ts';
85
- const contractPathAbsolute = config.contract?.output
86
- ? resolve(config.contract.output)
87
- : resolve('src/prisma/contract.json');
88
- // Convert to relative path for display
89
- const contractPath = relative(process.cwd(), contractPathAbsolute);
90
-
91
- // Output header (only for human-readable output)
92
- if (flags.json !== 'object' && !flags.quiet) {
93
- const details: Array<{ label: string; value: string }> = [
94
- { label: 'config', value: configPath },
95
- { label: 'contract', value: contractPath },
96
- ];
97
- if (options.db) {
98
- details.push({ label: 'database', value: options.db });
99
- }
100
- const header = formatStyledHeader({
240
+ // Validate JSON format option
241
+ if (flags.json === 'ndjson') {
242
+ const result = notOk(
243
+ errorJsonFormatNotSupported({
101
244
  command: 'db sign',
102
- description: 'Sign the database with your contract so you can safely run queries',
103
- url: 'https://pris.ly/db-sign',
104
- details,
105
- flags,
106
- });
107
- console.log(header);
108
- }
109
-
110
- // Load contract file (file I/O)
111
- let contractJsonContent: string;
112
- try {
113
- contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
114
- } catch (error) {
115
- if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
116
- throw errorFileNotFound(contractPathAbsolute, {
117
- why: `Contract file not found at ${contractPathAbsolute}`,
118
- });
119
- }
120
- throw errorUnexpected(error instanceof Error ? error.message : String(error), {
121
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
122
- });
123
- }
124
- const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
125
-
126
- // Resolve database URL
127
- const dbUrl = options.db ?? config.db?.url;
128
- if (!dbUrl) {
129
- throw errorDatabaseUrlRequired();
130
- }
131
-
132
- // Check for driver
133
- if (!config.driver) {
134
- throw errorDriverRequired();
135
- }
136
-
137
- // Store driver descriptor after null check
138
- const driverDescriptor = config.driver;
139
-
140
- // Create family instance (needed for contract validation - no DB connection required)
141
- const familyInstance = config.family.create({
142
- target: config.target,
143
- adapter: config.adapter,
144
- driver: driverDescriptor,
145
- extensionPacks: config.extensionPacks ?? [],
146
- });
147
-
148
- // Validate contract using instance validator (fail-fast before DB connection)
149
- const contractIR = familyInstance.validateContractIR(contractJson);
150
- assertContractRequirementsSatisfied({
151
- contract: contractIR,
152
- family: config.family,
153
- target: config.target,
154
- adapter: config.adapter,
155
- extensionPacks: config.extensionPacks,
156
- });
157
-
158
- const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];
159
- const frameworkComponents = assertFrameworkComponentsCompatible(
160
- config.family.familyId,
161
- config.target.targetId,
162
- rawComponents,
245
+ format: 'ndjson',
246
+ supportedFormats: ['object'],
247
+ }),
163
248
  );
249
+ const exitCode = handleResult(result, flags);
250
+ process.exit(exitCode);
251
+ }
164
252
 
165
- // Create driver (expensive operation - done after validation)
166
- const driver = await driverDescriptor.create(dbUrl);
167
-
168
- try {
169
- // Schema verification precondition with spinner
170
- let schemaVerifyResult: VerifyDatabaseSchemaResult;
171
- try {
172
- schemaVerifyResult = await withSpinner(
173
- () =>
174
- familyInstance.schemaVerify({
175
- driver,
176
- contractIR,
177
- strict: false,
178
- contractPath: contractPathAbsolute,
179
- configPath,
180
- frameworkComponents,
181
- }),
182
- {
183
- message: 'Verifying database satisfies contract',
184
- flags,
185
- },
186
- );
187
- } catch (error) {
188
- // Wrap errors from schemaVerify() in structured error
189
- throw errorRuntime(error instanceof Error ? error.message : String(error), {
190
- why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`,
191
- });
192
- }
193
-
194
- // If schema verification failed, return both results for handling outside performAction
195
- if (!schemaVerifyResult.ok) {
196
- return { schemaVerifyResult, signResult: undefined };
197
- }
198
-
199
- // Schema verification passed - proceed with signing
200
- let signResult: SignDatabaseResult;
201
- try {
202
- signResult = await withSpinner(
203
- () =>
204
- familyInstance.sign({
205
- driver,
206
- contractIR,
207
- contractPath: contractPathAbsolute,
208
- configPath,
209
- }),
210
- {
211
- message: 'Signing database...',
212
- flags,
213
- },
214
- );
215
- } catch (error) {
216
- // Wrap errors from sign() in structured error
217
- throw errorRuntime(error instanceof Error ? error.message : String(error), {
218
- why: `Failed to sign database: ${error instanceof Error ? error.message : String(error)}`,
219
- });
220
- }
253
+ const result = await executeDbSignCommand(options, flags);
221
254
 
222
- // Add blank line after all async operations if spinners were shown
223
- if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
224
- console.log('');
255
+ if (result.ok) {
256
+ // Success - format sign output
257
+ if (flags.json === 'object') {
258
+ console.log(formatSignJson(result.value));
259
+ } else {
260
+ const output = formatSignOutput(result.value, flags);
261
+ if (output) {
262
+ console.log(output);
225
263
  }
226
-
227
- return { schemaVerifyResult: undefined, signResult };
228
- } finally {
229
- // Ensure driver connection is closed
230
- await driver.close();
231
264
  }
232
- });
265
+ process.exit(0);
266
+ }
233
267
 
234
- // Handle result - formats output and returns exit code
235
- const exitCode = handleResult(result, flags, (value) => {
236
- const { schemaVerifyResult, signResult } = value;
268
+ // Failure - determine type and handle appropriately
269
+ const failure = result.failure;
237
270
 
238
- // If schema verification failed, format and print schema verification output
239
- if (schemaVerifyResult && !schemaVerifyResult.ok) {
240
- if (flags.json === 'object') {
241
- console.log(formatSchemaVerifyJson(schemaVerifyResult));
242
- } else {
243
- const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);
244
- if (output) {
245
- console.log(output);
246
- }
247
- }
248
- // Don't proceed to sign output formatting
249
- return;
250
- }
251
-
252
- // Schema verification passed - format sign output
253
- if (signResult) {
254
- if (flags.json === 'object') {
255
- console.log(formatSignJson(signResult));
256
- } else {
257
- const output = formatSignOutput(signResult, flags);
258
- if (output) {
259
- console.log(output);
260
- }
261
- }
262
- }
263
- });
271
+ if (failure instanceof CliStructuredError) {
272
+ // Infrastructure error - use standard handler
273
+ const exitCode = handleResult(result as Result<never, CliStructuredError>, flags);
274
+ process.exit(exitCode);
275
+ }
264
276
 
265
- // For logical schema mismatches, check if schema verification passed
266
- // Infra errors already handled by handleResult (returns non-zero exit code)
267
- if (result.ok && result.value.schemaVerifyResult && !result.value.schemaVerifyResult.ok) {
268
- // Schema verification failed - exit with code 1
269
- process.exit(1);
277
+ // Schema verification failed - format and print schema verification output
278
+ if (flags.json === 'object') {
279
+ console.log(formatSchemaVerifyJson(failure));
270
280
  } else {
271
- // Success or infra error - use exit code from handleResult
272
- process.exit(exitCode);
281
+ const output = formatSchemaVerifyOutput(failure, flags);
282
+ if (output) {
283
+ console.log(output);
284
+ }
273
285
  }
286
+ process.exit(1);
274
287
  });
275
288
 
276
289
  return command;
@@ -0,0 +1,220 @@
1
+ import { ifDefined } from '@prisma-next/utils/defined';
2
+ import { notOk, ok, type Result } from '@prisma-next/utils/result';
3
+ import { Command } from 'commander';
4
+ import { ContractValidationError } from '../control-api/errors';
5
+ import type { DbUpdateFailure } from '../control-api/types';
6
+ import {
7
+ CliStructuredError,
8
+ errorContractValidationFailed,
9
+ errorDestructiveChanges,
10
+ errorJsonFormatNotSupported,
11
+ errorMigrationPlanningFailed,
12
+ errorRunnerFailed,
13
+ errorUnexpected,
14
+ } from '../utils/cli-errors';
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';
18
+ import {
19
+ addMigrationCommandOptions,
20
+ prepareMigrationContext,
21
+ } from '../utils/migration-command-scaffold';
22
+ import {
23
+ formatCommandHelp,
24
+ formatMigrationApplyOutput,
25
+ formatMigrationJson,
26
+ formatMigrationPlanOutput,
27
+ type MigrationCommandResult,
28
+ } from '../utils/output';
29
+ import { handleResult } from '../utils/result-handler';
30
+
31
+ type DbUpdateOptions = MigrationCommandOptions & {
32
+ readonly acceptDataLoss?: boolean;
33
+ };
34
+
35
+ /**
36
+ * Maps a DbUpdateFailure to a CliStructuredError for consistent error handling.
37
+ */
38
+ function mapDbUpdateFailure(failure: DbUpdateFailure): CliStructuredError {
39
+ if (failure.code === 'PLANNING_FAILED') {
40
+ return errorMigrationPlanningFailed({ conflicts: failure.conflicts ?? [] });
41
+ }
42
+
43
+ if (failure.code === 'RUNNER_FAILED') {
44
+ return errorRunnerFailed(failure.summary, {
45
+ why: failure.why ?? 'Migration runner failed',
46
+ fix: 'Inspect the reported conflict, reconcile schema drift if needed, then re-run `prisma-next db update`',
47
+ ...ifDefined('meta', failure.meta),
48
+ });
49
+ }
50
+
51
+ if (failure.code === 'DESTRUCTIVE_CHANGES') {
52
+ return errorDestructiveChanges(failure.summary, {
53
+ ...ifDefined('why', failure.why),
54
+ fix: 'Use `prisma-next db update --plan` to preview, then re-run with `--accept-data-loss` to apply destructive changes',
55
+ ...ifDefined('meta', failure.meta),
56
+ });
57
+ }
58
+
59
+ const exhaustive: never = failure.code;
60
+ throw new Error(`Unhandled DbUpdateFailure code: ${exhaustive}`);
61
+ }
62
+
63
+ /**
64
+ * Executes the db update command and returns a structured Result.
65
+ */
66
+ async function executeDbUpdateCommand(
67
+ options: DbUpdateOptions,
68
+ flags: GlobalFlags,
69
+ startTime: number,
70
+ ): Promise<Result<MigrationCommandResult, CliStructuredError>> {
71
+ // Prepare shared migration context (config, contract, connection, client)
72
+ const ctxResult = await prepareMigrationContext(options, flags, {
73
+ commandName: 'db update',
74
+ description: 'Update your database schema to match your contract',
75
+ url: 'https://pris.ly/db-update',
76
+ });
77
+ if (!ctxResult.ok) {
78
+ return ctxResult;
79
+ }
80
+ const { client, contractJson, dbConnection, onProgress, contractPathAbsolute } = ctxResult.value;
81
+
82
+ try {
83
+ // Call dbUpdate with connection and progress callback
84
+ const result = await client.dbUpdate({
85
+ contractIR: contractJson,
86
+ mode: options.plan ? 'plan' : 'apply',
87
+ connection: dbConnection,
88
+ ...(options.acceptDataLoss ? { acceptDataLoss: true } : {}),
89
+ onProgress,
90
+ });
91
+
92
+ // Handle failures by mapping to CLI structured error
93
+ if (!result.ok) {
94
+ return notOk(mapDbUpdateFailure(result.failure));
95
+ }
96
+
97
+ // Convert success result to CLI output format
98
+ const dbUpdateResult: MigrationCommandResult = {
99
+ ok: true,
100
+ mode: result.value.mode,
101
+ plan: {
102
+ targetId: ctxResult.value.config.target.targetId,
103
+ destination: {
104
+ storageHash: result.value.destination.storageHash,
105
+ ...ifDefined('profileHash', result.value.destination.profileHash),
106
+ },
107
+ operations: result.value.plan.operations.map((op) => ({
108
+ id: op.id,
109
+ label: op.label,
110
+ operationClass: op.operationClass,
111
+ })),
112
+ ...ifDefined('sql', result.value.plan.sql),
113
+ },
114
+ ...ifDefined(
115
+ 'execution',
116
+ result.value.execution
117
+ ? {
118
+ operationsPlanned: result.value.execution.operationsPlanned,
119
+ operationsExecuted: result.value.execution.operationsExecuted,
120
+ }
121
+ : undefined,
122
+ ),
123
+ ...ifDefined(
124
+ 'marker',
125
+ result.value.marker
126
+ ? {
127
+ storageHash: result.value.marker.storageHash,
128
+ ...ifDefined('profileHash', result.value.marker.profileHash),
129
+ }
130
+ : undefined,
131
+ ),
132
+ summary: result.value.summary,
133
+ timings: { total: Date.now() - startTime },
134
+ };
135
+
136
+ return ok(dbUpdateResult);
137
+ } catch (error) {
138
+ if (CliStructuredError.is(error)) {
139
+ return notOk(error);
140
+ }
141
+
142
+ if (error instanceof ContractValidationError) {
143
+ return notOk(
144
+ errorContractValidationFailed(`Contract validation failed: ${error.message}`, {
145
+ where: { path: contractPathAbsolute },
146
+ }),
147
+ );
148
+ }
149
+
150
+ const rawMessage = error instanceof Error ? error.message : String(error);
151
+ const safeMessage = sanitizeErrorMessage(
152
+ rawMessage,
153
+ typeof dbConnection === 'string' ? dbConnection : undefined,
154
+ );
155
+ return notOk(
156
+ errorUnexpected(safeMessage, {
157
+ why: `Unexpected error during db update: ${safeMessage}`,
158
+ }),
159
+ );
160
+ } finally {
161
+ await client.close();
162
+ }
163
+ }
164
+
165
+ export function createDbUpdateCommand(): Command {
166
+ const command = new Command('update');
167
+ setCommandDescriptions(
168
+ command,
169
+ 'Update your database schema to match your contract',
170
+ 'Compares your database schema to the emitted contract and applies the necessary\n' +
171
+ 'changes. Works on any database, whether or not it has been initialized with `db init`.\n' +
172
+ 'Use --plan to preview operations before applying.',
173
+ );
174
+ addMigrationCommandOptions(command);
175
+ command.option(
176
+ '--accept-data-loss',
177
+ 'Confirm destructive operations (required when plan includes drops or type changes)',
178
+ false,
179
+ );
180
+ command.configureHelp({
181
+ formatHelp: (cmd) => {
182
+ const flags = parseGlobalFlags({});
183
+ return formatCommandHelp({ command: cmd, flags });
184
+ },
185
+ });
186
+ command.action(async (options: DbUpdateOptions) => {
187
+ const flags = parseGlobalFlags(options);
188
+ const startTime = Date.now();
189
+
190
+ if (flags.json === 'ndjson') {
191
+ const result = notOk(
192
+ errorJsonFormatNotSupported({
193
+ command: 'db update',
194
+ format: 'ndjson',
195
+ supportedFormats: ['object'],
196
+ }),
197
+ );
198
+ const exitCode = handleResult(result, flags);
199
+ process.exit(exitCode);
200
+ }
201
+
202
+ const result = await executeDbUpdateCommand(options, flags, startTime);
203
+ const exitCode = handleResult(result, flags, (dbUpdateResult) => {
204
+ if (flags.json === 'object') {
205
+ console.log(formatMigrationJson(dbUpdateResult));
206
+ } else {
207
+ const output =
208
+ dbUpdateResult.mode === 'plan'
209
+ ? formatMigrationPlanOutput(dbUpdateResult, flags)
210
+ : formatMigrationApplyOutput(dbUpdateResult, flags);
211
+ if (output) {
212
+ console.log(output);
213
+ }
214
+ }
215
+ });
216
+ process.exit(exitCode);
217
+ });
218
+
219
+ return command;
220
+ }