@prisma-next/cli 0.3.0-pr.94.3 → 0.3.0-pr.95.2
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/dist/chunk-AGOTG4L3.js +965 -0
- 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-HWYQOCAJ.js +47 -0
- package/dist/chunk-HWYQOCAJ.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 -2
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +2764 -2522
- package/dist/cli.js.map +1 -1
- package/dist/commands/contract-emit.d.ts +3 -0
- package/dist/commands/contract-emit.d.ts.map +1 -0
- package/dist/commands/contract-emit.js +10 -0
- package/dist/commands/contract-emit.js.map +1 -0
- package/dist/commands/db-init.d.ts +3 -0
- package/dist/commands/db-init.d.ts.map +1 -0
- package/dist/commands/db-init.js +257 -0
- package/dist/commands/db-init.js.map +1 -0
- package/dist/commands/db-introspect.d.ts +3 -0
- package/dist/commands/db-introspect.d.ts.map +1 -0
- package/dist/commands/db-introspect.js +155 -0
- package/dist/commands/db-introspect.js.map +1 -0
- package/dist/commands/db-schema-verify.d.ts +3 -0
- package/dist/commands/db-schema-verify.d.ts.map +1 -0
- package/dist/commands/db-schema-verify.js +171 -0
- package/dist/commands/db-schema-verify.js.map +1 -0
- package/dist/commands/db-sign.d.ts +3 -0
- package/dist/commands/db-sign.d.ts.map +1 -0
- package/dist/commands/db-sign.js +195 -0
- package/dist/commands/db-sign.js.map +1 -0
- package/dist/commands/db-verify.d.ts +3 -0
- package/dist/commands/db-verify.d.ts.map +1 -0
- package/dist/commands/db-verify.js +193 -0
- package/dist/commands/db-verify.js.map +1 -0
- package/dist/{config-loader.d.mts → config-loader.d.ts} +3 -8
- package/dist/config-loader.d.ts.map +1 -0
- package/dist/config-loader.js +7 -0
- package/dist/config-loader.js.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 +6 -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/exports/index.js +176 -0
- package/dist/exports/index.js.map +1 -0
- package/dist/{exports/index.d.mts → load-ts-contract.d.ts} +5 -10
- 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 +54 -29
- package/dist/client-CoxxGz_7.mjs +0 -692
- package/dist/client-CoxxGz_7.mjs.map +0 -1
- package/dist/commands/contract-emit.d.mts +0 -7
- package/dist/commands/contract-emit.d.mts.map +0 -1
- package/dist/commands/contract-emit.mjs +0 -139
- package/dist/commands/contract-emit.mjs.map +0 -1
- package/dist/commands/db-init.d.mts +0 -7
- package/dist/commands/db-init.d.mts.map +0 -1
- package/dist/commands/db-init.mjs +0 -178
- package/dist/commands/db-init.mjs.map +0 -1
- package/dist/commands/db-introspect.d.mts +0 -7
- package/dist/commands/db-introspect.d.mts.map +0 -1
- package/dist/commands/db-introspect.mjs +0 -120
- package/dist/commands/db-introspect.mjs.map +0 -1
- package/dist/commands/db-schema-verify.d.mts +0 -7
- package/dist/commands/db-schema-verify.d.mts.map +0 -1
- package/dist/commands/db-schema-verify.mjs +0 -116
- package/dist/commands/db-schema-verify.mjs.map +0 -1
- package/dist/commands/db-sign.d.mts +0 -7
- package/dist/commands/db-sign.d.mts.map +0 -1
- package/dist/commands/db-sign.mjs +0 -138
- package/dist/commands/db-sign.mjs.map +0 -1
- package/dist/commands/db-verify.d.mts +0 -7
- package/dist/commands/db-verify.d.mts.map +0 -1
- package/dist/commands/db-verify.mjs +0 -128
- package/dist/commands/db-verify.mjs.map +0 -1
- package/dist/config-loader-B-pobG0R.mjs +0 -42
- package/dist/config-loader-B-pobG0R.mjs.map +0 -1
- package/dist/config-loader.d.mts.map +0 -1
- package/dist/config-loader.mjs +0 -3
- package/dist/exports/config-types.d.mts +0 -2
- package/dist/exports/config-types.mjs +0 -3
- package/dist/exports/control-api.d.mts +0 -405
- package/dist/exports/control-api.d.mts.map +0 -1
- package/dist/exports/control-api.mjs +0 -3
- package/dist/exports/index.d.mts.map +0 -1
- package/dist/exports/index.mjs +0 -128
- package/dist/exports/index.mjs.map +0 -1
- package/dist/result-handler-Do_4Fi4U.mjs +0 -959
- package/dist/result-handler-Do_4Fi4U.mjs.map +0 -1
|
@@ -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"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -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"}
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createProgressAdapter,
|
|
3
|
+
formatCommandHelp,
|
|
4
|
+
formatDbInitApplyOutput,
|
|
5
|
+
formatDbInitJson,
|
|
6
|
+
formatDbInitPlanOutput,
|
|
7
|
+
formatStyledHeader,
|
|
8
|
+
handleResult,
|
|
9
|
+
parseGlobalFlags,
|
|
10
|
+
setCommandDescriptions
|
|
11
|
+
} from "../chunk-AGOTG4L3.js";
|
|
12
|
+
import {
|
|
13
|
+
loadConfig
|
|
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";
|
|
28
|
+
|
|
29
|
+
// src/commands/db-init.ts
|
|
30
|
+
import { readFile } from "fs/promises";
|
|
31
|
+
import { relative, resolve } from "path";
|
|
32
|
+
import { notOk, ok } from "@prisma-next/utils/result";
|
|
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
|
+
}
|
|
213
|
+
function createDbInitCommand() {
|
|
214
|
+
const command = new Command("init");
|
|
215
|
+
setCommandDescriptions(
|
|
216
|
+
command,
|
|
217
|
+
"Bootstrap a database to match the current contract and write the contract marker",
|
|
218
|
+
"Initializes a database to match your emitted contract using additive-only operations.\nCreates any missing tables, columns, indexes, and constraints defined in your contract.\nLeaves existing compatible structures in place, surfaces conflicts when destructive changes\nwould be required, and writes a contract marker to track the database state. Use --plan to\npreview changes without applying."
|
|
219
|
+
);
|
|
220
|
+
command.configureHelp({
|
|
221
|
+
formatHelp: (cmd) => {
|
|
222
|
+
const flags = parseGlobalFlags({});
|
|
223
|
+
return formatCommandHelp({ command: cmd, flags });
|
|
224
|
+
}
|
|
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) => {
|
|
226
|
+
const flags = parseGlobalFlags(options);
|
|
227
|
+
const startTime = Date.now();
|
|
228
|
+
if (flags.json === "ndjson") {
|
|
229
|
+
const result2 = notOk(
|
|
230
|
+
errorJsonFormatNotSupported({
|
|
231
|
+
command: "db init",
|
|
232
|
+
format: "ndjson",
|
|
233
|
+
supportedFormats: ["object"]
|
|
234
|
+
})
|
|
235
|
+
);
|
|
236
|
+
const exitCode2 = handleResult(result2, flags);
|
|
237
|
+
process.exit(exitCode2);
|
|
238
|
+
}
|
|
239
|
+
const result = await executeDbInitCommand(options, flags, startTime);
|
|
240
|
+
const exitCode = handleResult(result, flags, (dbInitResult) => {
|
|
241
|
+
if (flags.json === "object") {
|
|
242
|
+
console.log(formatDbInitJson(dbInitResult));
|
|
243
|
+
} else {
|
|
244
|
+
const output = dbInitResult.mode === "plan" ? formatDbInitPlanOutput(dbInitResult, flags) : formatDbInitApplyOutput(dbInitResult, flags);
|
|
245
|
+
if (output) {
|
|
246
|
+
console.log(output);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
process.exit(exitCode);
|
|
251
|
+
});
|
|
252
|
+
return command;
|
|
253
|
+
}
|
|
254
|
+
export {
|
|
255
|
+
createDbInitCommand
|
|
256
|
+
};
|
|
257
|
+
//# sourceMappingURL=db-init.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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(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,QAAQ;AAAA,UACR,kBAAkB,CAAC,QAAQ;AAAA,QAC7B,CAAC;AAAA,MACH;AACA,YAAMC,YAAW,aAAaD,SAAQ,KAAK;AAC3C,cAAQ,KAAKC,SAAQ;AAAA,IACvB;AAEA,UAAM,SAAS,MAAM,qBAAqB,SAAS,OAAO,SAAS;AAEnE,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":["result","exitCode"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"db-introspect.d.ts","sourceRoot":"","sources":["../../src/commands/db-introspect.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAkKpC,wBAAgB,yBAAyB,IAAI,OAAO,CA4DnD"}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createProgressAdapter,
|
|
3
|
+
formatCommandHelp,
|
|
4
|
+
formatIntrospectJson,
|
|
5
|
+
formatIntrospectOutput,
|
|
6
|
+
formatStyledHeader,
|
|
7
|
+
handleResult,
|
|
8
|
+
parseGlobalFlags,
|
|
9
|
+
setCommandDescriptions
|
|
10
|
+
} from "../chunk-AGOTG4L3.js";
|
|
11
|
+
import {
|
|
12
|
+
loadConfig
|
|
13
|
+
} from "../chunk-HWYQOCAJ.js";
|
|
14
|
+
import {
|
|
15
|
+
CliStructuredError,
|
|
16
|
+
createControlClient,
|
|
17
|
+
errorDatabaseConnectionRequired,
|
|
18
|
+
errorDriverRequired,
|
|
19
|
+
errorJsonFormatNotSupported,
|
|
20
|
+
errorUnexpected
|
|
21
|
+
} from "../chunk-VG2R7DGF.js";
|
|
22
|
+
|
|
23
|
+
// src/commands/db-introspect.ts
|
|
24
|
+
import { relative, resolve } from "path";
|
|
25
|
+
import { notOk, ok } from "@prisma-next/utils/result";
|
|
26
|
+
import { Command } from "commander";
|
|
27
|
+
async function executeDbIntrospectCommand(options, flags, startTime) {
|
|
28
|
+
const config = await loadConfig(options.config);
|
|
29
|
+
const configPath = options.config ? relative(process.cwd(), resolve(options.config)) : "prisma-next.config.ts";
|
|
30
|
+
if (flags.json !== "object" && !flags.quiet) {
|
|
31
|
+
const details = [
|
|
32
|
+
{ label: "config", value: configPath }
|
|
33
|
+
];
|
|
34
|
+
if (options.db) {
|
|
35
|
+
const maskedUrl = options.db.replace(/:([^:@]+)@/, ":****@");
|
|
36
|
+
details.push({ label: "database", value: maskedUrl });
|
|
37
|
+
} else if (config.db?.connection && typeof config.db.connection === "string") {
|
|
38
|
+
const maskedUrl = config.db.connection.replace(/:([^:@]+)@/, ":****@");
|
|
39
|
+
details.push({ label: "database", value: maskedUrl });
|
|
40
|
+
}
|
|
41
|
+
const header = formatStyledHeader({
|
|
42
|
+
command: "db introspect",
|
|
43
|
+
description: "Inspect the database schema",
|
|
44
|
+
url: "https://pris.ly/db-introspect",
|
|
45
|
+
details,
|
|
46
|
+
flags
|
|
47
|
+
});
|
|
48
|
+
console.log(header);
|
|
49
|
+
}
|
|
50
|
+
const dbConnection = options.db ?? config.db?.connection;
|
|
51
|
+
if (!dbConnection) {
|
|
52
|
+
return notOk(
|
|
53
|
+
errorDatabaseConnectionRequired({
|
|
54
|
+
why: `Database connection is required for db introspect (set db.connection in ${configPath}, or pass --db <url>)`
|
|
55
|
+
})
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
if (!config.driver) {
|
|
59
|
+
return notOk(errorDriverRequired({ why: "Config.driver is required for db introspect" }));
|
|
60
|
+
}
|
|
61
|
+
const client = createControlClient({
|
|
62
|
+
family: config.family,
|
|
63
|
+
target: config.target,
|
|
64
|
+
adapter: config.adapter,
|
|
65
|
+
driver: config.driver,
|
|
66
|
+
extensionPacks: config.extensionPacks ?? []
|
|
67
|
+
});
|
|
68
|
+
const onProgress = createProgressAdapter({ flags });
|
|
69
|
+
try {
|
|
70
|
+
const schemaIR = await client.introspect({
|
|
71
|
+
connection: dbConnection,
|
|
72
|
+
onProgress
|
|
73
|
+
});
|
|
74
|
+
if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
|
|
75
|
+
console.log("");
|
|
76
|
+
}
|
|
77
|
+
const schemaView = client.toSchemaView(schemaIR);
|
|
78
|
+
const totalTime = Date.now() - startTime;
|
|
79
|
+
const connectionForMeta = typeof dbConnection === "string" ? dbConnection.replace(/:([^:@]+)@/, ":****@") : void 0;
|
|
80
|
+
const introspectResult = {
|
|
81
|
+
ok: true,
|
|
82
|
+
summary: "Schema introspected successfully",
|
|
83
|
+
target: {
|
|
84
|
+
familyId: config.family.familyId,
|
|
85
|
+
id: config.target.targetId
|
|
86
|
+
},
|
|
87
|
+
schema: schemaIR,
|
|
88
|
+
meta: {
|
|
89
|
+
...configPath ? { configPath } : {},
|
|
90
|
+
...connectionForMeta ? { dbUrl: connectionForMeta } : {}
|
|
91
|
+
},
|
|
92
|
+
timings: {
|
|
93
|
+
total: totalTime
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
return ok({ introspectResult, schemaView });
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if (error instanceof CliStructuredError) {
|
|
99
|
+
return notOk(error);
|
|
100
|
+
}
|
|
101
|
+
return notOk(
|
|
102
|
+
errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
103
|
+
why: `Unexpected error during db introspect: ${error instanceof Error ? error.message : String(error)}`
|
|
104
|
+
})
|
|
105
|
+
);
|
|
106
|
+
} finally {
|
|
107
|
+
await client.close();
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function createDbIntrospectCommand() {
|
|
111
|
+
const command = new Command("introspect");
|
|
112
|
+
setCommandDescriptions(
|
|
113
|
+
command,
|
|
114
|
+
"Inspect the database schema",
|
|
115
|
+
"Reads the live database schema and displays it as a tree structure. This command\ndoes not check the schema against your contract - it only shows what exists in\nthe database. Use `db verify` or `db schema-verify` to compare against your contract."
|
|
116
|
+
);
|
|
117
|
+
command.configureHelp({
|
|
118
|
+
formatHelp: (cmd) => {
|
|
119
|
+
const flags = parseGlobalFlags({});
|
|
120
|
+
return formatCommandHelp({ command: cmd, flags });
|
|
121
|
+
}
|
|
122
|
+
}).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").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) => {
|
|
123
|
+
const flags = parseGlobalFlags(options);
|
|
124
|
+
const startTime = Date.now();
|
|
125
|
+
if (flags.json === "ndjson") {
|
|
126
|
+
const result2 = notOk(
|
|
127
|
+
errorJsonFormatNotSupported({
|
|
128
|
+
command: "db introspect",
|
|
129
|
+
format: "ndjson",
|
|
130
|
+
supportedFormats: ["object"]
|
|
131
|
+
})
|
|
132
|
+
);
|
|
133
|
+
const exitCode2 = handleResult(result2, flags);
|
|
134
|
+
process.exit(exitCode2);
|
|
135
|
+
}
|
|
136
|
+
const result = await executeDbIntrospectCommand(options, flags, startTime);
|
|
137
|
+
const exitCode = handleResult(result, flags, (value) => {
|
|
138
|
+
const { introspectResult, schemaView } = value;
|
|
139
|
+
if (flags.json === "object") {
|
|
140
|
+
console.log(formatIntrospectJson(introspectResult));
|
|
141
|
+
} else {
|
|
142
|
+
const output = formatIntrospectOutput(introspectResult, schemaView, flags);
|
|
143
|
+
if (output) {
|
|
144
|
+
console.log(output);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
process.exit(exitCode);
|
|
149
|
+
});
|
|
150
|
+
return command;
|
|
151
|
+
}
|
|
152
|
+
export {
|
|
153
|
+
createDbIntrospectCommand
|
|
154
|
+
};
|
|
155
|
+
//# sourceMappingURL=db-introspect.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/commands/db-introspect.ts"],"sourcesContent":["import { relative, resolve } from 'node:path';\nimport type { CoreSchemaView } from '@prisma-next/core-control-plane/schema-view';\nimport type { IntrospectSchemaResult } from '@prisma-next/core-control-plane/types';\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 {\n CliStructuredError,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorJsonFormatNotSupported,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatIntrospectJson,\n formatIntrospectOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport { handleResult } from '../utils/result-handler';\n\ninterface DbIntrospectOptions {\n readonly db?: string;\n readonly config?: string;\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\ninterface DbIntrospectCommandResult {\n readonly introspectResult: IntrospectSchemaResult<unknown>;\n readonly schemaView: CoreSchemaView | undefined;\n}\n\n/**\n * Executes the db introspect command and returns a structured Result.\n */\nasync function executeDbIntrospectCommand(\n options: DbIntrospectOptions,\n flags: GlobalFlags,\n startTime: number,\n): Promise<Result<DbIntrospectCommandResult, 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\n // Output header\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n ];\n if (options.db) {\n // Mask password in URL for security\n const maskedUrl = options.db.replace(/:([^:@]+)@/, ':****@');\n details.push({ label: 'database', value: maskedUrl });\n } else if (config.db?.connection && typeof config.db.connection === 'string') {\n // Mask password in URL for security\n const maskedUrl = config.db.connection.replace(/:([^:@]+)@/, ':****@');\n details.push({ label: 'database', value: maskedUrl });\n }\n const header = formatStyledHeader({\n command: 'db introspect',\n description: 'Inspect the database schema',\n url: 'https://pris.ly/db-introspect',\n details,\n flags,\n });\n console.log(header);\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 introspect (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 introspect' }));\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 // Introspect with connection and progress\n const schemaIR = await client.introspect({\n connection: dbConnection,\n onProgress,\n });\n\n // Add blank line after all async operations if spinners were shown\n if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {\n console.log('');\n }\n\n // Call toSchemaView to convert schema IR to CoreSchemaView for tree rendering\n const schemaView = client.toSchemaView(schemaIR);\n\n const totalTime = Date.now() - startTime;\n\n // Get masked connection URL for meta (only for string connections)\n const connectionForMeta =\n typeof dbConnection === 'string' ? dbConnection.replace(/:([^:@]+)@/, ':****@') : undefined;\n\n const introspectResult: IntrospectSchemaResult<unknown> = {\n ok: true,\n summary: 'Schema introspected successfully',\n target: {\n familyId: config.family.familyId,\n id: config.target.targetId,\n },\n schema: schemaIR,\n meta: {\n ...(configPath ? { configPath } : {}),\n ...(connectionForMeta ? { dbUrl: connectionForMeta } : {}),\n },\n timings: {\n total: totalTime,\n },\n };\n\n return ok({ introspectResult, schemaView });\n } catch (error) {\n // Driver already throws CliStructuredError for connection failures\n if (error instanceof CliStructuredError) {\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 introspect: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createDbIntrospectCommand(): Command {\n const command = new Command('introspect');\n setCommandDescriptions(\n command,\n 'Inspect the database schema',\n 'Reads the live database schema and displays it as a tree structure. This command\\n' +\n 'does not check the schema against your contract - it only shows what exists in\\n' +\n 'the database. Use `db verify` or `db schema-verify` to compare against your contract.',\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('--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: DbIntrospectOptions) => {\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 introspect',\n format: 'ndjson',\n supportedFormats: ['object'],\n }),\n );\n const exitCode = handleResult(result, flags);\n process.exit(exitCode);\n }\n\n const result = await executeDbIntrospectCommand(options, flags, startTime);\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (value) => {\n const { introspectResult, schemaView } = value;\n if (flags.json === 'object') {\n console.log(formatIntrospectJson(introspectResult));\n } else {\n const output = formatIntrospectOutput(introspectResult, schemaView, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,UAAU,eAAe;AAGlC,SAAS,OAAO,UAAuB;AACvC,SAAS,eAAe;AA4CxB,eAAe,2BACb,SACA,OACA,WACgE;AAEhE,QAAM,SAAS,MAAM,WAAW,QAAQ,MAAM;AAC9C,QAAM,aAAa,QAAQ,SACvB,SAAS,QAAQ,IAAI,GAAG,QAAQ,QAAQ,MAAM,CAAC,IAC/C;AAGJ,MAAI,MAAM,SAAS,YAAY,CAAC,MAAM,OAAO;AAC3C,UAAM,UAAmD;AAAA,MACvD,EAAE,OAAO,UAAU,OAAO,WAAW;AAAA,IACvC;AACA,QAAI,QAAQ,IAAI;AAEd,YAAM,YAAY,QAAQ,GAAG,QAAQ,cAAc,QAAQ;AAC3D,cAAQ,KAAK,EAAE,OAAO,YAAY,OAAO,UAAU,CAAC;AAAA,IACtD,WAAW,OAAO,IAAI,cAAc,OAAO,OAAO,GAAG,eAAe,UAAU;AAE5E,YAAM,YAAY,OAAO,GAAG,WAAW,QAAQ,cAAc,QAAQ;AACrE,cAAQ,KAAK,EAAE,OAAO,YAAY,OAAO,UAAU,CAAC;AAAA,IACtD;AACA,UAAM,SAAS,mBAAmB;AAAA,MAChC,SAAS;AAAA,MACT,aAAa;AAAA,MACb,KAAK;AAAA,MACL;AAAA,MACA;AAAA,IACF,CAAC;AACD,YAAQ,IAAI,MAAM;AAAA,EACpB;AAGA,QAAM,eAAe,QAAQ,MAAM,OAAO,IAAI;AAC9C,MAAI,CAAC,cAAc;AACjB,WAAO;AAAA,MACL,gCAAgC;AAAA,QAC9B,KAAK,2EAA2E,UAAU;AAAA,MAC5F,CAAC;A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