@prisma-next/cli 0.3.0-dev.3 → 0.3.0-dev.30
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.
- package/README.md +111 -27
- package/dist/{chunk-BZMBKEEQ.js → chunk-AGOTG4L3.js} +44 -76
- package/dist/chunk-AGOTG4L3.js.map +1 -0
- package/dist/chunk-HLLI4YL7.js +180 -0
- package/dist/chunk-HLLI4YL7.js.map +1 -0
- package/dist/chunk-VG2R7DGF.js +735 -0
- package/dist/chunk-VG2R7DGF.js.map +1 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +1502 -968
- package/dist/cli.js.map +1 -1
- package/dist/commands/contract-emit.d.ts +2 -4
- package/dist/commands/contract-emit.d.ts.map +1 -0
- package/dist/commands/contract-emit.js +3 -2
- package/dist/commands/db-init.d.ts +2 -4
- package/dist/commands/db-init.d.ts.map +1 -0
- package/dist/commands/db-init.js +205 -289
- package/dist/commands/db-init.js.map +1 -1
- package/dist/commands/db-introspect.d.ts +2 -4
- package/dist/commands/db-introspect.d.ts.map +1 -0
- package/dist/commands/db-introspect.js +108 -143
- package/dist/commands/db-introspect.js.map +1 -1
- package/dist/commands/db-schema-verify.d.ts +2 -4
- package/dist/commands/db-schema-verify.d.ts.map +1 -0
- package/dist/commands/db-schema-verify.js +120 -113
- package/dist/commands/db-schema-verify.js.map +1 -1
- package/dist/commands/db-sign.d.ts +2 -4
- package/dist/commands/db-sign.d.ts.map +1 -0
- package/dist/commands/db-sign.js +152 -156
- package/dist/commands/db-sign.js.map +1 -1
- package/dist/commands/db-verify.d.ts +2 -4
- package/dist/commands/db-verify.d.ts.map +1 -0
- package/dist/commands/db-verify.js +142 -122
- package/dist/commands/db-verify.js.map +1 -1
- package/dist/config-loader.d.ts +3 -5
- package/dist/config-loader.d.ts.map +1 -0
- package/dist/control-api/client.d.ts +13 -0
- package/dist/control-api/client.d.ts.map +1 -0
- package/dist/control-api/operations/db-init.d.ts +29 -0
- package/dist/control-api/operations/db-init.d.ts.map +1 -0
- package/dist/control-api/types.d.ts +387 -0
- package/dist/control-api/types.d.ts.map +1 -0
- package/dist/exports/config-types.d.ts +3 -0
- package/dist/exports/config-types.d.ts.map +1 -0
- package/dist/exports/config-types.js.map +1 -0
- package/dist/exports/control-api.d.ts +13 -0
- package/dist/exports/control-api.d.ts.map +1 -0
- package/dist/exports/control-api.js +7 -0
- package/dist/exports/control-api.js.map +1 -0
- package/dist/exports/index.d.ts +4 -0
- package/dist/exports/index.d.ts.map +1 -0
- package/dist/{index.js → exports/index.js} +4 -3
- package/dist/exports/index.js.map +1 -0
- package/dist/{index.d.ts → load-ts-contract.d.ts} +4 -8
- package/dist/load-ts-contract.d.ts.map +1 -0
- package/dist/utils/cli-errors.d.ts +7 -0
- package/dist/utils/cli-errors.d.ts.map +1 -0
- package/dist/utils/command-helpers.d.ts +12 -0
- package/dist/utils/command-helpers.d.ts.map +1 -0
- package/dist/utils/framework-components.d.ts +70 -0
- package/dist/utils/framework-components.d.ts.map +1 -0
- package/dist/utils/global-flags.d.ts +25 -0
- package/dist/utils/global-flags.d.ts.map +1 -0
- package/dist/utils/output.d.ts +142 -0
- package/dist/utils/output.d.ts.map +1 -0
- package/dist/utils/progress-adapter.d.ts +26 -0
- package/dist/utils/progress-adapter.d.ts.map +1 -0
- package/dist/utils/result-handler.d.ts +15 -0
- package/dist/utils/result-handler.d.ts.map +1 -0
- package/package.json +30 -26
- package/src/cli.ts +260 -0
- package/src/commands/contract-emit.ts +259 -0
- package/src/commands/db-init.ts +360 -0
- package/src/commands/db-introspect.ts +227 -0
- package/src/commands/db-schema-verify.ts +238 -0
- package/src/commands/db-sign.ts +279 -0
- package/src/commands/db-verify.ts +258 -0
- package/src/config-loader.ts +76 -0
- package/src/control-api/client.ts +589 -0
- package/src/control-api/operations/db-init.ts +281 -0
- package/src/control-api/types.ts +461 -0
- package/src/exports/config-types.ts +6 -0
- package/src/exports/control-api.ts +46 -0
- package/src/exports/index.ts +4 -0
- package/src/load-ts-contract.ts +217 -0
- package/src/utils/cli-errors.ts +26 -0
- package/src/utils/command-helpers.ts +26 -0
- package/src/utils/framework-components.ts +177 -0
- package/src/utils/global-flags.ts +75 -0
- package/src/utils/output.ts +1471 -0
- package/src/utils/progress-adapter.ts +86 -0
- package/src/utils/result-handler.ts +44 -0
- package/dist/chunk-464LNZCE.js +0 -134
- package/dist/chunk-464LNZCE.js.map +0 -1
- package/dist/chunk-BZMBKEEQ.js.map +0 -1
- package/dist/chunk-ZKYEJROM.js +0 -94
- package/dist/chunk-ZKYEJROM.js.map +0 -1
- package/dist/config-types.d.ts +0 -1
- package/dist/config-types.js.map +0 -1
- package/dist/index.js.map +0 -1
- /package/dist/{config-types.js → exports/config-types.js} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contract-emit.d.ts","sourceRoot":"","sources":["../../src/commands/contract-emit.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AA0MpC,wBAAgB,yBAAyB,IAAI,OAAO,CAoDnD"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createContractEmitCommand
|
|
3
|
-
} from "../chunk-
|
|
4
|
-
import "../chunk-
|
|
3
|
+
} from "../chunk-HLLI4YL7.js";
|
|
4
|
+
import "../chunk-AGOTG4L3.js";
|
|
5
5
|
import "../chunk-HWYQOCAJ.js";
|
|
6
|
+
import "../chunk-VG2R7DGF.js";
|
|
6
7
|
export {
|
|
7
8
|
createContractEmitCommand
|
|
8
9
|
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"db-init.d.ts","sourceRoot":"","sources":["../../src/commands/db-init.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAmSpC,wBAAgB,mBAAmB,IAAI,OAAO,CAiE7C"}
|
package/dist/commands/db-init.js
CHANGED
|
@@ -1,17 +1,5 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
assertFrameworkComponentsCompatible
|
|
4
|
-
} from "../chunk-ZKYEJROM.js";
|
|
5
|
-
import {
|
|
6
|
-
errorContractValidationFailed,
|
|
7
|
-
errorDatabaseUrlRequired,
|
|
8
|
-
errorDriverRequired,
|
|
9
|
-
errorFileNotFound,
|
|
10
|
-
errorJsonFormatNotSupported,
|
|
11
|
-
errorMigrationPlanningFailed,
|
|
12
|
-
errorRuntime,
|
|
13
|
-
errorTargetMigrationNotSupported,
|
|
14
|
-
errorUnexpected,
|
|
2
|
+
createProgressAdapter,
|
|
15
3
|
formatCommandHelp,
|
|
16
4
|
formatDbInitApplyOutput,
|
|
17
5
|
formatDbInitJson,
|
|
@@ -19,19 +7,209 @@ import {
|
|
|
19
7
|
formatStyledHeader,
|
|
20
8
|
handleResult,
|
|
21
9
|
parseGlobalFlags,
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
withSpinner
|
|
25
|
-
} from "../chunk-BZMBKEEQ.js";
|
|
10
|
+
setCommandDescriptions
|
|
11
|
+
} from "../chunk-AGOTG4L3.js";
|
|
26
12
|
import {
|
|
27
13
|
loadConfig
|
|
28
14
|
} from "../chunk-HWYQOCAJ.js";
|
|
15
|
+
import {
|
|
16
|
+
CliStructuredError,
|
|
17
|
+
createControlClient,
|
|
18
|
+
errorContractValidationFailed,
|
|
19
|
+
errorDatabaseConnectionRequired,
|
|
20
|
+
errorDriverRequired,
|
|
21
|
+
errorFileNotFound,
|
|
22
|
+
errorJsonFormatNotSupported,
|
|
23
|
+
errorMigrationPlanningFailed,
|
|
24
|
+
errorRuntime,
|
|
25
|
+
errorTargetMigrationNotSupported,
|
|
26
|
+
errorUnexpected
|
|
27
|
+
} from "../chunk-VG2R7DGF.js";
|
|
29
28
|
|
|
30
29
|
// src/commands/db-init.ts
|
|
31
30
|
import { readFile } from "fs/promises";
|
|
32
31
|
import { relative, resolve } from "path";
|
|
33
|
-
import {
|
|
32
|
+
import { notOk, ok } from "@prisma-next/utils/result";
|
|
34
33
|
import { Command } from "commander";
|
|
34
|
+
function mapDbInitFailure(failure) {
|
|
35
|
+
if (failure.code === "PLANNING_FAILED") {
|
|
36
|
+
return errorMigrationPlanningFailed({ conflicts: failure.conflicts ?? [] });
|
|
37
|
+
}
|
|
38
|
+
if (failure.code === "MARKER_ORIGIN_MISMATCH") {
|
|
39
|
+
const mismatchParts = [];
|
|
40
|
+
if (failure.marker?.coreHash !== failure.destination?.coreHash && failure.marker?.coreHash && failure.destination?.coreHash) {
|
|
41
|
+
mismatchParts.push(
|
|
42
|
+
`coreHash (marker: ${failure.marker.coreHash}, destination: ${failure.destination.coreHash})`
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
if (failure.marker?.profileHash !== failure.destination?.profileHash && failure.marker?.profileHash && failure.destination?.profileHash) {
|
|
46
|
+
mismatchParts.push(
|
|
47
|
+
`profileHash (marker: ${failure.marker.profileHash}, destination: ${failure.destination.profileHash})`
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
return errorRuntime(
|
|
51
|
+
`Existing contract marker does not match plan destination.${mismatchParts.length > 0 ? ` Mismatch in ${mismatchParts.join(" and ")}.` : ""}`,
|
|
52
|
+
{
|
|
53
|
+
why: "Database has an existing contract marker that does not match the target contract",
|
|
54
|
+
fix: "If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow",
|
|
55
|
+
meta: {
|
|
56
|
+
code: "MARKER_ORIGIN_MISMATCH",
|
|
57
|
+
...failure.marker?.coreHash ? { markerCoreHash: failure.marker.coreHash } : {},
|
|
58
|
+
...failure.destination?.coreHash ? { destinationCoreHash: failure.destination.coreHash } : {},
|
|
59
|
+
...failure.marker?.profileHash ? { markerProfileHash: failure.marker.profileHash } : {},
|
|
60
|
+
...failure.destination?.profileHash ? { destinationProfileHash: failure.destination.profileHash } : {}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
if (failure.code === "RUNNER_FAILED") {
|
|
66
|
+
return errorRuntime(failure.summary, {
|
|
67
|
+
why: failure.why ?? "Migration runner failed",
|
|
68
|
+
fix: "Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`",
|
|
69
|
+
meta: {
|
|
70
|
+
code: "RUNNER_FAILED",
|
|
71
|
+
...failure.meta ?? {}
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
const exhaustive = failure.code;
|
|
76
|
+
throw new Error(`Unhandled DbInitFailure code: ${exhaustive}`);
|
|
77
|
+
}
|
|
78
|
+
async function executeDbInitCommand(options, flags, startTime) {
|
|
79
|
+
const config = await loadConfig(options.config);
|
|
80
|
+
const configPath = options.config ? relative(process.cwd(), resolve(options.config)) : "prisma-next.config.ts";
|
|
81
|
+
const contractPathAbsolute = config.contract?.output ? resolve(config.contract.output) : resolve("src/prisma/contract.json");
|
|
82
|
+
const contractPath = relative(process.cwd(), contractPathAbsolute);
|
|
83
|
+
if (flags.json !== "object" && !flags.quiet) {
|
|
84
|
+
const details = [
|
|
85
|
+
{ label: "config", value: configPath },
|
|
86
|
+
{ label: "contract", value: contractPath }
|
|
87
|
+
];
|
|
88
|
+
if (options.db) {
|
|
89
|
+
details.push({ label: "database", value: options.db });
|
|
90
|
+
}
|
|
91
|
+
if (options.plan) {
|
|
92
|
+
details.push({ label: "mode", value: "plan (dry run)" });
|
|
93
|
+
}
|
|
94
|
+
const header = formatStyledHeader({
|
|
95
|
+
command: "db init",
|
|
96
|
+
description: "Bootstrap a database to match the current contract",
|
|
97
|
+
url: "https://pris.ly/db-init",
|
|
98
|
+
details,
|
|
99
|
+
flags
|
|
100
|
+
});
|
|
101
|
+
console.log(header);
|
|
102
|
+
}
|
|
103
|
+
let contractJsonContent;
|
|
104
|
+
try {
|
|
105
|
+
contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
|
|
106
|
+
} catch (error) {
|
|
107
|
+
if (error instanceof Error && error.code === "ENOENT") {
|
|
108
|
+
return notOk(
|
|
109
|
+
errorFileNotFound(contractPathAbsolute, {
|
|
110
|
+
why: `Contract file not found at ${contractPathAbsolute}`,
|
|
111
|
+
fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`
|
|
112
|
+
})
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
return notOk(
|
|
116
|
+
errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
117
|
+
why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
|
|
118
|
+
})
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
let contractJson;
|
|
122
|
+
try {
|
|
123
|
+
contractJson = JSON.parse(contractJsonContent);
|
|
124
|
+
} catch (error) {
|
|
125
|
+
return notOk(
|
|
126
|
+
errorContractValidationFailed(
|
|
127
|
+
`Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
|
|
128
|
+
{ where: { path: contractPathAbsolute } }
|
|
129
|
+
)
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
const dbConnection = options.db ?? config.db?.connection;
|
|
133
|
+
if (!dbConnection) {
|
|
134
|
+
return notOk(
|
|
135
|
+
errorDatabaseConnectionRequired({
|
|
136
|
+
why: `Database connection is required for db init (set db.connection in ${configPath}, or pass --db <url>)`
|
|
137
|
+
})
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
if (!config.driver) {
|
|
141
|
+
return notOk(errorDriverRequired({ why: "Config.driver is required for db init" }));
|
|
142
|
+
}
|
|
143
|
+
if (!config.target.migrations) {
|
|
144
|
+
return notOk(
|
|
145
|
+
errorTargetMigrationNotSupported({
|
|
146
|
+
why: `Target "${config.target.id}" does not support migrations`
|
|
147
|
+
})
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
const client = createControlClient({
|
|
151
|
+
family: config.family,
|
|
152
|
+
target: config.target,
|
|
153
|
+
adapter: config.adapter,
|
|
154
|
+
driver: config.driver,
|
|
155
|
+
extensionPacks: config.extensionPacks ?? []
|
|
156
|
+
});
|
|
157
|
+
const onProgress = createProgressAdapter({ flags });
|
|
158
|
+
try {
|
|
159
|
+
const result = await client.dbInit({
|
|
160
|
+
contractIR: contractJson,
|
|
161
|
+
mode: options.plan ? "plan" : "apply",
|
|
162
|
+
connection: dbConnection,
|
|
163
|
+
onProgress
|
|
164
|
+
});
|
|
165
|
+
if (!result.ok) {
|
|
166
|
+
return notOk(mapDbInitFailure(result.failure));
|
|
167
|
+
}
|
|
168
|
+
const profileHash = result.value.marker?.profileHash;
|
|
169
|
+
const dbInitResult = {
|
|
170
|
+
ok: true,
|
|
171
|
+
mode: result.value.mode,
|
|
172
|
+
plan: {
|
|
173
|
+
targetId: config.target.targetId,
|
|
174
|
+
destination: {
|
|
175
|
+
coreHash: result.value.marker?.coreHash ?? "",
|
|
176
|
+
...profileHash ? { profileHash } : {}
|
|
177
|
+
},
|
|
178
|
+
operations: result.value.plan.operations.map((op) => ({
|
|
179
|
+
id: op.id,
|
|
180
|
+
label: op.label,
|
|
181
|
+
operationClass: op.operationClass
|
|
182
|
+
}))
|
|
183
|
+
},
|
|
184
|
+
...result.value.execution ? {
|
|
185
|
+
execution: {
|
|
186
|
+
operationsPlanned: result.value.execution.operationsPlanned,
|
|
187
|
+
operationsExecuted: result.value.execution.operationsExecuted
|
|
188
|
+
}
|
|
189
|
+
} : {},
|
|
190
|
+
...result.value.marker ? {
|
|
191
|
+
marker: {
|
|
192
|
+
coreHash: result.value.marker.coreHash,
|
|
193
|
+
...result.value.marker.profileHash ? { profileHash: result.value.marker.profileHash } : {}
|
|
194
|
+
}
|
|
195
|
+
} : {},
|
|
196
|
+
summary: result.value.summary,
|
|
197
|
+
timings: { total: Date.now() - startTime }
|
|
198
|
+
};
|
|
199
|
+
return ok(dbInitResult);
|
|
200
|
+
} catch (error) {
|
|
201
|
+
if (CliStructuredError.is(error)) {
|
|
202
|
+
return notOk(error);
|
|
203
|
+
}
|
|
204
|
+
return notOk(
|
|
205
|
+
errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
206
|
+
why: `Unexpected error during db init: ${error instanceof Error ? error.message : String(error)}`
|
|
207
|
+
})
|
|
208
|
+
);
|
|
209
|
+
} finally {
|
|
210
|
+
await client.close();
|
|
211
|
+
}
|
|
212
|
+
}
|
|
35
213
|
function createDbInitCommand() {
|
|
36
214
|
const command = new Command("init");
|
|
37
215
|
setCommandDescriptions(
|
|
@@ -47,280 +225,18 @@ function createDbInitCommand() {
|
|
|
47
225
|
}).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--plan", "Preview planned operations without applying", false).option("--json [format]", "Output as JSON (object)", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
|
|
48
226
|
const flags = parseGlobalFlags(options);
|
|
49
227
|
const startTime = Date.now();
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
228
|
+
if (flags.json === "ndjson") {
|
|
229
|
+
const result2 = notOk(
|
|
230
|
+
errorJsonFormatNotSupported({
|
|
53
231
|
command: "db init",
|
|
54
232
|
format: "ndjson",
|
|
55
233
|
supportedFormats: ["object"]
|
|
56
|
-
})
|
|
57
|
-
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
if (flags.json !== "object" && !flags.quiet) {
|
|
63
|
-
const details = [
|
|
64
|
-
{ label: "config", value: configPath },
|
|
65
|
-
{ label: "contract", value: contractPath }
|
|
66
|
-
];
|
|
67
|
-
if (options.db) {
|
|
68
|
-
details.push({ label: "database", value: options.db });
|
|
69
|
-
}
|
|
70
|
-
if (options.plan) {
|
|
71
|
-
details.push({ label: "mode", value: "plan (dry run)" });
|
|
72
|
-
}
|
|
73
|
-
const header = formatStyledHeader({
|
|
74
|
-
command: "db init",
|
|
75
|
-
description: "Bootstrap a database to match the current contract",
|
|
76
|
-
url: "https://pris.ly/db-init",
|
|
77
|
-
details,
|
|
78
|
-
flags
|
|
79
|
-
});
|
|
80
|
-
console.log(header);
|
|
81
|
-
}
|
|
82
|
-
let contractJsonContent;
|
|
83
|
-
try {
|
|
84
|
-
contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
|
|
85
|
-
} catch (error) {
|
|
86
|
-
if (error instanceof Error && error.code === "ENOENT") {
|
|
87
|
-
throw errorFileNotFound(contractPathAbsolute, {
|
|
88
|
-
why: `Contract file not found at ${contractPathAbsolute}`,
|
|
89
|
-
fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
throw errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
93
|
-
why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
let contractJson;
|
|
97
|
-
try {
|
|
98
|
-
contractJson = JSON.parse(contractJsonContent);
|
|
99
|
-
} catch (error) {
|
|
100
|
-
throw errorContractValidationFailed(
|
|
101
|
-
`Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
|
|
102
|
-
{ where: { path: contractPathAbsolute } }
|
|
103
|
-
);
|
|
104
|
-
}
|
|
105
|
-
const dbUrl = options.db ?? config.db?.url;
|
|
106
|
-
if (!dbUrl) {
|
|
107
|
-
throw errorDatabaseUrlRequired({
|
|
108
|
-
why: `Database URL is required for db init (set db.url in ${configPath}, or pass --db <url>)`
|
|
109
|
-
});
|
|
110
|
-
}
|
|
111
|
-
if (!config.driver) {
|
|
112
|
-
throw errorDriverRequired({ why: "Config.driver is required for db init" });
|
|
113
|
-
}
|
|
114
|
-
const driverDescriptor = config.driver;
|
|
115
|
-
if (!config.target.migrations) {
|
|
116
|
-
throw errorTargetMigrationNotSupported({
|
|
117
|
-
why: `Target "${config.target.id}" does not support migrations`
|
|
118
|
-
});
|
|
119
|
-
}
|
|
120
|
-
const migrations = config.target.migrations;
|
|
121
|
-
let driver;
|
|
122
|
-
try {
|
|
123
|
-
driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
|
|
124
|
-
message: "Connecting to database...",
|
|
125
|
-
flags
|
|
126
|
-
});
|
|
127
|
-
} catch (error) {
|
|
128
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
129
|
-
const code = error.code;
|
|
130
|
-
const redacted = redactDatabaseUrl(dbUrl);
|
|
131
|
-
throw errorRuntime("Database connection failed", {
|
|
132
|
-
why: message,
|
|
133
|
-
fix: "Verify the database URL, ensure the database is reachable, and confirm credentials/permissions",
|
|
134
|
-
meta: {
|
|
135
|
-
...typeof code !== "undefined" ? { code } : {},
|
|
136
|
-
...redacted
|
|
137
|
-
}
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
try {
|
|
141
|
-
const familyInstance = config.family.create({
|
|
142
|
-
target: config.target,
|
|
143
|
-
adapter: config.adapter,
|
|
144
|
-
driver: driverDescriptor,
|
|
145
|
-
extensionPacks: config.extensionPacks ?? []
|
|
146
|
-
});
|
|
147
|
-
const rawComponents = [config.target, config.adapter, ...config.extensionPacks ?? []];
|
|
148
|
-
const frameworkComponents = assertFrameworkComponentsCompatible(
|
|
149
|
-
config.family.familyId,
|
|
150
|
-
config.target.targetId,
|
|
151
|
-
rawComponents
|
|
152
|
-
);
|
|
153
|
-
const contractIR = familyInstance.validateContractIR(contractJson);
|
|
154
|
-
assertContractRequirementsSatisfied({
|
|
155
|
-
contract: contractIR,
|
|
156
|
-
family: config.family,
|
|
157
|
-
target: config.target,
|
|
158
|
-
adapter: config.adapter,
|
|
159
|
-
extensionPacks: config.extensionPacks
|
|
160
|
-
});
|
|
161
|
-
const planner = migrations.createPlanner(familyInstance);
|
|
162
|
-
const runner = migrations.createRunner(familyInstance);
|
|
163
|
-
const schemaIR = await withSpinner(() => familyInstance.introspect({ driver }), {
|
|
164
|
-
message: "Introspecting database schema...",
|
|
165
|
-
flags
|
|
166
|
-
});
|
|
167
|
-
const policy = { allowedOperationClasses: ["additive"] };
|
|
168
|
-
const plannerResult = await withSpinner(
|
|
169
|
-
async () => planner.plan({
|
|
170
|
-
contract: contractIR,
|
|
171
|
-
schema: schemaIR,
|
|
172
|
-
policy,
|
|
173
|
-
frameworkComponents
|
|
174
|
-
}),
|
|
175
|
-
{
|
|
176
|
-
message: "Planning migration...",
|
|
177
|
-
flags
|
|
178
|
-
}
|
|
179
|
-
);
|
|
180
|
-
if (plannerResult.kind === "failure") {
|
|
181
|
-
throw errorMigrationPlanningFailed({ conflicts: plannerResult.conflicts });
|
|
182
|
-
}
|
|
183
|
-
const migrationPlan = plannerResult.plan;
|
|
184
|
-
const existingMarker = await familyInstance.readMarker({ driver });
|
|
185
|
-
if (existingMarker) {
|
|
186
|
-
const markerMatchesDestination = existingMarker.coreHash === migrationPlan.destination.coreHash && (!migrationPlan.destination.profileHash || existingMarker.profileHash === migrationPlan.destination.profileHash);
|
|
187
|
-
if (markerMatchesDestination) {
|
|
188
|
-
const dbInitResult2 = {
|
|
189
|
-
ok: true,
|
|
190
|
-
mode: options.plan ? "plan" : "apply",
|
|
191
|
-
plan: {
|
|
192
|
-
targetId: migrationPlan.targetId,
|
|
193
|
-
destination: migrationPlan.destination,
|
|
194
|
-
operations: []
|
|
195
|
-
},
|
|
196
|
-
...options.plan ? {} : {
|
|
197
|
-
execution: { operationsPlanned: 0, operationsExecuted: 0 },
|
|
198
|
-
marker: {
|
|
199
|
-
coreHash: existingMarker.coreHash,
|
|
200
|
-
profileHash: existingMarker.profileHash
|
|
201
|
-
}
|
|
202
|
-
},
|
|
203
|
-
summary: "Database already at target contract state",
|
|
204
|
-
timings: { total: Date.now() - startTime }
|
|
205
|
-
};
|
|
206
|
-
return dbInitResult2;
|
|
207
|
-
}
|
|
208
|
-
const coreHashMismatch = existingMarker.coreHash !== migrationPlan.destination.coreHash;
|
|
209
|
-
const profileHashMismatch = migrationPlan.destination.profileHash && existingMarker.profileHash !== migrationPlan.destination.profileHash;
|
|
210
|
-
const mismatchParts = [];
|
|
211
|
-
if (coreHashMismatch) {
|
|
212
|
-
mismatchParts.push(
|
|
213
|
-
`coreHash (marker: ${existingMarker.coreHash}, destination: ${migrationPlan.destination.coreHash})`
|
|
214
|
-
);
|
|
215
|
-
}
|
|
216
|
-
if (profileHashMismatch) {
|
|
217
|
-
mismatchParts.push(
|
|
218
|
-
`profileHash (marker: ${existingMarker.profileHash}, destination: ${migrationPlan.destination.profileHash})`
|
|
219
|
-
);
|
|
220
|
-
}
|
|
221
|
-
throw errorRuntime(
|
|
222
|
-
`Existing contract marker does not match plan destination. Mismatch in ${mismatchParts.join(" and ")}.`,
|
|
223
|
-
{
|
|
224
|
-
why: "Database has an existing contract marker that does not match the target contract",
|
|
225
|
-
fix: "If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow",
|
|
226
|
-
meta: {
|
|
227
|
-
code: "MARKER_ORIGIN_MISMATCH",
|
|
228
|
-
markerCoreHash: existingMarker.coreHash,
|
|
229
|
-
destinationCoreHash: migrationPlan.destination.coreHash,
|
|
230
|
-
...existingMarker.profileHash ? { markerProfileHash: existingMarker.profileHash } : {},
|
|
231
|
-
...migrationPlan.destination.profileHash ? { destinationProfileHash: migrationPlan.destination.profileHash } : {}
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
);
|
|
235
|
-
}
|
|
236
|
-
if (options.plan) {
|
|
237
|
-
const dbInitResult2 = {
|
|
238
|
-
ok: true,
|
|
239
|
-
mode: "plan",
|
|
240
|
-
plan: {
|
|
241
|
-
targetId: migrationPlan.targetId,
|
|
242
|
-
destination: migrationPlan.destination,
|
|
243
|
-
operations: migrationPlan.operations.map((op) => ({
|
|
244
|
-
id: op.id,
|
|
245
|
-
label: op.label,
|
|
246
|
-
operationClass: op.operationClass
|
|
247
|
-
}))
|
|
248
|
-
},
|
|
249
|
-
summary: `Planned ${migrationPlan.operations.length} operation(s)`,
|
|
250
|
-
timings: { total: Date.now() - startTime }
|
|
251
|
-
};
|
|
252
|
-
return dbInitResult2;
|
|
253
|
-
}
|
|
254
|
-
if (!flags.quiet && flags.json !== "object") {
|
|
255
|
-
console.log("Applying migration plan and verifying schema...");
|
|
256
|
-
}
|
|
257
|
-
const callbacks = {
|
|
258
|
-
onOperationStart: (op) => {
|
|
259
|
-
if (!flags.quiet && flags.json !== "object") {
|
|
260
|
-
console.log(` \u2192 ${op.label}...`);
|
|
261
|
-
}
|
|
262
|
-
},
|
|
263
|
-
onOperationComplete: (_op) => {
|
|
264
|
-
}
|
|
265
|
-
};
|
|
266
|
-
const runnerResult = await runner.execute({
|
|
267
|
-
plan: migrationPlan,
|
|
268
|
-
driver,
|
|
269
|
-
destinationContract: contractIR,
|
|
270
|
-
policy,
|
|
271
|
-
callbacks,
|
|
272
|
-
// db init plans and applies back-to-back from a fresh introspection, so per-operation
|
|
273
|
-
// pre/postchecks and the idempotency probe are usually redundant overhead. We still
|
|
274
|
-
// enforce marker/origin compatibility and a full schema verification after apply.
|
|
275
|
-
executionChecks: {
|
|
276
|
-
prechecks: false,
|
|
277
|
-
postchecks: false,
|
|
278
|
-
idempotencyChecks: false
|
|
279
|
-
},
|
|
280
|
-
frameworkComponents
|
|
281
|
-
});
|
|
282
|
-
if (!runnerResult.ok) {
|
|
283
|
-
const meta = {
|
|
284
|
-
code: runnerResult.failure.code,
|
|
285
|
-
...runnerResult.failure.meta ?? {}
|
|
286
|
-
};
|
|
287
|
-
const sqlState = typeof meta["sqlState"] === "string" ? meta["sqlState"] : void 0;
|
|
288
|
-
const fix = sqlState === "42501" ? "Grant the database user sufficient privileges (insufficient_privilege), or run db init as a more privileged role" : runnerResult.failure.code === "SCHEMA_VERIFY_FAILED" ? "Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`" : void 0;
|
|
289
|
-
throw errorRuntime(runnerResult.failure.summary, {
|
|
290
|
-
why: runnerResult.failure.why ?? `Migration runner failed: ${runnerResult.failure.code}`,
|
|
291
|
-
...fix ? { fix } : {},
|
|
292
|
-
meta
|
|
293
|
-
});
|
|
294
|
-
}
|
|
295
|
-
const execution = runnerResult.value;
|
|
296
|
-
const dbInitResult = {
|
|
297
|
-
ok: true,
|
|
298
|
-
mode: "apply",
|
|
299
|
-
plan: {
|
|
300
|
-
targetId: migrationPlan.targetId,
|
|
301
|
-
destination: migrationPlan.destination,
|
|
302
|
-
operations: migrationPlan.operations.map((op) => ({
|
|
303
|
-
id: op.id,
|
|
304
|
-
label: op.label,
|
|
305
|
-
operationClass: op.operationClass
|
|
306
|
-
}))
|
|
307
|
-
},
|
|
308
|
-
execution: {
|
|
309
|
-
operationsPlanned: execution.operationsPlanned,
|
|
310
|
-
operationsExecuted: execution.operationsExecuted
|
|
311
|
-
},
|
|
312
|
-
marker: migrationPlan.destination.profileHash ? {
|
|
313
|
-
coreHash: migrationPlan.destination.coreHash,
|
|
314
|
-
profileHash: migrationPlan.destination.profileHash
|
|
315
|
-
} : { coreHash: migrationPlan.destination.coreHash },
|
|
316
|
-
summary: `Applied ${execution.operationsExecuted} operation(s), marker written`,
|
|
317
|
-
timings: { total: Date.now() - startTime }
|
|
318
|
-
};
|
|
319
|
-
return dbInitResult;
|
|
320
|
-
} finally {
|
|
321
|
-
await driver.close();
|
|
322
|
-
}
|
|
323
|
-
});
|
|
234
|
+
})
|
|
235
|
+
);
|
|
236
|
+
const exitCode2 = handleResult(result2, flags);
|
|
237
|
+
process.exit(exitCode2);
|
|
238
|
+
}
|
|
239
|
+
const result = await executeDbInitCommand(options, flags, startTime);
|
|
324
240
|
const exitCode = handleResult(result, flags, (dbInitResult) => {
|
|
325
241
|
if (flags.json === "object") {
|
|
326
242
|
console.log(formatDbInitJson(dbInitResult));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/db-init.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type {\n MigrationPlan,\n MigrationPlannerResult,\n MigrationPlanOperation,\n MigrationRunnerResult,\n} from '@prisma-next/core-control-plane/types';\nimport { redactDatabaseUrl } from '@prisma-next/utils/redact-db-url';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { performAction } from '../utils/action';\nimport {\n errorContractValidationFailed,\n errorDatabaseUrlRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorJsonFormatNotSupported,\n errorMigrationPlanningFailed,\n errorRuntime,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport {\n assertContractRequirementsSatisfied,\n assertFrameworkComponentsCompatible,\n} from '../utils/framework-components';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n type DbInitResult,\n formatCommandHelp,\n formatDbInitApplyOutput,\n formatDbInitJson,\n formatDbInitPlanOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbInitOptions {\n readonly db?: string;\n readonly config?: string;\n readonly plan?: boolean;\n readonly json?: string | boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\nexport function createDbInitCommand(): Command {\n const command = new Command('init');\n setCommandDescriptions(\n command,\n 'Bootstrap a database to match the current contract and write the contract marker',\n 'Initializes a database to match your emitted contract using additive-only operations.\\n' +\n 'Creates any missing tables, columns, indexes, and constraints defined in your contract.\\n' +\n 'Leaves existing compatible structures in place, surfaces conflicts when destructive changes\\n' +\n 'would be required, and writes a contract marker to track the database state. Use --plan to\\n' +\n 'preview changes without applying.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--plan', 'Preview planned operations without applying', false)\n .option('--json [format]', 'Output as JSON (object)', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbInitOptions) => {\n const flags = parseGlobalFlags(options);\n const startTime = Date.now();\n\n const result = await performAction(async () => {\n if (flags.json === 'ndjson') {\n throw errorJsonFormatNotSupported({\n command: 'db init',\n format: 'ndjson',\n supportedFormats: ['object'],\n });\n }\n\n // Load config\n const config = await loadConfig(options.config);\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = config.contract?.output\n ? resolve(config.contract.output)\n : resolve('src/prisma/contract.json');\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: options.db });\n }\n if (options.plan) {\n details.push({ label: 'mode', value: 'plan (dry run)' });\n }\n const header = formatStyledHeader({\n command: 'db init',\n description: 'Bootstrap a database to match the current contract',\n url: 'https://pris.ly/db-init',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: `Run \\`prisma-next contract emit\\` to generate ${contractPath}, or update \\`config.contract.output\\` in ${configPath}`,\n });\n }\n throw errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n let contractJson: Record<string, unknown>;\n try {\n contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n } catch (error) {\n throw errorContractValidationFailed(\n `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\n );\n }\n\n // Resolve database URL\n const dbUrl = options.db ?? config.db?.url;\n if (!dbUrl) {\n throw errorDatabaseUrlRequired({\n why: `Database URL is required for db init (set db.url in ${configPath}, or pass --db <url>)`,\n });\n }\n\n // Check for driver\n if (!config.driver) {\n throw errorDriverRequired({ why: 'Config.driver is required for db init' });\n }\n const driverDescriptor = config.driver;\n\n // Check target supports migrations via the migrations capability\n if (!config.target.migrations) {\n throw errorTargetMigrationNotSupported({\n why: `Target \"${config.target.id}\" does not support migrations`,\n });\n }\n const migrations = config.target.migrations;\n\n // Create driver\n let driver: Awaited<ReturnType<(typeof driverDescriptor)['create']>>;\n try {\n driver = await withSpinner(() => driverDescriptor.create(dbUrl), {\n message: 'Connecting to database...',\n flags,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const code = (error as { code?: unknown }).code;\n const redacted = redactDatabaseUrl(dbUrl);\n throw errorRuntime('Database connection failed', {\n why: message,\n fix: 'Verify the database URL, ensure the database is reachable, and confirm credentials/permissions',\n meta: {\n ...(typeof code !== 'undefined' ? { code } : {}),\n ...redacted,\n },\n });\n }\n\n try {\n // Create family instance\n const familyInstance = config.family.create({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensionPacks: config.extensionPacks ?? [],\n });\n const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];\n const frameworkComponents = assertFrameworkComponentsCompatible(\n config.family.familyId,\n config.target.targetId,\n rawComponents,\n );\n\n // Validate contract\n const contractIR = familyInstance.validateContractIR(contractJson);\n assertContractRequirementsSatisfied({\n contract: contractIR,\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n extensionPacks: config.extensionPacks,\n });\n\n // Create planner and runner from target migrations capability\n const planner = migrations.createPlanner(familyInstance);\n const runner = migrations.createRunner(familyInstance);\n\n // Introspect live schema\n const schemaIR = await withSpinner(() => familyInstance.introspect({ driver }), {\n message: 'Introspecting database schema...',\n flags,\n });\n\n // Policy for init mode (additive only)\n const policy = { allowedOperationClasses: ['additive'] as const };\n\n // Plan migration\n const plannerResult: MigrationPlannerResult = await withSpinner(\n async () =>\n planner.plan({\n contract: contractIR,\n schema: schemaIR,\n policy,\n frameworkComponents,\n }),\n {\n message: 'Planning migration...',\n flags,\n },\n );\n\n if (plannerResult.kind === 'failure') {\n throw errorMigrationPlanningFailed({ conflicts: plannerResult.conflicts });\n }\n\n const migrationPlan: MigrationPlan = plannerResult.plan;\n\n // Check for existing marker - handle idempotency and mismatch errors\n const existingMarker = await familyInstance.readMarker({ driver });\n if (existingMarker) {\n const markerMatchesDestination =\n existingMarker.coreHash === migrationPlan.destination.coreHash &&\n (!migrationPlan.destination.profileHash ||\n existingMarker.profileHash === migrationPlan.destination.profileHash);\n\n if (markerMatchesDestination) {\n // Already at destination - return success with no operations\n const dbInitResult: DbInitResult = {\n ok: true,\n mode: options.plan ? 'plan' : 'apply',\n plan: {\n targetId: migrationPlan.targetId,\n destination: migrationPlan.destination,\n operations: [],\n },\n ...(options.plan\n ? {}\n : {\n execution: { operationsPlanned: 0, operationsExecuted: 0 },\n marker: {\n coreHash: existingMarker.coreHash,\n profileHash: existingMarker.profileHash,\n },\n }),\n summary: 'Database already at target contract state',\n timings: { total: Date.now() - startTime },\n };\n return dbInitResult;\n }\n\n // Marker exists but doesn't match destination - fail\n const coreHashMismatch = existingMarker.coreHash !== migrationPlan.destination.coreHash;\n const profileHashMismatch =\n migrationPlan.destination.profileHash &&\n existingMarker.profileHash !== migrationPlan.destination.profileHash;\n\n const mismatchParts: string[] = [];\n if (coreHashMismatch) {\n mismatchParts.push(\n `coreHash (marker: ${existingMarker.coreHash}, destination: ${migrationPlan.destination.coreHash})`,\n );\n }\n if (profileHashMismatch) {\n mismatchParts.push(\n `profileHash (marker: ${existingMarker.profileHash}, destination: ${migrationPlan.destination.profileHash})`,\n );\n }\n\n throw errorRuntime(\n `Existing contract marker does not match plan destination. Mismatch in ${mismatchParts.join(' and ')}.`,\n {\n why: 'Database has an existing contract marker that does not match the target contract',\n fix: 'If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow',\n meta: {\n code: 'MARKER_ORIGIN_MISMATCH',\n markerCoreHash: existingMarker.coreHash,\n destinationCoreHash: migrationPlan.destination.coreHash,\n ...(existingMarker.profileHash\n ? { markerProfileHash: existingMarker.profileHash }\n : {}),\n ...(migrationPlan.destination.profileHash\n ? { destinationProfileHash: migrationPlan.destination.profileHash }\n : {}),\n },\n },\n );\n }\n\n // Plan mode - don't execute\n if (options.plan) {\n const dbInitResult: DbInitResult = {\n ok: true,\n mode: 'plan',\n plan: {\n targetId: migrationPlan.targetId,\n destination: migrationPlan.destination,\n operations: migrationPlan.operations.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n })),\n },\n summary: `Planned ${migrationPlan.operations.length} operation(s)`,\n timings: { total: Date.now() - startTime },\n };\n return dbInitResult;\n }\n\n // Apply mode - execute runner\n // Log main message once, then show individual operations via callbacks\n if (!flags.quiet && flags.json !== 'object') {\n console.log('Applying migration plan and verifying schema...');\n }\n\n const callbacks = {\n onOperationStart: (op: MigrationPlanOperation) => {\n if (!flags.quiet && flags.json !== 'object') {\n console.log(` → ${op.label}...`);\n }\n },\n onOperationComplete: (_op: MigrationPlanOperation) => {\n // Could log completion if needed\n },\n };\n\n const runnerResult: MigrationRunnerResult = await runner.execute({\n plan: migrationPlan,\n driver,\n destinationContract: contractIR,\n policy,\n callbacks,\n // db init plans and applies back-to-back from a fresh introspection, so per-operation\n // pre/postchecks and the idempotency probe are usually redundant overhead. We still\n // enforce marker/origin compatibility and a full schema verification after apply.\n executionChecks: {\n prechecks: false,\n postchecks: false,\n idempotencyChecks: false,\n },\n frameworkComponents,\n });\n\n if (!runnerResult.ok) {\n const meta: Record<string, unknown> = {\n code: runnerResult.failure.code,\n ...(runnerResult.failure.meta ?? {}),\n };\n const sqlState = typeof meta['sqlState'] === 'string' ? meta['sqlState'] : undefined;\n const fix =\n sqlState === '42501'\n ? 'Grant the database user sufficient privileges (insufficient_privilege), or run db init as a more privileged role'\n : runnerResult.failure.code === 'SCHEMA_VERIFY_FAILED'\n ? 'Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`'\n : undefined;\n\n throw errorRuntime(runnerResult.failure.summary, {\n why:\n runnerResult.failure.why ?? `Migration runner failed: ${runnerResult.failure.code}`,\n ...(fix ? { fix } : {}),\n meta,\n });\n }\n\n const execution = runnerResult.value;\n\n const dbInitResult: DbInitResult = {\n ok: true,\n mode: 'apply',\n plan: {\n targetId: migrationPlan.targetId,\n destination: migrationPlan.destination,\n operations: migrationPlan.operations.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n })),\n },\n execution: {\n operationsPlanned: execution.operationsPlanned,\n operationsExecuted: execution.operationsExecuted,\n },\n marker: migrationPlan.destination.profileHash\n ? {\n coreHash: migrationPlan.destination.coreHash,\n profileHash: migrationPlan.destination.profileHash,\n }\n : { coreHash: migrationPlan.destination.coreHash },\n summary: `Applied ${execution.operationsExecuted} operation(s), marker written`,\n timings: { total: Date.now() - startTime },\n };\n return dbInitResult;\n } finally {\n await driver.close();\n }\n });\n\n // Handle result\n const exitCode = handleResult(result, flags, (dbInitResult) => {\n if (flags.json === 'object') {\n console.log(formatDbInitJson(dbInitResult));\n } else {\n const output =\n dbInitResult.mode === 'plan'\n ? formatDbInitPlanOutput(dbInitResult, flags)\n : formatDbInitApplyOutput(dbInitResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";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jC,IAAI;AAAA,UACJ,MAAM;AAAA,UACN,MAAM;AAAA,YACJ,UAAU,cAAc;AAAA,YACxB,aAAa,cAAc;AAAA,YAC3B,YAAY,cAAc,WAAW,IAAI,CAAC,QAAQ;AAAA,cAChD,IAAI,GAAG;AAAA,cACP,OAAO,GAAG;AAAA,cACV,gBAAgB,GAAG;AAAA,YACrB,EAAE;AAAA,UACJ;AAAA,UACA,WAAW;AAAA,YACT,mBAAmB,UAAU;AAAA,YAC7B,oBAAoB,UAAU;AAAA,UAChC;AAAA,UACA,QAAQ,cAAc,YAAY,cAC9B;AAAA,YACE,UAAU,cAAc,YAAY;AAAA,YACpC,aAAa,cAAc,YAAY;AAAA,UACzC,IACA,EAAE,UAAU,cAAc,YAAY,SAAS;AAAA,UACnD,SAAS,WAAW,UAAU,kBAAkB;AAAA,UAChD,SAAS,EAAE,OAAO,KAAK,IAAI,IAAI,UAAU;AAAA,QAC3C;AACA,eAAO;AAAA,MACT,UAAE;AACA,cAAM,OAAO,MAAM;AAAA,MACrB;AAAA,IACF,CAAC;AAGD,UAAM,WAAW,aAAa,QAAQ,OAAO,CAAC,iBAAiB;AAC7D,UAAI,MAAM,SAAS,UAAU;AAC3B,gBAAQ,IAAI,iBAAiB,YAAY,CAAC;AAAA,MAC5C,OAAO;AACL,cAAM,SACJ,aAAa,SAAS,SAClB,uBAAuB,cAAc,KAAK,IAC1C,wBAAwB,cAAc,KAAK;AACjD,YAAI,QAAQ;AACV,kBAAQ,IAAI,MAAM;AAAA,QACpB;AAAA,MACF;AAAA,IACF,CAAC;AAED,YAAQ,KAAK,QAAQ;AAAA,EACvB,CAAC;AAEH,SAAO;AACT;","names":["dbInitResult"]}
|
|
1
|
+
{"version":3,"sources":["../../src/commands/db-init.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport type { DbInitFailure } from '../control-api/types';\nimport {\n CliStructuredError,\n errorContractValidationFailed,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorJsonFormatNotSupported,\n errorMigrationPlanningFailed,\n errorRuntime,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport {\n type DbInitResult,\n formatCommandHelp,\n formatDbInitApplyOutput,\n formatDbInitJson,\n formatDbInitPlanOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport { handleResult } from '../utils/result-handler';\n\ninterface DbInitOptions {\n readonly db?: string;\n readonly config?: string;\n readonly plan?: boolean;\n readonly json?: string | boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\n/**\n * Maps a DbInitFailure to a CliStructuredError for consistent error handling.\n */\nfunction mapDbInitFailure(failure: DbInitFailure): CliStructuredError {\n if (failure.code === 'PLANNING_FAILED') {\n return errorMigrationPlanningFailed({ conflicts: failure.conflicts ?? [] });\n }\n\n if (failure.code === 'MARKER_ORIGIN_MISMATCH') {\n const mismatchParts: string[] = [];\n if (\n failure.marker?.coreHash !== failure.destination?.coreHash &&\n failure.marker?.coreHash &&\n failure.destination?.coreHash\n ) {\n mismatchParts.push(\n `coreHash (marker: ${failure.marker.coreHash}, destination: ${failure.destination.coreHash})`,\n );\n }\n if (\n failure.marker?.profileHash !== failure.destination?.profileHash &&\n failure.marker?.profileHash &&\n failure.destination?.profileHash\n ) {\n mismatchParts.push(\n `profileHash (marker: ${failure.marker.profileHash}, destination: ${failure.destination.profileHash})`,\n );\n }\n\n return errorRuntime(\n `Existing contract marker does not match plan destination.${mismatchParts.length > 0 ? ` Mismatch in ${mismatchParts.join(' and ')}.` : ''}`,\n {\n why: 'Database has an existing contract marker that does not match the target contract',\n fix: 'If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow',\n meta: {\n code: 'MARKER_ORIGIN_MISMATCH',\n ...(failure.marker?.coreHash ? { markerCoreHash: failure.marker.coreHash } : {}),\n ...(failure.destination?.coreHash\n ? { destinationCoreHash: failure.destination.coreHash }\n : {}),\n ...(failure.marker?.profileHash ? { markerProfileHash: failure.marker.profileHash } : {}),\n ...(failure.destination?.profileHash\n ? { destinationProfileHash: failure.destination.profileHash }\n : {}),\n },\n },\n );\n }\n\n if (failure.code === 'RUNNER_FAILED') {\n return errorRuntime(failure.summary, {\n why: failure.why ?? 'Migration runner failed',\n fix: 'Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`',\n meta: {\n code: 'RUNNER_FAILED',\n ...(failure.meta ?? {}),\n },\n });\n }\n\n // Exhaustive check - TypeScript will error if a new code is added but not handled\n const exhaustive: never = failure.code;\n throw new Error(`Unhandled DbInitFailure code: ${exhaustive}`);\n}\n\n/**\n * Executes the db init command and returns a structured Result.\n */\nasync function executeDbInitCommand(\n options: DbInitOptions,\n flags: GlobalFlags,\n startTime: number,\n): Promise<Result<DbInitResult, CliStructuredError>> {\n // Load config\n const config = await loadConfig(options.config);\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = config.contract?.output\n ? resolve(config.contract.output)\n : resolve('src/prisma/contract.json');\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: options.db });\n }\n if (options.plan) {\n details.push({ label: 'mode', value: 'plan (dry run)' });\n }\n const header = formatStyledHeader({\n command: 'db init',\n description: 'Bootstrap a database to match the current contract',\n url: 'https://pris.ly/db-init',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: `Run \\`prisma-next contract emit\\` to generate ${contractPath}, or update \\`config.contract.output\\` in ${configPath}`,\n }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n let contractJson: Record<string, unknown>;\n try {\n contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n } catch (error) {\n return notOk(\n errorContractValidationFailed(\n `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\n ),\n );\n }\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n return notOk(\n errorDatabaseConnectionRequired({\n why: `Database connection is required for db init (set db.connection in ${configPath}, or pass --db <url>)`,\n }),\n );\n }\n\n // Check for driver\n if (!config.driver) {\n return notOk(errorDriverRequired({ why: 'Config.driver is required for db init' }));\n }\n\n // Check target supports migrations via the migrations capability\n if (!config.target.migrations) {\n return notOk(\n errorTargetMigrationNotSupported({\n why: `Target \"${config.target.id}\" does not support migrations`,\n }),\n );\n }\n\n // Create control client\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n\n // Create progress adapter\n const onProgress = createProgressAdapter({ flags });\n\n try {\n // Call dbInit with connection and progress callback\n // Connection happens inside dbInit with a 'connect' progress span\n const result = await client.dbInit({\n contractIR: contractJson,\n mode: options.plan ? 'plan' : 'apply',\n connection: dbConnection,\n onProgress,\n });\n\n // Handle failures by mapping to CLI structured error\n if (!result.ok) {\n return notOk(mapDbInitFailure(result.failure));\n }\n\n // Convert success result to CLI output format\n const profileHash = result.value.marker?.profileHash;\n const dbInitResult: DbInitResult = {\n ok: true,\n mode: result.value.mode,\n plan: {\n targetId: config.target.targetId,\n destination: {\n coreHash: result.value.marker?.coreHash ?? '',\n ...(profileHash ? { profileHash } : {}),\n },\n operations: result.value.plan.operations.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n })),\n },\n ...(result.value.execution\n ? {\n execution: {\n operationsPlanned: result.value.execution.operationsPlanned,\n operationsExecuted: result.value.execution.operationsExecuted,\n },\n }\n : {}),\n ...(result.value.marker\n ? {\n marker: {\n coreHash: result.value.marker.coreHash,\n ...(result.value.marker.profileHash\n ? { profileHash: result.value.marker.profileHash }\n : {}),\n },\n }\n : {}),\n summary: result.value.summary,\n timings: { total: Date.now() - startTime },\n };\n\n return ok(dbInitResult);\n } catch (error) {\n // Driver already throws CliStructuredError for connection failures\n // Use static type guard to work across module boundaries\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n\n // Wrap unexpected errors\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during db init: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createDbInitCommand(): Command {\n const command = new Command('init');\n setCommandDescriptions(\n command,\n 'Bootstrap a database to match the current contract and write the contract marker',\n 'Initializes a database to match your emitted contract using additive-only operations.\\n' +\n 'Creates any missing tables, columns, indexes, and constraints defined in your contract.\\n' +\n 'Leaves existing compatible structures in place, surfaces conflicts when destructive changes\\n' +\n 'would be required, and writes a contract marker to track the database state. Use --plan to\\n' +\n 'preview changes without applying.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--plan', 'Preview planned operations without applying', false)\n .option('--json [format]', 'Output as JSON (object)', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbInitOptions) => {\n const flags = parseGlobalFlags(options);\n const startTime = Date.now();\n\n // Validate JSON format option\n if (flags.json === 'ndjson') {\n const result = notOk(\n errorJsonFormatNotSupported({\n command: 'db init',\n format: 'ndjson',\n supportedFormats: ['object'],\n }),\n );\n const exitCode = handleResult(result, flags);\n process.exit(exitCode);\n }\n\n const result = await executeDbInitCommand(options, flags, startTime);\n\n const exitCode = handleResult(result, flags, (dbInitResult) => {\n if (flags.json === 'object') {\n console.log(formatDbInitJson(dbInitResult));\n } else {\n const output =\n dbInitResult.mode === 'plan'\n ? formatDbInitPlanOutput(dbInitResult, flags)\n : formatDbInitApplyOutput(dbInitResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAClC,SAAS,OAAO,UAAuB;AACvC,SAAS,eAAe;AAgDxB,SAAS,iBAAiB,SAA4C;AACpE,MAAI,QAAQ,SAAS,mBAAmB;AACtC,WAAO,6BAA6B,EAAE,WAAW,QAAQ,aAAa,CAAC,EAAE,CAAC;AAAA,EAC5E;AAEA,MAAI,QAAQ,SAAS,0BAA0B;AAC7C,UAAM,gBAA0B,CAAC;AACjC,QACE,QAAQ,QAAQ,aAAa,QAAQ,aAAa,YAClD,QAAQ,QAAQ,YAChB,QAAQ,aAAa,UACrB;AACA,oBAAc;AAAA,QACZ,qBAAqB,QAAQ,OAAO,QAAQ,kBAAkB,QA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