@prisma-next/cli 0.3.0-dev.9 → 0.3.0-pr.100.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/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.js +1502 -942
- package/dist/cli.js.map +1 -1
- package/dist/commands/contract-emit.d.ts.map +1 -1
- package/dist/commands/contract-emit.js +3 -2
- package/dist/commands/db-init.d.ts.map +1 -1
- package/dist/commands/db-init.js +205 -285
- package/dist/commands/db-init.js.map +1 -1
- package/dist/commands/db-introspect.d.ts.map +1 -1
- package/dist/commands/db-introspect.js +108 -139
- package/dist/commands/db-introspect.js.map +1 -1
- package/dist/commands/db-schema-verify.d.ts.map +1 -1
- package/dist/commands/db-schema-verify.js +120 -109
- package/dist/commands/db-schema-verify.js.map +1 -1
- package/dist/commands/db-sign.d.ts.map +1 -1
- package/dist/commands/db-sign.js +152 -152
- package/dist/commands/db-sign.js.map +1 -1
- package/dist/commands/db-verify.d.ts.map +1 -1
- package/dist/commands/db-verify.js +142 -118
- package/dist/commands/db-verify.js.map +1 -1
- 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/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.js +3 -2
- package/dist/exports/index.js.map +1 -1
- package/dist/utils/cli-errors.d.ts +1 -1
- package/dist/utils/cli-errors.d.ts.map +1 -1
- package/dist/utils/progress-adapter.d.ts +26 -0
- package/dist/utils/progress-adapter.d.ts.map +1 -0
- package/package.json +20 -16
- package/src/commands/contract-emit.ts +179 -102
- package/src/commands/db-init.ts +263 -355
- package/src/commands/db-introspect.ts +151 -180
- package/src/commands/db-schema-verify.ts +151 -145
- package/src/commands/db-sign.ts +202 -196
- package/src/commands/db-verify.ts +180 -151
- 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/control-api.ts +46 -0
- package/src/utils/cli-errors.ts +1 -1
- package/src/utils/progress-adapter.ts +86 -0
- package/dist/chunk-BZMBKEEQ.js.map +0 -1
- package/dist/chunk-CVNWLFXO.js +0 -91
- package/dist/chunk-CVNWLFXO.js.map +0 -1
- package/dist/chunk-QUPBU4KV.js +0 -131
- package/dist/chunk-QUPBU4KV.js.map +0 -1
- package/dist/utils/action.d.ts +0 -16
- package/dist/utils/action.d.ts.map +0 -1
- package/dist/utils/spinner.d.ts +0 -29
- package/dist/utils/spinner.d.ts.map +0 -1
- package/src/utils/action.ts +0 -43
- package/src/utils/spinner.ts +0 -67
|
@@ -1,32 +1,112 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
} from "../chunk-CVNWLFXO.js";
|
|
4
|
-
import {
|
|
2
|
+
createProgressAdapter,
|
|
5
3
|
formatCommandHelp,
|
|
6
4
|
formatIntrospectJson,
|
|
7
5
|
formatIntrospectOutput,
|
|
8
6
|
formatStyledHeader,
|
|
9
7
|
handleResult,
|
|
10
8
|
parseGlobalFlags,
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
withSpinner
|
|
14
|
-
} from "../chunk-BZMBKEEQ.js";
|
|
9
|
+
setCommandDescriptions
|
|
10
|
+
} from "../chunk-AGOTG4L3.js";
|
|
15
11
|
import {
|
|
16
12
|
loadConfig
|
|
17
13
|
} from "../chunk-HWYQOCAJ.js";
|
|
18
|
-
|
|
19
|
-
// src/commands/db-introspect.ts
|
|
20
|
-
import { readFile } from "fs/promises";
|
|
21
|
-
import { relative, resolve } from "path";
|
|
22
14
|
import {
|
|
23
|
-
|
|
15
|
+
CliStructuredError,
|
|
16
|
+
createControlClient,
|
|
17
|
+
errorDatabaseConnectionRequired,
|
|
24
18
|
errorDriverRequired,
|
|
25
|
-
|
|
19
|
+
errorJsonFormatNotSupported,
|
|
26
20
|
errorUnexpected
|
|
27
|
-
} from "
|
|
28
|
-
|
|
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";
|
|
29
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
|
+
}
|
|
30
110
|
function createDbIntrospectCommand() {
|
|
31
111
|
const command = new Command("introspect");
|
|
32
112
|
setCommandDescriptions(
|
|
@@ -39,132 +119,21 @@ function createDbIntrospectCommand() {
|
|
|
39
119
|
const flags = parseGlobalFlags({});
|
|
40
120
|
return formatCommandHelp({ command: cmd, flags });
|
|
41
121
|
}
|
|
42
|
-
}).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object
|
|
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) => {
|
|
43
123
|
const flags = parseGlobalFlags(options);
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
let contractIR;
|
|
49
|
-
if (config.contract?.output) {
|
|
50
|
-
const contractPath = resolve(config.contract.output);
|
|
51
|
-
try {
|
|
52
|
-
const contractJsonContent = await readFile(contractPath, "utf-8");
|
|
53
|
-
contractIR = JSON.parse(contractJsonContent);
|
|
54
|
-
} catch (error) {
|
|
55
|
-
if (error instanceof Error && error.code !== "ENOENT") {
|
|
56
|
-
throw errorUnexpected(error.message, {
|
|
57
|
-
why: `Failed to read contract file: ${error.message}`
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
if (flags.json !== "object" && !flags.quiet) {
|
|
63
|
-
const details = [
|
|
64
|
-
{ label: "config", value: configPath }
|
|
65
|
-
];
|
|
66
|
-
if (options.db) {
|
|
67
|
-
const maskedUrl = options.db.replace(/:([^:@]+)@/, ":****@");
|
|
68
|
-
details.push({ label: "database", value: maskedUrl });
|
|
69
|
-
} else if (config.db?.url) {
|
|
70
|
-
const maskedUrl = config.db.url.replace(/:([^:@]+)@/, ":****@");
|
|
71
|
-
details.push({ label: "database", value: maskedUrl });
|
|
72
|
-
}
|
|
73
|
-
const header = formatStyledHeader({
|
|
124
|
+
const startTime = Date.now();
|
|
125
|
+
if (flags.json === "ndjson") {
|
|
126
|
+
const result2 = notOk(
|
|
127
|
+
errorJsonFormatNotSupported({
|
|
74
128
|
command: "db introspect",
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
if (!dbUrl) {
|
|
84
|
-
throw errorDatabaseUrlRequired();
|
|
85
|
-
}
|
|
86
|
-
if (!config.driver) {
|
|
87
|
-
throw errorDriverRequired();
|
|
88
|
-
}
|
|
89
|
-
const driverDescriptor = config.driver;
|
|
90
|
-
const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
|
|
91
|
-
message: "Connecting to database...",
|
|
92
|
-
flags
|
|
93
|
-
});
|
|
94
|
-
try {
|
|
95
|
-
const stack = createControlPlaneStack({
|
|
96
|
-
target: config.target,
|
|
97
|
-
adapter: config.adapter,
|
|
98
|
-
driver: driverDescriptor,
|
|
99
|
-
extensionPacks: config.extensionPacks
|
|
100
|
-
});
|
|
101
|
-
const familyInstance = config.family.create(stack);
|
|
102
|
-
if (contractIR) {
|
|
103
|
-
const validatedContract = familyInstance.validateContractIR(contractIR);
|
|
104
|
-
assertContractRequirementsSatisfied({ contract: validatedContract, stack });
|
|
105
|
-
contractIR = validatedContract;
|
|
106
|
-
}
|
|
107
|
-
let schemaIR;
|
|
108
|
-
try {
|
|
109
|
-
schemaIR = await withSpinner(
|
|
110
|
-
() => familyInstance.introspect({
|
|
111
|
-
driver,
|
|
112
|
-
contractIR
|
|
113
|
-
}),
|
|
114
|
-
{
|
|
115
|
-
message: "Introspecting database schema...",
|
|
116
|
-
flags
|
|
117
|
-
}
|
|
118
|
-
);
|
|
119
|
-
} catch (error) {
|
|
120
|
-
throw errorRuntime(error instanceof Error ? error.message : String(error), {
|
|
121
|
-
why: `Failed to introspect database: ${error instanceof Error ? error.message : String(error)}`
|
|
122
|
-
});
|
|
123
|
-
}
|
|
124
|
-
let schemaView;
|
|
125
|
-
if (familyInstance.toSchemaView) {
|
|
126
|
-
try {
|
|
127
|
-
schemaView = familyInstance.toSchemaView(schemaIR);
|
|
128
|
-
} catch (error) {
|
|
129
|
-
if (flags.verbose) {
|
|
130
|
-
console.error(
|
|
131
|
-
`Warning: Failed to project schema to view: ${error instanceof Error ? error.message : String(error)}`
|
|
132
|
-
);
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
const totalTime = Date.now() - startTime;
|
|
137
|
-
if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
|
|
138
|
-
console.log("");
|
|
139
|
-
}
|
|
140
|
-
const introspectResult = {
|
|
141
|
-
ok: true,
|
|
142
|
-
summary: "Schema introspected successfully",
|
|
143
|
-
target: {
|
|
144
|
-
familyId: config.family.familyId,
|
|
145
|
-
id: config.target.targetId
|
|
146
|
-
},
|
|
147
|
-
schema: schemaIR,
|
|
148
|
-
...configPath || options.db || config.db?.url ? {
|
|
149
|
-
meta: {
|
|
150
|
-
...configPath ? { configPath } : {},
|
|
151
|
-
...options.db || config.db?.url ? {
|
|
152
|
-
dbUrl: (options.db ?? config.db?.url ?? "").replace(
|
|
153
|
-
/:([^:@]+)@/,
|
|
154
|
-
":****@"
|
|
155
|
-
)
|
|
156
|
-
} : {}
|
|
157
|
-
}
|
|
158
|
-
} : {},
|
|
159
|
-
timings: {
|
|
160
|
-
total: totalTime
|
|
161
|
-
}
|
|
162
|
-
};
|
|
163
|
-
return { introspectResult, schemaView };
|
|
164
|
-
} finally {
|
|
165
|
-
await driver.close();
|
|
166
|
-
}
|
|
167
|
-
});
|
|
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);
|
|
168
137
|
const exitCode = handleResult(result, flags, (value) => {
|
|
169
138
|
const { introspectResult, schemaView } = value;
|
|
170
139
|
if (flags.json === "object") {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/db-introspect.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport {\n errorDatabaseUrlRequired,\n errorDriverRequired,\n errorRuntime,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type { CoreSchemaView } from '@prisma-next/core-control-plane/schema-view';\nimport type { IntrospectSchemaResult } from '@prisma-next/core-control-plane/types';\nimport { createControlPlaneStack } from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { performAction } from '../utils/action';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport { assertContractRequirementsSatisfied } from '../utils/framework-components';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatIntrospectJson,\n formatIntrospectOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\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\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 or ndjson)', 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\n const result = await performAction(async () => {\n const startTime = Date.now();\n\n // Load config (file I/O)\n const config = await loadConfig(options.config);\n // Normalize config path for display (match contract path format - no ./ prefix)\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n\n // Optionally load contract if contract config exists\n let contractIR: unknown | undefined;\n if (config.contract?.output) {\n const contractPath = resolve(config.contract.output);\n try {\n const contractJsonContent = await readFile(contractPath, 'utf-8');\n contractIR = JSON.parse(contractJsonContent);\n } catch (error) {\n // Contract file is optional for introspection - don't fail if it doesn't exist\n if (error instanceof Error && (error as { code?: string }).code !== 'ENOENT') {\n throw errorUnexpected(error.message, {\n why: `Failed to read contract file: ${error.message}`,\n });\n }\n }\n }\n\n // Output header (only for human-readable output)\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?.url) {\n // Mask password in URL for security\n const maskedUrl = config.db.url.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 URL\n const dbUrl = options.db ?? config.db?.url;\n if (!dbUrl) {\n throw errorDatabaseUrlRequired();\n }\n\n // Check for driver\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n // Create driver\n const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {\n message: 'Connecting to database...',\n flags,\n });\n\n try {\n // Create family instance\n const stack = createControlPlaneStack({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensionPacks: config.extensionPacks,\n });\n const familyInstance = config.family.create(stack);\n\n // Validate contract IR if we loaded it\n if (contractIR) {\n const validatedContract = familyInstance.validateContractIR(contractIR);\n assertContractRequirementsSatisfied({ contract: validatedContract, stack });\n contractIR = validatedContract;\n }\n\n // Call family instance introspect method\n let schemaIR: unknown;\n try {\n schemaIR = await withSpinner(\n () =>\n familyInstance.introspect({\n driver,\n contractIR,\n }),\n {\n message: 'Introspecting database schema...',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from introspect() in structured error\n throw errorRuntime(error instanceof Error ? error.message : String(error), {\n why: `Failed to introspect database: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // Optionally call toSchemaView if available\n let schemaView: CoreSchemaView | undefined;\n if (familyInstance.toSchemaView) {\n try {\n schemaView = familyInstance.toSchemaView(schemaIR);\n } catch (error) {\n // Schema view projection is optional - log but don't fail\n if (flags.verbose) {\n console.error(\n `Warning: Failed to project schema to view: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n\n const totalTime = Date.now() - startTime;\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 // Build result envelope\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 ...(configPath || options.db || config.db?.url\n ? {\n meta: {\n ...(configPath ? { configPath } : {}),\n ...(options.db || config.db?.url\n ? {\n dbUrl: (options.db ?? config.db?.url ?? '').replace(\n /:([^:@]+)@/,\n ':****@',\n ),\n }\n : {}),\n },\n }\n : {}),\n timings: {\n total: totalTime,\n },\n };\n\n return { introspectResult, schemaView };\n } finally {\n // Ensure driver connection is closed\n await driver.close();\n }\n });\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (value) => {\n const { introspectResult, schemaView } = value;\n // Output based on flags\n if (flags.json === 'object') {\n // JSON output to stdout\n console.log(formatIntrospectJson(introspectResult));\n } else {\n // Human-readable output to stdout\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,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAAS,+BAA+B;AACxC,SAAS,eAAe;AA8BjB,SAAS,4BAAqC;AACnD,QAAM,UAAU,IAAI,QAAQ,YAAY;AACxC;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,EAGF;AACA,UACG,cAAc;AAAA,IACb,YAAY,CAAC,QAAQ;AACnB,YAAM,QAAQ,iBAAiB,CAAC,CAAC;AACjC,aAAO,kBAAkB,EAAE,SAAS,KAAK,MAAM,CAAC;AAAA,IAClD;AAAA,EACF,CAAC,EACA,OAAO,cAAc,4BAA4B,EACjD,OAA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YAAI,QAAQ;AACV,kBAAQ,IAAI,MAAM;AAAA,QACpB;AAAA,MACF;AAAA,IACF,CAAC;AACD,YAAQ,KAAK,QAAQ;AAAA,EACvB,CAAC;AAEH,SAAO;AACT;","names":[]}
|
|
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;AAAA,IACH;AAAA,EACF;AAGA,MAAI,CAAC,OAAO,QAAQ;AAClB,WAAO,MAAM,oBAAoB,E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AAS,uBAAuB,kBAAkB,YAAY,KAAK;AACzE,YAAI,QAAQ;AACV,kBAAQ,IAAI,MAAM;AAAA,QACpB;AAAA,MACF;AAAA,IACF,CAAC;AACD,YAAQ,KAAK,QAAQ;AAAA,EACvB,CAAC;AAEH,SAAO;AACT;","names":["result","exitCode"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"db-schema-verify.d.ts","sourceRoot":"","sources":["../../src/commands/db-schema-verify.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"db-schema-verify.d.ts","sourceRoot":"","sources":["../../src/commands/db-schema-verify.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAqKpC,wBAAgB,2BAA2B,IAAI,OAAO,CAoErD"}
|
|
@@ -1,34 +1,126 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
assertFrameworkComponentsCompatible
|
|
4
|
-
} from "../chunk-CVNWLFXO.js";
|
|
5
|
-
import {
|
|
2
|
+
createProgressAdapter,
|
|
6
3
|
formatCommandHelp,
|
|
7
4
|
formatSchemaVerifyJson,
|
|
8
5
|
formatSchemaVerifyOutput,
|
|
9
6
|
formatStyledHeader,
|
|
10
7
|
handleResult,
|
|
11
8
|
parseGlobalFlags,
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
withSpinner
|
|
15
|
-
} from "../chunk-BZMBKEEQ.js";
|
|
9
|
+
setCommandDescriptions
|
|
10
|
+
} from "../chunk-AGOTG4L3.js";
|
|
16
11
|
import {
|
|
17
12
|
loadConfig
|
|
18
13
|
} from "../chunk-HWYQOCAJ.js";
|
|
19
|
-
|
|
20
|
-
// src/commands/db-schema-verify.ts
|
|
21
|
-
import { readFile } from "fs/promises";
|
|
22
|
-
import { relative, resolve } from "path";
|
|
23
14
|
import {
|
|
24
|
-
|
|
15
|
+
CliStructuredError,
|
|
16
|
+
createControlClient,
|
|
17
|
+
errorContractValidationFailed,
|
|
18
|
+
errorDatabaseConnectionRequired,
|
|
25
19
|
errorDriverRequired,
|
|
26
20
|
errorFileNotFound,
|
|
27
|
-
|
|
21
|
+
errorJsonFormatNotSupported,
|
|
28
22
|
errorUnexpected
|
|
29
|
-
} from "
|
|
30
|
-
|
|
23
|
+
} from "../chunk-VG2R7DGF.js";
|
|
24
|
+
|
|
25
|
+
// src/commands/db-schema-verify.ts
|
|
26
|
+
import { readFile } from "fs/promises";
|
|
27
|
+
import { relative, resolve } from "path";
|
|
28
|
+
import { notOk, ok } from "@prisma-next/utils/result";
|
|
31
29
|
import { Command } from "commander";
|
|
30
|
+
async function executeDbSchemaVerifyCommand(options, flags) {
|
|
31
|
+
const config = await loadConfig(options.config);
|
|
32
|
+
const configPath = options.config ? relative(process.cwd(), resolve(options.config)) : "prisma-next.config.ts";
|
|
33
|
+
const contractPathAbsolute = config.contract?.output ? resolve(config.contract.output) : resolve("src/prisma/contract.json");
|
|
34
|
+
const contractPath = relative(process.cwd(), contractPathAbsolute);
|
|
35
|
+
if (flags.json !== "object" && !flags.quiet) {
|
|
36
|
+
const details = [
|
|
37
|
+
{ label: "config", value: configPath },
|
|
38
|
+
{ label: "contract", value: contractPath }
|
|
39
|
+
];
|
|
40
|
+
if (options.db) {
|
|
41
|
+
details.push({ label: "database", value: options.db });
|
|
42
|
+
}
|
|
43
|
+
const header = formatStyledHeader({
|
|
44
|
+
command: "db schema-verify",
|
|
45
|
+
description: "Check whether the database schema satisfies your contract",
|
|
46
|
+
url: "https://pris.ly/db-schema-verify",
|
|
47
|
+
details,
|
|
48
|
+
flags
|
|
49
|
+
});
|
|
50
|
+
console.log(header);
|
|
51
|
+
}
|
|
52
|
+
let contractJsonContent;
|
|
53
|
+
try {
|
|
54
|
+
contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (error instanceof Error && error.code === "ENOENT") {
|
|
57
|
+
return notOk(
|
|
58
|
+
errorFileNotFound(contractPathAbsolute, {
|
|
59
|
+
why: `Contract file not found at ${contractPathAbsolute}`,
|
|
60
|
+
fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`
|
|
61
|
+
})
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
return notOk(
|
|
65
|
+
errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
66
|
+
why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
|
|
67
|
+
})
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
let contractJson;
|
|
71
|
+
try {
|
|
72
|
+
contractJson = JSON.parse(contractJsonContent);
|
|
73
|
+
} catch (error) {
|
|
74
|
+
return notOk(
|
|
75
|
+
errorContractValidationFailed(
|
|
76
|
+
`Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
|
|
77
|
+
{ where: { path: contractPathAbsolute } }
|
|
78
|
+
)
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
const dbConnection = options.db ?? config.db?.connection;
|
|
82
|
+
if (!dbConnection) {
|
|
83
|
+
return notOk(
|
|
84
|
+
errorDatabaseConnectionRequired({
|
|
85
|
+
why: `Database connection is required for db schema-verify (set db.connection in ${configPath}, or pass --db <url>)`
|
|
86
|
+
})
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
if (!config.driver) {
|
|
90
|
+
return notOk(errorDriverRequired({ why: "Config.driver is required for db schema-verify" }));
|
|
91
|
+
}
|
|
92
|
+
const client = createControlClient({
|
|
93
|
+
family: config.family,
|
|
94
|
+
target: config.target,
|
|
95
|
+
adapter: config.adapter,
|
|
96
|
+
driver: config.driver,
|
|
97
|
+
extensionPacks: config.extensionPacks ?? []
|
|
98
|
+
});
|
|
99
|
+
const onProgress = createProgressAdapter({ flags });
|
|
100
|
+
try {
|
|
101
|
+
const schemaVerifyResult = await client.schemaVerify({
|
|
102
|
+
contractIR: contractJson,
|
|
103
|
+
strict: options.strict ?? false,
|
|
104
|
+
connection: dbConnection,
|
|
105
|
+
onProgress
|
|
106
|
+
});
|
|
107
|
+
if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
|
|
108
|
+
console.log("");
|
|
109
|
+
}
|
|
110
|
+
return ok(schemaVerifyResult);
|
|
111
|
+
} catch (error) {
|
|
112
|
+
if (error instanceof CliStructuredError) {
|
|
113
|
+
return notOk(error);
|
|
114
|
+
}
|
|
115
|
+
return notOk(
|
|
116
|
+
errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
117
|
+
why: `Unexpected error during db schema-verify: ${error instanceof Error ? error.message : String(error)}`
|
|
118
|
+
})
|
|
119
|
+
);
|
|
120
|
+
} finally {
|
|
121
|
+
await client.close();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
32
124
|
function createDbSchemaVerifyCommand() {
|
|
33
125
|
const command = new Command("schema-verify");
|
|
34
126
|
setCommandDescriptions(
|
|
@@ -41,101 +133,20 @@ function createDbSchemaVerifyCommand() {
|
|
|
41
133
|
const flags = parseGlobalFlags({});
|
|
42
134
|
return formatCommandHelp({ command: cmd, flags });
|
|
43
135
|
}
|
|
44
|
-
}).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object
|
|
136
|
+
}).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object)", false).option("--strict", "Strict mode: extra schema elements cause failures", 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) => {
|
|
45
137
|
const flags = parseGlobalFlags(options);
|
|
46
|
-
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
const contractPathAbsolute = config.contract?.output ? resolve(config.contract.output) : resolve("src/prisma/contract.json");
|
|
50
|
-
const contractPath = relative(process.cwd(), contractPathAbsolute);
|
|
51
|
-
if (flags.json !== "object" && !flags.quiet) {
|
|
52
|
-
const details = [
|
|
53
|
-
{ label: "config", value: configPath },
|
|
54
|
-
{ label: "contract", value: contractPath }
|
|
55
|
-
];
|
|
56
|
-
if (options.db) {
|
|
57
|
-
details.push({ label: "database", value: options.db });
|
|
58
|
-
}
|
|
59
|
-
const header = formatStyledHeader({
|
|
138
|
+
if (flags.json === "ndjson") {
|
|
139
|
+
const result2 = notOk(
|
|
140
|
+
errorJsonFormatNotSupported({
|
|
60
141
|
command: "db schema-verify",
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
try {
|
|
70
|
-
contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
|
|
71
|
-
} catch (error) {
|
|
72
|
-
if (error instanceof Error && error.code === "ENOENT") {
|
|
73
|
-
throw errorFileNotFound(contractPathAbsolute, {
|
|
74
|
-
why: `Contract file not found at ${contractPathAbsolute}`
|
|
75
|
-
});
|
|
76
|
-
}
|
|
77
|
-
throw errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
78
|
-
why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
const contractJson = JSON.parse(contractJsonContent);
|
|
82
|
-
if (!config.driver) {
|
|
83
|
-
throw errorDriverRequired();
|
|
84
|
-
}
|
|
85
|
-
const driverDescriptor = config.driver;
|
|
86
|
-
const stack = createControlPlaneStack({
|
|
87
|
-
target: config.target,
|
|
88
|
-
adapter: config.adapter,
|
|
89
|
-
driver: driverDescriptor,
|
|
90
|
-
extensionPacks: config.extensionPacks
|
|
91
|
-
});
|
|
92
|
-
const familyInstance = config.family.create(stack);
|
|
93
|
-
const contractIR = familyInstance.validateContractIR(contractJson);
|
|
94
|
-
assertContractRequirementsSatisfied({ contract: contractIR, stack });
|
|
95
|
-
const dbUrl = options.db ?? config.db?.url;
|
|
96
|
-
if (!dbUrl) {
|
|
97
|
-
throw errorDatabaseUrlRequired();
|
|
98
|
-
}
|
|
99
|
-
const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
|
|
100
|
-
message: "Connecting to database...",
|
|
101
|
-
flags
|
|
102
|
-
});
|
|
103
|
-
try {
|
|
104
|
-
const rawComponents = [config.target, config.adapter, ...config.extensionPacks ?? []];
|
|
105
|
-
const frameworkComponents = assertFrameworkComponentsCompatible(
|
|
106
|
-
config.family.familyId,
|
|
107
|
-
config.target.targetId,
|
|
108
|
-
rawComponents
|
|
109
|
-
);
|
|
110
|
-
let schemaVerifyResult;
|
|
111
|
-
try {
|
|
112
|
-
schemaVerifyResult = await withSpinner(
|
|
113
|
-
() => familyInstance.schemaVerify({
|
|
114
|
-
driver,
|
|
115
|
-
contractIR,
|
|
116
|
-
strict: options.strict ?? false,
|
|
117
|
-
contractPath: contractPathAbsolute,
|
|
118
|
-
configPath,
|
|
119
|
-
frameworkComponents
|
|
120
|
-
}),
|
|
121
|
-
{
|
|
122
|
-
message: "Verifying database schema...",
|
|
123
|
-
flags
|
|
124
|
-
}
|
|
125
|
-
);
|
|
126
|
-
} catch (error) {
|
|
127
|
-
throw errorRuntime(error instanceof Error ? error.message : String(error), {
|
|
128
|
-
why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`
|
|
129
|
-
});
|
|
130
|
-
}
|
|
131
|
-
if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
|
|
132
|
-
console.log("");
|
|
133
|
-
}
|
|
134
|
-
return schemaVerifyResult;
|
|
135
|
-
} finally {
|
|
136
|
-
await driver.close();
|
|
137
|
-
}
|
|
138
|
-
});
|
|
142
|
+
format: "ndjson",
|
|
143
|
+
supportedFormats: ["object"]
|
|
144
|
+
})
|
|
145
|
+
);
|
|
146
|
+
const exitCode2 = handleResult(result2, flags);
|
|
147
|
+
process.exit(exitCode2);
|
|
148
|
+
}
|
|
149
|
+
const result = await executeDbSchemaVerifyCommand(options, flags);
|
|
139
150
|
const exitCode = handleResult(result, flags, (schemaVerifyResult) => {
|
|
140
151
|
if (flags.json === "object") {
|
|
141
152
|
console.log(formatSchemaVerifyJson(schemaVerifyResult));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/db-schema-verify.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type { ContractIR } from '@prisma-next/contract/ir';\nimport {\n errorDatabaseUrlRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorRuntime,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type { VerifyDatabaseSchemaResult } from '@prisma-next/core-control-plane/types';\nimport { createControlPlaneStack } from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { performAction } from '../utils/action';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport {\n assertContractRequirementsSatisfied,\n assertFrameworkComponentsCompatible,\n} from '../utils/framework-components';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbSchemaVerifyOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | boolean;\n readonly strict?: 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 createDbSchemaVerifyCommand(): Command {\n const command = new Command('schema-verify');\n setCommandDescriptions(\n command,\n 'Check whether the database schema satisfies your contract',\n 'Verifies that your database schema satisfies the emitted contract. Compares table structures,\\n' +\n 'column types, constraints, and extensions. Reports any mismatches via a contract-shaped\\n' +\n 'verification tree. This is a read-only operation that does not modify the database.',\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 or ndjson)', false)\n .option('--strict', 'Strict mode: extra schema elements cause failures', 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: DbSchemaVerifyOptions) => {\n const flags = parseGlobalFlags(options);\n\n const result = await performAction(async () => {\n // Load config (file I/O)\n const config = await loadConfig(options.config);\n // Normalize config path for display (match contract path format - no ./ prefix)\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 // Convert to relative path for display\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header (only for human-readable output)\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 const header = formatStyledHeader({\n command: 'db schema-verify',\n description: 'Check whether the database schema satisfies your contract',\n url: 'https://pris.ly/db-schema-verify',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file (file I/O)\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 });\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 const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n\n // Check for driver (needed for family instance creation)\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n // Create family instance (needed for contract validation)\n const stack = createControlPlaneStack({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensionPacks: config.extensionPacks,\n });\n const familyInstance = config.family.create(stack);\n\n // Validate contract using instance validator\n const contractIR = familyInstance.validateContractIR(contractJson) as ContractIR;\n\n // Validate contract requirements fail-fast before connecting to database\n assertContractRequirementsSatisfied({ contract: contractIR, stack });\n\n // Resolve database URL\n const dbUrl = options.db ?? config.db?.url;\n if (!dbUrl) {\n throw errorDatabaseUrlRequired();\n }\n\n // Create driver\n const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {\n message: 'Connecting to database...',\n flags,\n });\n\n try {\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 // Call family instance schemaVerify method\n let schemaVerifyResult: VerifyDatabaseSchemaResult;\n try {\n schemaVerifyResult = await withSpinner(\n () =>\n familyInstance.schemaVerify({\n driver,\n contractIR,\n strict: options.strict ?? false,\n contractPath: contractPathAbsolute,\n configPath,\n frameworkComponents,\n }),\n {\n message: 'Verifying database schema...',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from schemaVerify() in structured error\n throw errorRuntime(error instanceof Error ? error.message : String(error), {\n why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`,\n });\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 // Return result (don't throw for logical mismatches - handle exit code separately)\n return schemaVerifyResult;\n } finally {\n // Ensure driver connection is closed\n await driver.close();\n }\n });\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (schemaVerifyResult) => {\n // Output based on flags\n if (flags.json === 'object') {\n // JSON output to stdout\n console.log(formatSchemaVerifyJson(schemaVerifyResult));\n } else {\n // Human-readable output to stdout\n const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n\n // For logical schema mismatches, check if verification passed\n // Infra errors already handled by handleResult (returns non-zero exit code)\n if (result.ok && !result.value.ok) {\n // Schema verification failed - exit with code 1\n process.exit(1);\n } else {\n // Success or infra error - use exit code from handleResult\n process.exit(exitCode);\n }\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAElC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,+BAA+B;AACxC,SAAS,eAAe;AAkCjB,SAAS,8BAAuC;AACrD,QAAM,UAAU,IAAI,QAAQ,eAAe;AAC3C;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,EAGF;AACA,UACG,cAAc;AAAA,IACb,YAAY,CAAC,QAAQ;AACnB,YAAM,QAAQ,iBAAiB,CAAC,CAAC;AACjC,aAAO,kBAAkB,EAAE,SAAS,KAAK,MAAM,CAAC;AAAA,IAClD;AAAA,EACF,CAAC,EACA,OAAO,cAAc,4BAA4B,EACjD,OAAO,mBAAmB,+BAA+B,EACzD,OAAO,mBAAmB,qCAAqC,KAAK,EACpE,OAAO,YAAY,qDAAqD,KAAK,EAC7E,OAAO,eAAe,yBAAyB,EAC/C,OAAO,iBAAiB,qCAAqC,EAC7D,OAAO,gBAAgB,4CAA4C,EACnE,OAAO,gBAAgB,0BAA0B,EACjD,OAAO,WAAW,oBAAoB,EACtC,OAAO,cAAc,sBAAsB,EAC3C,OAAO,OAAO,YAAmC;AAChD,UAAM,QAAQ,iBAAiB,OAAO;AAEtC,UAAM,SAAS,MAAM,cAAc,YAAY;AAE7C,YAAM,SAAS,MAAM,WAAW,QA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F,CAAC;AAGD,UAAM,WAAW,aAAa,QAAQ,OAAO,CAAC,uBAAuB;AAEnE,UAAI,MAAM,SAAS,UAAU;AAE3B,gBAAQ,IAAI,uBAAuB,kBAAkB,CAAC;AAAA,MACxD,OAAO;AAEL,cAAM,SAAS,yBAAyB,oBAAoB,KAAK;AACjE,YAAI,QAAQ;AACV,kBAAQ,IAAI,MAAM;AAAA,QACpB;AAAA,MACF;AAAA,IACF,CAAC;AAID,QAAI,OAAO,MAAM,CAAC,OAAO,MAAM,IAAI;AAEjC,cAAQ,KAAK,CAAC;AAAA,IAChB,OAAO;AAEL,cAAQ,KAAK,QAAQ;AAAA,IACvB;AAAA,EACF,CAAC;AAEH,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/commands/db-schema-verify.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type { VerifyDatabaseSchemaResult } 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 errorContractValidationFailed,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\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 formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport { handleResult } from '../utils/result-handler';\n\ninterface DbSchemaVerifyOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | boolean;\n readonly strict?: 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 * Executes the db schema-verify command and returns a structured Result.\n */\nasync function executeDbSchemaVerifyCommand(\n options: DbSchemaVerifyOptions,\n flags: GlobalFlags,\n): Promise<Result<VerifyDatabaseSchemaResult, 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 const header = formatStyledHeader({\n command: 'db schema-verify',\n description: 'Check whether the database schema satisfies your contract',\n url: 'https://pris.ly/db-schema-verify',\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 schema-verify (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 schema-verify' }));\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 const schemaVerifyResult = await client.schemaVerify({\n contractIR: contractJson,\n strict: options.strict ?? false,\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 return ok(schemaVerifyResult);\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 schema-verify: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createDbSchemaVerifyCommand(): Command {\n const command = new Command('schema-verify');\n setCommandDescriptions(\n command,\n 'Check whether the database schema satisfies your contract',\n 'Verifies that your database schema satisfies the emitted contract. Compares table structures,\\n' +\n 'column types, constraints, and extensions. Reports any mismatches via a contract-shaped\\n' +\n 'verification tree. This is a read-only operation that does not modify the database.',\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('--strict', 'Strict mode: extra schema elements cause failures', 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: DbSchemaVerifyOptions) => {\n const flags = parseGlobalFlags(options);\n\n // Validate JSON format option\n if (flags.json === 'ndjson') {\n const result = notOk(\n errorJsonFormatNotSupported({\n command: 'db schema-verify',\n format: 'ndjson',\n supportedFormats: ['object'],\n }),\n );\n const exitCode = handleResult(result, flags);\n process.exit(exitCode);\n }\n\n const result = await executeDbSchemaVerifyCommand(options, flags);\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (schemaVerifyResult) => {\n if (flags.json === 'object') {\n console.log(formatSchemaVerifyJson(schemaVerifyResult));\n } else {\n const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n\n // For logical schema mismatches, check if verification passed\n // Infra errors already handled by handleResult (returns non-zero exit code)\n if (result.ok && !result.value.ok) {\n // Schema verification failed - exit with code 1\n process.exit(1);\n } else {\n // Success or infra error - use exit code from handleResult\n process.exit(exitCode);\n }\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAElC,SAAS,OAAO,UAAuB;AACvC,SAAS,eAAe;AA0CxB,eAAe,6BACb,SACA,OACiE;AAEjE,QAAM,SAAS,MAAM,WAAW,QAAQ,MAAM;AAC9C,QAAM,aAAa,QAAQ,SACvB,SAAS,QAAQ,IAAI,GAAG,QAAQ,QAAQ,MAAM,CAAC,IAC/C;AACJ,QAAM,uBAAuB,OAAO,UAAU,SAC1C,QAAQ,OAAO,SAAS,MAAM,IAC9B,QAAQ,0BAA0B;AACtC,QAAM,eAAe,SAAS,QAAQ,IAAI,GAAG,oBAAoB;AAGjE,MAAI,MAAM,SAAS,YAAY,CAAC,MAAM,OAAO;AAC3C,UAAM,UAAmD;AAAA,MACvD,EAAE,OAAO,UAAU,O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