@prisma-next/cli 0.3.0-dev.7 → 0.3.0-dev.71
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/LICENSE +201 -0
- package/README.md +314 -80
- package/dist/cli-errors-JlPTsazx.mjs +3 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.js +1 -2376
- package/dist/cli.mjs +198 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/client-PimzSD1f.mjs +981 -0
- package/dist/client-PimzSD1f.mjs.map +1 -0
- package/dist/commands/contract-emit.d.mts +7 -0
- package/dist/commands/contract-emit.d.mts.map +1 -0
- package/dist/commands/contract-emit.mjs +150 -0
- package/dist/commands/contract-emit.mjs.map +1 -0
- package/dist/commands/db-init.d.mts +7 -0
- package/dist/commands/db-init.d.mts.map +1 -0
- package/dist/commands/db-init.mjs +132 -0
- package/dist/commands/db-init.mjs.map +1 -0
- package/dist/commands/db-introspect.d.mts +7 -0
- package/dist/commands/db-introspect.d.mts.map +1 -0
- package/dist/commands/db-introspect.mjs +117 -0
- package/dist/commands/db-introspect.mjs.map +1 -0
- package/dist/commands/db-schema-verify.d.mts +7 -0
- package/dist/commands/db-schema-verify.d.mts.map +1 -0
- package/dist/commands/db-schema-verify.mjs +119 -0
- package/dist/commands/db-schema-verify.mjs.map +1 -0
- package/dist/commands/db-sign.d.mts +7 -0
- package/dist/commands/db-sign.d.mts.map +1 -0
- package/dist/commands/db-sign.mjs +141 -0
- package/dist/commands/db-sign.mjs.map +1 -0
- package/dist/commands/db-update.d.mts +7 -0
- package/dist/commands/db-update.d.mts.map +1 -0
- package/dist/commands/db-update.mjs +121 -0
- package/dist/commands/db-update.mjs.map +1 -0
- package/dist/commands/db-verify.d.mts +7 -0
- package/dist/commands/db-verify.d.mts.map +1 -0
- package/dist/commands/db-verify.mjs +132 -0
- package/dist/commands/db-verify.mjs.map +1 -0
- package/dist/commands/migration-apply.d.mts +23 -0
- package/dist/commands/migration-apply.d.mts.map +1 -0
- package/dist/commands/migration-apply.mjs +249 -0
- package/dist/commands/migration-apply.mjs.map +1 -0
- package/dist/commands/migration-plan.d.mts +25 -0
- package/dist/commands/migration-plan.d.mts.map +1 -0
- package/dist/commands/migration-plan.mjs +266 -0
- package/dist/commands/migration-plan.mjs.map +1 -0
- package/dist/commands/migration-show.d.mts +28 -0
- package/dist/commands/migration-show.d.mts.map +1 -0
- package/dist/commands/migration-show.mjs +138 -0
- package/dist/commands/migration-show.mjs.map +1 -0
- package/dist/commands/migration-status.d.mts +35 -0
- package/dist/commands/migration-status.d.mts.map +1 -0
- package/dist/commands/migration-status.mjs +259 -0
- package/dist/commands/migration-status.mjs.map +1 -0
- package/dist/commands/migration-verify.d.mts +16 -0
- package/dist/commands/migration-verify.d.mts.map +1 -0
- package/dist/commands/migration-verify.mjs +86 -0
- package/dist/commands/migration-verify.mjs.map +1 -0
- package/dist/config-loader-PPf4CtDj.mjs +43 -0
- package/dist/config-loader-PPf4CtDj.mjs.map +1 -0
- package/dist/{config-loader.d.ts → config-loader.d.mts} +8 -3
- package/dist/config-loader.d.mts.map +1 -0
- package/dist/config-loader.mjs +3 -0
- package/dist/exports/config-types.d.mts +2 -0
- package/dist/exports/config-types.mjs +3 -0
- package/dist/exports/control-api.d.mts +621 -0
- package/dist/exports/control-api.d.mts.map +1 -0
- package/dist/exports/control-api.mjs +97 -0
- package/dist/exports/control-api.mjs.map +1 -0
- package/dist/{load-ts-contract.d.ts → exports/index.d.mts} +10 -5
- package/dist/exports/index.d.mts.map +1 -0
- package/dist/exports/index.mjs +130 -0
- package/dist/exports/index.mjs.map +1 -0
- package/dist/extract-sql-ddl-BmlKvk4o.mjs +26 -0
- package/dist/extract-sql-ddl-BmlKvk4o.mjs.map +1 -0
- package/dist/framework-components-CjV_jD8f.mjs +59 -0
- package/dist/framework-components-CjV_jD8f.mjs.map +1 -0
- package/dist/migration-command-scaffold-DfY_F3ev.mjs +97 -0
- package/dist/migration-command-scaffold-DfY_F3ev.mjs.map +1 -0
- package/dist/progress-adapter-DENrzF6I.mjs +49 -0
- package/dist/progress-adapter-DENrzF6I.mjs.map +1 -0
- package/dist/result-handler-iA9JtUC7.mjs +1186 -0
- package/dist/result-handler-iA9JtUC7.mjs.map +1 -0
- package/package.json +75 -38
- package/src/cli.ts +43 -0
- package/src/commands/contract-emit.ts +221 -111
- package/src/commands/db-init.ts +217 -426
- package/src/commands/db-introspect.ts +148 -185
- package/src/commands/db-schema-verify.ts +162 -149
- package/src/commands/db-sign.ts +215 -202
- package/src/commands/db-update.ts +220 -0
- package/src/commands/db-verify.ts +193 -156
- package/src/commands/migration-apply.ts +431 -0
- package/src/commands/migration-plan.ts +446 -0
- package/src/commands/migration-show.ts +255 -0
- package/src/commands/migration-status.ts +436 -0
- package/src/commands/migration-verify.ts +151 -0
- package/src/config-loader.ts +13 -3
- package/src/control-api/client.ts +605 -0
- package/src/control-api/errors.ts +9 -0
- package/src/control-api/operations/contract-emit.ts +161 -0
- package/src/control-api/operations/db-init.ts +286 -0
- package/src/control-api/operations/db-update.ts +221 -0
- package/src/control-api/operations/extract-sql-ddl.ts +47 -0
- package/src/control-api/operations/migration-apply.ts +195 -0
- package/src/control-api/operations/migration-helpers.ts +49 -0
- package/src/control-api/types.ts +687 -0
- package/src/exports/config-types.ts +3 -3
- package/src/exports/control-api.ts +53 -0
- package/src/load-ts-contract.ts +16 -11
- package/src/utils/cli-errors.ts +3 -1
- package/src/utils/command-helpers.ts +92 -3
- package/src/utils/framework-components.ts +11 -30
- package/src/utils/migration-command-scaffold.ts +190 -0
- package/src/utils/output.ts +363 -25
- package/src/utils/progress-adapter.ts +86 -0
- package/dist/chunk-464LNZCE.js +0 -134
- package/dist/chunk-464LNZCE.js.map +0 -1
- package/dist/chunk-BZMBKEEQ.js +0 -997
- package/dist/chunk-BZMBKEEQ.js.map +0 -1
- package/dist/chunk-HWYQOCAJ.js +0 -47
- package/dist/chunk-HWYQOCAJ.js.map +0 -1
- package/dist/chunk-ZKYEJROM.js +0 -94
- package/dist/chunk-ZKYEJROM.js.map +0 -1
- package/dist/cli.d.ts +0 -2
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/commands/contract-emit.d.ts +0 -3
- package/dist/commands/contract-emit.d.ts.map +0 -1
- package/dist/commands/contract-emit.js +0 -9
- package/dist/commands/contract-emit.js.map +0 -1
- package/dist/commands/db-init.d.ts +0 -3
- package/dist/commands/db-init.d.ts.map +0 -1
- package/dist/commands/db-init.js +0 -341
- package/dist/commands/db-init.js.map +0 -1
- package/dist/commands/db-introspect.d.ts +0 -3
- package/dist/commands/db-introspect.d.ts.map +0 -1
- package/dist/commands/db-introspect.js +0 -190
- package/dist/commands/db-introspect.js.map +0 -1
- package/dist/commands/db-schema-verify.d.ts +0 -3
- package/dist/commands/db-schema-verify.d.ts.map +0 -1
- package/dist/commands/db-schema-verify.js +0 -164
- package/dist/commands/db-schema-verify.js.map +0 -1
- package/dist/commands/db-sign.d.ts +0 -3
- package/dist/commands/db-sign.d.ts.map +0 -1
- package/dist/commands/db-sign.js +0 -199
- package/dist/commands/db-sign.js.map +0 -1
- package/dist/commands/db-verify.d.ts +0 -3
- package/dist/commands/db-verify.d.ts.map +0 -1
- package/dist/commands/db-verify.js +0 -173
- package/dist/commands/db-verify.js.map +0 -1
- package/dist/config-loader.d.ts.map +0 -1
- package/dist/config-loader.js +0 -7
- package/dist/config-loader.js.map +0 -1
- package/dist/exports/config-types.d.ts +0 -3
- package/dist/exports/config-types.d.ts.map +0 -1
- package/dist/exports/config-types.js +0 -6
- package/dist/exports/config-types.js.map +0 -1
- package/dist/exports/index.d.ts +0 -4
- package/dist/exports/index.d.ts.map +0 -1
- package/dist/exports/index.js +0 -175
- package/dist/exports/index.js.map +0 -1
- package/dist/load-ts-contract.d.ts.map +0 -1
- package/dist/utils/action.d.ts +0 -16
- package/dist/utils/action.d.ts.map +0 -1
- package/dist/utils/cli-errors.d.ts +0 -7
- package/dist/utils/cli-errors.d.ts.map +0 -1
- package/dist/utils/command-helpers.d.ts +0 -12
- package/dist/utils/command-helpers.d.ts.map +0 -1
- package/dist/utils/framework-components.d.ts +0 -81
- package/dist/utils/framework-components.d.ts.map +0 -1
- package/dist/utils/global-flags.d.ts +0 -25
- package/dist/utils/global-flags.d.ts.map +0 -1
- package/dist/utils/output.d.ts +0 -142
- package/dist/utils/output.d.ts.map +0 -1
- package/dist/utils/result-handler.d.ts +0 -15
- package/dist/utils/result-handler.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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"db-update.mjs","names":["exhaustive: never","exitCode"],"sources":["../../src/commands/db-update.ts"],"sourcesContent":["import { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { ContractValidationError } from '../control-api/errors';\nimport type { DbUpdateFailure } from '../control-api/types';\nimport {\n CliStructuredError,\n errorContractValidationFailed,\n errorDestructiveChanges,\n errorJsonFormatNotSupported,\n errorMigrationPlanningFailed,\n errorRunnerFailed,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport type { MigrationCommandOptions } from '../utils/command-helpers';\nimport { sanitizeErrorMessage, setCommandDescriptions } from '../utils/command-helpers';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport {\n addMigrationCommandOptions,\n prepareMigrationContext,\n} from '../utils/migration-command-scaffold';\nimport {\n formatCommandHelp,\n formatMigrationApplyOutput,\n formatMigrationJson,\n formatMigrationPlanOutput,\n type MigrationCommandResult,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\n\ntype DbUpdateOptions = MigrationCommandOptions & {\n readonly acceptDataLoss?: boolean;\n};\n\n/**\n * Maps a DbUpdateFailure to a CliStructuredError for consistent error handling.\n */\nfunction mapDbUpdateFailure(failure: DbUpdateFailure): CliStructuredError {\n if (failure.code === 'PLANNING_FAILED') {\n return errorMigrationPlanningFailed({ conflicts: failure.conflicts ?? [] });\n }\n\n if (failure.code === 'RUNNER_FAILED') {\n return errorRunnerFailed(failure.summary, {\n why: failure.why ?? 'Migration runner failed',\n fix: 'Inspect the reported conflict, reconcile schema drift if needed, then re-run `prisma-next db update`',\n ...ifDefined('meta', failure.meta),\n });\n }\n\n if (failure.code === 'DESTRUCTIVE_CHANGES') {\n return errorDestructiveChanges(failure.summary, {\n ...ifDefined('why', failure.why),\n fix: 'Use `prisma-next db update --plan` to preview, then re-run with `--accept-data-loss` to apply destructive changes',\n ...ifDefined('meta', failure.meta),\n });\n }\n\n const exhaustive: never = failure.code;\n throw new Error(`Unhandled DbUpdateFailure code: ${exhaustive}`);\n}\n\n/**\n * Executes the db update command and returns a structured Result.\n */\nasync function executeDbUpdateCommand(\n options: DbUpdateOptions,\n flags: GlobalFlags,\n startTime: number,\n): Promise<Result<MigrationCommandResult, CliStructuredError>> {\n // Prepare shared migration context (config, contract, connection, client)\n const ctxResult = await prepareMigrationContext(options, flags, {\n commandName: 'db update',\n description: 'Update your database schema to match your contract',\n url: 'https://pris.ly/db-update',\n });\n if (!ctxResult.ok) {\n return ctxResult;\n }\n const { client, contractJson, dbConnection, onProgress, contractPathAbsolute } = ctxResult.value;\n\n try {\n // Call dbUpdate with connection and progress callback\n const result = await client.dbUpdate({\n contractIR: contractJson,\n mode: options.plan ? 'plan' : 'apply',\n connection: dbConnection,\n ...(options.acceptDataLoss ? { acceptDataLoss: true } : {}),\n onProgress,\n });\n\n // Handle failures by mapping to CLI structured error\n if (!result.ok) {\n return notOk(mapDbUpdateFailure(result.failure));\n }\n\n // Convert success result to CLI output format\n const dbUpdateResult: MigrationCommandResult = {\n ok: true,\n mode: result.value.mode,\n plan: {\n targetId: ctxResult.value.config.target.targetId,\n destination: {\n storageHash: result.value.destination.storageHash,\n ...ifDefined('profileHash', result.value.destination.profileHash),\n },\n operations: result.value.plan.operations.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n })),\n ...ifDefined('sql', result.value.plan.sql),\n },\n ...ifDefined(\n 'execution',\n result.value.execution\n ? {\n operationsPlanned: result.value.execution.operationsPlanned,\n operationsExecuted: result.value.execution.operationsExecuted,\n }\n : undefined,\n ),\n ...ifDefined(\n 'marker',\n result.value.marker\n ? {\n storageHash: result.value.marker.storageHash,\n ...ifDefined('profileHash', result.value.marker.profileHash),\n }\n : undefined,\n ),\n summary: result.value.summary,\n timings: { total: Date.now() - startTime },\n };\n\n return ok(dbUpdateResult);\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n\n if (error instanceof ContractValidationError) {\n return notOk(\n errorContractValidationFailed(`Contract validation failed: ${error.message}`, {\n where: { path: contractPathAbsolute },\n }),\n );\n }\n\n const rawMessage = error instanceof Error ? error.message : String(error);\n const safeMessage = sanitizeErrorMessage(\n rawMessage,\n typeof dbConnection === 'string' ? dbConnection : undefined,\n );\n return notOk(\n errorUnexpected(safeMessage, {\n why: `Unexpected error during db update: ${safeMessage}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createDbUpdateCommand(): Command {\n const command = new Command('update');\n setCommandDescriptions(\n command,\n 'Update your database schema to match your contract',\n 'Compares your database schema to the emitted contract and applies the necessary\\n' +\n 'changes. Works on any database, whether or not it has been initialized with `db init`.\\n' +\n 'Use --plan to preview operations before applying.',\n );\n addMigrationCommandOptions(command);\n command.option(\n '--accept-data-loss',\n 'Confirm destructive operations (required when plan includes drops or type changes)',\n false,\n );\n command.configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n });\n command.action(async (options: DbUpdateOptions) => {\n const flags = parseGlobalFlags(options);\n const startTime = Date.now();\n\n if (flags.json === 'ndjson') {\n const result = notOk(\n errorJsonFormatNotSupported({\n command: 'db update',\n format: 'ndjson',\n supportedFormats: ['object'],\n }),\n );\n const exitCode = handleResult(result, flags);\n process.exit(exitCode);\n }\n\n const result = await executeDbUpdateCommand(options, flags, startTime);\n const exitCode = handleResult(result, flags, (dbUpdateResult) => {\n if (flags.json === 'object') {\n console.log(formatMigrationJson(dbUpdateResult));\n } else {\n const output =\n dbUpdateResult.mode === 'plan'\n ? formatMigrationPlanOutput(dbUpdateResult, flags)\n : formatMigrationApplyOutput(dbUpdateResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;AAqCA,SAAS,mBAAmB,SAA8C;AACxE,KAAI,QAAQ,SAAS,kBACnB,QAAO,6BAA6B,EAAE,WAAW,QAAQ,aAAa,EAAE,EAAE,CAAC;AAG7E,KAAI,QAAQ,SAAS,gBACnB,QAAO,kBAAkB,QAAQ,SAAS;EACxC,KAAK,QAAQ,OAAO;EACpB,KAAK;EACL,GAAG,UAAU,QAAQ,QAAQ,KAAK;EACnC,CAAC;AAGJ,KAAI,QAAQ,SAAS,sBACnB,QAAO,wBAAwB,QAAQ,SAAS;EAC9C,GAAG,UAAU,OAAO,QAAQ,IAAI;EAChC,KAAK;EACL,GAAG,UAAU,QAAQ,QAAQ,KAAK;EACnC,CAAC;CAGJ,MAAMA,aAAoB,QAAQ;AAClC,OAAM,IAAI,MAAM,mCAAmC,aAAa;;;;;AAMlE,eAAe,uBACb,SACA,OACA,WAC6D;CAE7D,MAAM,YAAY,MAAM,wBAAwB,SAAS,OAAO;EAC9D,aAAa;EACb,aAAa;EACb,KAAK;EACN,CAAC;AACF,KAAI,CAAC,UAAU,GACb,QAAO;CAET,MAAM,EAAE,QAAQ,cAAc,cAAc,YAAY,yBAAyB,UAAU;AAE3F,KAAI;EAEF,MAAM,SAAS,MAAM,OAAO,SAAS;GACnC,YAAY;GACZ,MAAM,QAAQ,OAAO,SAAS;GAC9B,YAAY;GACZ,GAAI,QAAQ,iBAAiB,EAAE,gBAAgB,MAAM,GAAG,EAAE;GA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AAQ,SAAS;AACrC,wBACE,SACA,sDACA,6NAGD;AACD,4BAA2B,QAAQ;AACnC,SAAQ,OACN,sBACA,sFACA,MACD;AACD,SAAQ,cAAc,EACpB,aAAa,QAAQ;AAEnB,SAAO,kBAAkB;GAAE,SAAS;GAAK,OAD3B,iBAAiB,EAAE,CAAC;GACc,CAAC;IAEpD,CAAC;AACF,SAAQ,OAAO,OAAO,YAA6B;EACjD,MAAM,QAAQ,iBAAiB,QAAQ;EACvC,MAAM,YAAY,KAAK,KAAK;AAE5B,MAAI,MAAM,SAAS,UAAU;GAQ3B,MAAMC,aAAW,aAPF,MACb,4BAA4B;IAC1B,SAAS;IACT,QAAQ;IACR,kBAAkB,CAAC,SAAS;IAC7B,CAAC,CACH,EACqC,MAAM;AAC5C,WAAQ,KAAKA,WAAS;;EAIxB,MAAM,WAAW,aADF,MAAM,uBAAuB,SAAS,OAAO,UAAU,EAChC,QAAQ,mBAAmB;AAC/D,OAAI,MAAM,SAAS,SACjB,SAAQ,IAAI,oBAAoB,eAAe,CAAC;QAC3C;IACL,MAAM,SACJ,eAAe,SAAS,SACpB,0BAA0B,gBAAgB,MAAM,GAChD,2BAA2B,gBAAgB,MAAM;AACvD,QAAI,OACF,SAAQ,IAAI,OAAO;;IAGvB;AACF,UAAQ,KAAK,SAAS;GACtB;AAEF,QAAO"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"db-verify.d.mts","names":[],"sources":["../../src/commands/db-verify.ts"],"sourcesContent":[],"mappings":";;;iBAqNgB,qBAAA,CAAA,GAAyB"}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { t as loadConfig } from "../config-loader-PPf4CtDj.mjs";
|
|
2
|
+
import { _ as errorUnexpected, a as errorDatabaseConnectionRequired, c as errorFileNotFound, d as errorMarkerMissing, g as errorTargetMismatch, i as errorContractValidationFailed, l as errorHashMismatch, m as errorRuntime, s as errorDriverRequired, t as CliStructuredError, u as errorJsonFormatNotSupported } from "../cli-errors-JlPTsazx.mjs";
|
|
3
|
+
import { n as ContractValidationError, t as createControlClient } from "../client-PimzSD1f.mjs";
|
|
4
|
+
import { C as parseGlobalFlags, D as setCommandDescriptions, S as formatVerifyOutput, T as resolveContractPath, n as formatCommandHelp, t as handleResult, w as maskConnectionUrl, x as formatVerifyJson, y as formatStyledHeader } from "../result-handler-iA9JtUC7.mjs";
|
|
5
|
+
import { t as createProgressAdapter } from "../progress-adapter-DENrzF6I.mjs";
|
|
6
|
+
import { Command } from "commander";
|
|
7
|
+
import { notOk, ok } from "@prisma-next/utils/result";
|
|
8
|
+
import { relative, resolve } from "node:path";
|
|
9
|
+
import { ifDefined } from "@prisma-next/utils/defined";
|
|
10
|
+
import { readFile } from "node:fs/promises";
|
|
11
|
+
|
|
12
|
+
//#region src/commands/db-verify.ts
|
|
13
|
+
/**
|
|
14
|
+
* Maps a VerifyDatabaseResult failure to a CliStructuredError.
|
|
15
|
+
*/
|
|
16
|
+
function mapVerifyFailure(verifyResult) {
|
|
17
|
+
if (!verifyResult.ok && verifyResult.code) {
|
|
18
|
+
if (verifyResult.code === "PN-RTM-3001") return errorMarkerMissing();
|
|
19
|
+
if (verifyResult.code === "PN-RTM-3002") return errorHashMismatch({
|
|
20
|
+
expected: verifyResult.contract.storageHash,
|
|
21
|
+
...ifDefined("actual", verifyResult.marker?.storageHash)
|
|
22
|
+
});
|
|
23
|
+
if (verifyResult.code === "PN-RTM-3003") return errorTargetMismatch(verifyResult.target.expected, verifyResult.target.actual ?? "unknown");
|
|
24
|
+
}
|
|
25
|
+
return errorRuntime(verifyResult.summary);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Executes the db verify command and returns a structured Result.
|
|
29
|
+
*/
|
|
30
|
+
async function executeDbVerifyCommand(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 = resolveContractPath(config);
|
|
34
|
+
const contractPath = relative(process.cwd(), contractPathAbsolute);
|
|
35
|
+
if (flags.json !== "object" && !flags.quiet) {
|
|
36
|
+
const details = [{
|
|
37
|
+
label: "config",
|
|
38
|
+
value: configPath
|
|
39
|
+
}, {
|
|
40
|
+
label: "contract",
|
|
41
|
+
value: contractPath
|
|
42
|
+
}];
|
|
43
|
+
if (options.db) details.push({
|
|
44
|
+
label: "database",
|
|
45
|
+
value: maskConnectionUrl(options.db)
|
|
46
|
+
});
|
|
47
|
+
const header = formatStyledHeader({
|
|
48
|
+
command: "db verify",
|
|
49
|
+
description: "Check whether the database has been signed with your contract",
|
|
50
|
+
url: "https://pris.ly/db-verify",
|
|
51
|
+
details,
|
|
52
|
+
flags
|
|
53
|
+
});
|
|
54
|
+
console.log(header);
|
|
55
|
+
}
|
|
56
|
+
let contractJsonContent;
|
|
57
|
+
try {
|
|
58
|
+
contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (error instanceof Error && error.code === "ENOENT") return notOk(errorFileNotFound(contractPathAbsolute, {
|
|
61
|
+
why: `Contract file not found at ${contractPathAbsolute}`,
|
|
62
|
+
fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`
|
|
63
|
+
}));
|
|
64
|
+
return notOk(errorUnexpected(error instanceof Error ? error.message : String(error), { why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}` }));
|
|
65
|
+
}
|
|
66
|
+
let contractJson;
|
|
67
|
+
try {
|
|
68
|
+
contractJson = JSON.parse(contractJsonContent);
|
|
69
|
+
} catch (error) {
|
|
70
|
+
return notOk(errorContractValidationFailed(`Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`, { where: { path: contractPathAbsolute } }));
|
|
71
|
+
}
|
|
72
|
+
const dbConnection = options.db ?? config.db?.connection;
|
|
73
|
+
if (!dbConnection) return notOk(errorDatabaseConnectionRequired({ why: `Database connection is required for db verify (set db.connection in ${configPath}, or pass --db <url>)` }));
|
|
74
|
+
if (!config.driver) return notOk(errorDriverRequired({ why: "Config.driver is required for db verify" }));
|
|
75
|
+
const client = createControlClient({
|
|
76
|
+
family: config.family,
|
|
77
|
+
target: config.target,
|
|
78
|
+
adapter: config.adapter,
|
|
79
|
+
driver: config.driver,
|
|
80
|
+
extensionPacks: config.extensionPacks ?? []
|
|
81
|
+
});
|
|
82
|
+
const onProgress = createProgressAdapter({ flags });
|
|
83
|
+
try {
|
|
84
|
+
const verifyResult = await client.verify({
|
|
85
|
+
contractIR: contractJson,
|
|
86
|
+
connection: dbConnection,
|
|
87
|
+
onProgress
|
|
88
|
+
});
|
|
89
|
+
if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) console.log("");
|
|
90
|
+
if (!verifyResult.ok) return notOk(mapVerifyFailure(verifyResult));
|
|
91
|
+
return ok(verifyResult);
|
|
92
|
+
} catch (error) {
|
|
93
|
+
if (error instanceof CliStructuredError) return notOk(error);
|
|
94
|
+
if (error instanceof ContractValidationError) return notOk(errorContractValidationFailed(`Contract validation failed: ${error.message}`, { where: { path: contractPathAbsolute } }));
|
|
95
|
+
return notOk(errorUnexpected(error instanceof Error ? error.message : String(error), { why: `Unexpected error during db verify: ${error instanceof Error ? error.message : String(error)}` }));
|
|
96
|
+
} finally {
|
|
97
|
+
await client.close();
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function createDbVerifyCommand() {
|
|
101
|
+
const command = new Command("verify");
|
|
102
|
+
setCommandDescriptions(command, "Check whether the database has been signed with your contract", "Verifies that your database schema matches the emitted contract. Checks table structures,\ncolumn types, constraints, and codec coverage. Reports any mismatches or missing codecs.");
|
|
103
|
+
command.configureHelp({ formatHelp: (cmd) => {
|
|
104
|
+
return formatCommandHelp({
|
|
105
|
+
command: cmd,
|
|
106
|
+
flags: parseGlobalFlags({})
|
|
107
|
+
});
|
|
108
|
+
} }).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) => {
|
|
109
|
+
const flags = parseGlobalFlags(options);
|
|
110
|
+
if (flags.json === "ndjson") {
|
|
111
|
+
const exitCode$1 = handleResult(notOk(errorJsonFormatNotSupported({
|
|
112
|
+
command: "db verify",
|
|
113
|
+
format: "ndjson",
|
|
114
|
+
supportedFormats: ["object"]
|
|
115
|
+
})), flags);
|
|
116
|
+
process.exit(exitCode$1);
|
|
117
|
+
}
|
|
118
|
+
const exitCode = handleResult(await executeDbVerifyCommand(options, flags), flags, (verifyResult) => {
|
|
119
|
+
if (flags.json === "object") console.log(formatVerifyJson(verifyResult));
|
|
120
|
+
else {
|
|
121
|
+
const output = formatVerifyOutput(verifyResult, flags);
|
|
122
|
+
if (output) console.log(output);
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
process.exit(exitCode);
|
|
126
|
+
});
|
|
127
|
+
return command;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
//#endregion
|
|
131
|
+
export { createDbVerifyCommand };
|
|
132
|
+
//# sourceMappingURL=db-verify.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"db-verify.mjs","names":["details: Array<{ label: string; value: string }>","contractJsonContent: string","contractJson: Record<string, unknown>","exitCode"],"sources":["../../src/commands/db-verify.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type { VerifyDatabaseResult } from '@prisma-next/core-control-plane/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\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 { ContractValidationError } from '../control-api/errors';\nimport {\n CliStructuredError,\n errorContractValidationFailed,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorHashMismatch,\n errorJsonFormatNotSupported,\n errorMarkerMissing,\n errorRuntime,\n errorTargetMismatch,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport {\n maskConnectionUrl,\n resolveContractPath,\n setCommandDescriptions,\n} from '../utils/command-helpers';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatStyledHeader,\n formatVerifyJson,\n formatVerifyOutput,\n} from '../utils/output';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport { handleResult } from '../utils/result-handler';\n\ninterface DbVerifyOptions {\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\n/**\n * Maps a VerifyDatabaseResult failure to a CliStructuredError.\n */\nfunction mapVerifyFailure(verifyResult: VerifyDatabaseResult): CliStructuredError {\n if (!verifyResult.ok && verifyResult.code) {\n if (verifyResult.code === 'PN-RTM-3001') {\n return errorMarkerMissing();\n }\n if (verifyResult.code === 'PN-RTM-3002') {\n return errorHashMismatch({\n expected: verifyResult.contract.storageHash,\n ...ifDefined('actual', verifyResult.marker?.storageHash),\n });\n }\n if (verifyResult.code === 'PN-RTM-3003') {\n return errorTargetMismatch(\n verifyResult.target.expected,\n verifyResult.target.actual ?? 'unknown',\n );\n }\n // Unknown code - fall through to runtime error\n }\n return errorRuntime(verifyResult.summary);\n}\n\n/**\n * Executes the db verify command and returns a structured Result.\n */\nasync function executeDbVerifyCommand(\n options: DbVerifyOptions,\n flags: GlobalFlags,\n): Promise<Result<VerifyDatabaseResult, 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 = resolveContractPath(config);\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: maskConnectionUrl(options.db) });\n }\n const header = formatStyledHeader({\n command: 'db verify',\n description: 'Check whether the database has been signed with your contract',\n url: 'https://pris.ly/db-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 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 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 verifyResult = await client.verify({\n contractIR: contractJson,\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 // If verification failed, map to CLI structured error\n if (!verifyResult.ok) {\n return notOk(mapVerifyFailure(verifyResult));\n }\n\n return ok(verifyResult);\n } catch (error) {\n // Driver already throws CliStructuredError for connection failures\n if (error instanceof CliStructuredError) {\n return notOk(error);\n }\n\n if (error instanceof ContractValidationError) {\n return notOk(\n errorContractValidationFailed(`Contract validation failed: ${error.message}`, {\n where: { path: contractPathAbsolute },\n }),\n );\n }\n\n // Wrap unexpected errors\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during db verify: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createDbVerifyCommand(): Command {\n const command = new Command('verify');\n setCommandDescriptions(\n command,\n 'Check whether the database has been signed with your contract',\n 'Verifies that your database schema matches the emitted contract. Checks table structures,\\n' +\n 'column types, constraints, and codec coverage. Reports any mismatches or missing codecs.',\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: DbVerifyOptions) => {\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 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 executeDbVerifyCommand(options, flags);\n\n const exitCode = handleResult(result, flags, (verifyResult) => {\n if (flags.json === 'object') {\n console.log(formatVerifyJson(verifyResult));\n } else {\n const output = formatVerifyOutput(verifyResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuDA,SAAS,iBAAiB,cAAwD;AAChF,KAAI,CAAC,aAAa,MAAM,aAAa,MAAM;AACzC,MAAI,aAAa,SAAS,cACxB,QAAO,oBAAoB;AAE7B,MAAI,aAAa,SAAS,cACxB,QAAO,kBAAkB;GACvB,UAAU,aAAa,SAAS;GAChC,GAAG,UAAU,UAAU,aAAa,QAAQ,YAAY;GACzD,CAAC;AAEJ,MAAI,aAAa,SAAS,cACxB,QAAO,oBACL,aAAa,OAAO,UACpB,aAAa,OAAO,UAAU,UAC/B;;AAIL,QAAO,aAAa,aAAa,QAAQ;;;;;AAM3C,eAAe,uBACb,SACA,OAC2D;CAE3D,MAAM,SAAS,MAAM,WAAW,QAAQ,OAAO;CAC/C,MAAM,aAAa,QAAQ,SACvB,SAAS,QAAQ,KAAK,EAAE,QAAQ,QAAQ,OAAO,CAAC,GAChD;CACJ,MAAM,uBAAuB,oBAAoB,OAAO;CACxD,MAAM,eAAe,SAAS,QAAQ,KAAK,EAAE,qBAAqB;AAGlE,KAAI,MAAM,SAAS,YAAY,CAAC,MAAM,OAAO;EAC3C,MAAMA,UAAmD,CACvD;GAAE,OAAO;GAAU,OAAO;GAAY,EACtC;GAAE,OAAO;GAAY,OAAO;GAAc,CAC3C;AACD,MAAI,QAAQ,GACV,SAAQ,KAAK;GAAE,OAAO;GAAY,OAAO,kBAAkB,QAAQ,GAAG;GAAE,CAAC;EAE3E,MAAM,SAAS,mBAAmB;GAChC,SAAS;GACT,aAAa;GACb,KAAK;GACL;GACA;GACD,CAAC;A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AiB,aAAa,CAAC;QACtC;IACL,MAAM,SAAS,mBAAmB,cAAc,MAAM;AACtD,QAAI,OACF,SAAQ,IAAI,OAAO;;IAGvB;AACF,UAAQ,KAAK,SAAS;GACtB;AAEJ,QAAO"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
|
|
3
|
+
//#region src/commands/migration-apply.d.ts
|
|
4
|
+
interface MigrationApplyResult {
|
|
5
|
+
readonly ok: boolean;
|
|
6
|
+
readonly migrationsApplied: number;
|
|
7
|
+
readonly migrationsTotal: number;
|
|
8
|
+
readonly markerHash: string;
|
|
9
|
+
readonly applied: readonly {
|
|
10
|
+
readonly dirName: string;
|
|
11
|
+
readonly from: string;
|
|
12
|
+
readonly to: string;
|
|
13
|
+
readonly operationsExecuted: number;
|
|
14
|
+
}[];
|
|
15
|
+
readonly summary: string;
|
|
16
|
+
readonly timings: {
|
|
17
|
+
readonly total: number;
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
declare function createMigrationApplyCommand(): Command;
|
|
21
|
+
//#endregion
|
|
22
|
+
export { MigrationApplyResult, createMigrationApplyCommand };
|
|
23
|
+
//# sourceMappingURL=migration-apply.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-apply.d.mts","names":[],"sources":["../../src/commands/migration-apply.ts"],"sourcesContent":[],"mappings":";;;UAiDiB,oBAAA;;EAAA,SAAA,iBAAoB,EAAA,MAAA;EAiVrB,SAAA,eAAA,EAAA,MAA2B;;;;;;;;;;;;;iBAA3B,2BAAA,CAAA,GAA+B"}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { t as loadConfig } from "../config-loader-PPf4CtDj.mjs";
|
|
2
|
+
import { _ as errorUnexpected, a as errorDatabaseConnectionRequired, h as errorTargetMigrationNotSupported, m as errorRuntime, s as errorDriverRequired, t as CliStructuredError } from "../cli-errors-JlPTsazx.mjs";
|
|
3
|
+
import { t as createControlClient } from "../client-PimzSD1f.mjs";
|
|
4
|
+
import { C as parseGlobalFlags, D as setCommandDescriptions, T as resolveContractPath, n as formatCommandHelp, s as formatMigrationApplyCommandOutput, t as handleResult, w as maskConnectionUrl, y as formatStyledHeader } from "../result-handler-iA9JtUC7.mjs";
|
|
5
|
+
import { Command } from "commander";
|
|
6
|
+
import { notOk, ok } from "@prisma-next/utils/result";
|
|
7
|
+
import { relative, resolve } from "pathe";
|
|
8
|
+
import { EMPTY_CONTRACT_HASH } from "@prisma-next/core-control-plane/constants";
|
|
9
|
+
import { readFile } from "node:fs/promises";
|
|
10
|
+
import { findPath, reconstructGraph } from "@prisma-next/migration-tools/dag";
|
|
11
|
+
import { readMigrationsDir } from "@prisma-next/migration-tools/io";
|
|
12
|
+
import { MigrationToolsError } from "@prisma-next/migration-tools/types";
|
|
13
|
+
|
|
14
|
+
//#region src/commands/migration-apply.ts
|
|
15
|
+
function mapMigrationToolsError(error) {
|
|
16
|
+
if (MigrationToolsError.is(error)) return errorRuntime(error.message, {
|
|
17
|
+
why: error.why,
|
|
18
|
+
fix: error.fix,
|
|
19
|
+
meta: {
|
|
20
|
+
code: error.code,
|
|
21
|
+
...error.details ?? {}
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
return errorUnexpected(error instanceof Error ? error.message : String(error), { why: `Unexpected error during migration apply: ${error instanceof Error ? error.message : String(error)}` });
|
|
25
|
+
}
|
|
26
|
+
function mapApplyFailure(failure) {
|
|
27
|
+
return errorRuntime(failure.summary, {
|
|
28
|
+
why: failure.why ?? "Migration runner failed",
|
|
29
|
+
fix: "Fix the issue and re-run `prisma-next migration apply` — previously applied migrations are preserved.",
|
|
30
|
+
meta: failure.meta ?? {}
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
function packageToStep(pkg) {
|
|
34
|
+
return {
|
|
35
|
+
dirName: pkg.dirName,
|
|
36
|
+
from: pkg.manifest.from,
|
|
37
|
+
to: pkg.manifest.to,
|
|
38
|
+
toContract: pkg.manifest.toContract,
|
|
39
|
+
operations: pkg.ops
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
async function executeMigrationApplyCommand(options, flags, startTime) {
|
|
43
|
+
const config = await loadConfig(options.config);
|
|
44
|
+
const configPath = options.config ? relative(process.cwd(), resolve(options.config)) : "prisma-next.config.ts";
|
|
45
|
+
const migrationsDir = resolve(options.config ? resolve(options.config, "..") : process.cwd(), config.migrations?.dir ?? "migrations");
|
|
46
|
+
const migrationsRelative = relative(process.cwd(), migrationsDir);
|
|
47
|
+
const dbConnection = options.db ?? config.db?.connection;
|
|
48
|
+
if (!dbConnection) return notOk(errorDatabaseConnectionRequired({ why: `Database connection is required for migration apply (set db.connection in ${configPath}, or pass --db <url>)` }));
|
|
49
|
+
if (!config.driver) return notOk(errorDriverRequired({ why: "Config.driver is required for migration apply" }));
|
|
50
|
+
if (!config.target.migrations) return notOk(errorTargetMigrationNotSupported({ why: `Target "${config.target.id}" does not support migrations` }));
|
|
51
|
+
let destinationHash;
|
|
52
|
+
try {
|
|
53
|
+
const contractPathAbsolute = resolveContractPath(config);
|
|
54
|
+
const contractHash = JSON.parse(await readFile(contractPathAbsolute, "utf-8"))["storageHash"];
|
|
55
|
+
if (typeof contractHash !== "string") return notOk(errorRuntime("Current contract is missing storage hash", {
|
|
56
|
+
why: `The contract at ${relative(process.cwd(), contractPathAbsolute)} does not contain a valid storageHash`,
|
|
57
|
+
fix: "Run `prisma-next contract emit` and re-run `prisma-next migration apply`."
|
|
58
|
+
}));
|
|
59
|
+
destinationHash = contractHash;
|
|
60
|
+
} catch (error) {
|
|
61
|
+
return notOk(errorRuntime("Current contract is unavailable", {
|
|
62
|
+
why: `Failed to read contract hash before apply: ${error instanceof Error ? error.message : String(error)}`,
|
|
63
|
+
fix: "Run `prisma-next contract emit` to generate a valid contract.json, then retry apply."
|
|
64
|
+
}));
|
|
65
|
+
}
|
|
66
|
+
if (flags.json !== "object" && !flags.quiet) {
|
|
67
|
+
const details = [{
|
|
68
|
+
label: "config",
|
|
69
|
+
value: configPath
|
|
70
|
+
}, {
|
|
71
|
+
label: "migrations",
|
|
72
|
+
value: migrationsRelative
|
|
73
|
+
}];
|
|
74
|
+
if (typeof dbConnection === "string") details.push({
|
|
75
|
+
label: "database",
|
|
76
|
+
value: maskConnectionUrl(dbConnection)
|
|
77
|
+
});
|
|
78
|
+
const header = formatStyledHeader({
|
|
79
|
+
command: "migration apply",
|
|
80
|
+
description: "Apply planned migrations to the database",
|
|
81
|
+
url: "https://pris.ly/migration-apply",
|
|
82
|
+
details,
|
|
83
|
+
flags
|
|
84
|
+
});
|
|
85
|
+
console.log(header);
|
|
86
|
+
}
|
|
87
|
+
let packages;
|
|
88
|
+
try {
|
|
89
|
+
packages = (await readMigrationsDir(migrationsDir)).filter((p) => typeof p.manifest.migrationId === "string");
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (MigrationToolsError.is(error)) return notOk(mapMigrationToolsError(error));
|
|
92
|
+
throw error;
|
|
93
|
+
}
|
|
94
|
+
if (packages.length === 0) {
|
|
95
|
+
const client$1 = createControlClient({
|
|
96
|
+
family: config.family,
|
|
97
|
+
target: config.target,
|
|
98
|
+
adapter: config.adapter,
|
|
99
|
+
driver: config.driver,
|
|
100
|
+
extensionPacks: config.extensionPacks ?? []
|
|
101
|
+
});
|
|
102
|
+
try {
|
|
103
|
+
await client$1.connect(dbConnection);
|
|
104
|
+
const markerHash = (await client$1.readMarker())?.storageHash ?? EMPTY_CONTRACT_HASH;
|
|
105
|
+
if (markerHash !== EMPTY_CONTRACT_HASH) return notOk(errorRuntime("Database has state but no migrations exist", {
|
|
106
|
+
why: `The database marker hash "${markerHash}" exists but no attested migrations were found in ${migrationsRelative}`,
|
|
107
|
+
fix: "Ensure the migrations directory is correct, or reset the database with `prisma-next db init`.",
|
|
108
|
+
meta: {
|
|
109
|
+
markerHash,
|
|
110
|
+
migrationsDir: migrationsRelative
|
|
111
|
+
}
|
|
112
|
+
}));
|
|
113
|
+
if (destinationHash !== EMPTY_CONTRACT_HASH) return notOk(errorRuntime("Current contract has no planned migrations", {
|
|
114
|
+
why: `No attested migrations were found in ${migrationsRelative}, but current contract hash is "${destinationHash}"`,
|
|
115
|
+
fix: "Run `prisma-next migration plan` to create an attested migration for the current contract.",
|
|
116
|
+
meta: {
|
|
117
|
+
destinationHash,
|
|
118
|
+
migrationsDir: migrationsRelative
|
|
119
|
+
}
|
|
120
|
+
}));
|
|
121
|
+
} catch (error) {
|
|
122
|
+
if (CliStructuredError.is(error)) return notOk(error);
|
|
123
|
+
return notOk(errorUnexpected(error instanceof Error ? error.message : String(error), { why: `Unexpected error during migration apply: ${error instanceof Error ? error.message : String(error)}` }));
|
|
124
|
+
} finally {
|
|
125
|
+
await client$1.close();
|
|
126
|
+
}
|
|
127
|
+
return ok({
|
|
128
|
+
ok: true,
|
|
129
|
+
migrationsApplied: 0,
|
|
130
|
+
migrationsTotal: 0,
|
|
131
|
+
markerHash: EMPTY_CONTRACT_HASH,
|
|
132
|
+
applied: [],
|
|
133
|
+
summary: "No attested migrations found",
|
|
134
|
+
timings: { total: Date.now() - startTime }
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
let graph;
|
|
138
|
+
try {
|
|
139
|
+
graph = reconstructGraph(packages);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (MigrationToolsError.is(error)) return notOk(mapMigrationToolsError(error));
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
const client = createControlClient({
|
|
145
|
+
family: config.family,
|
|
146
|
+
target: config.target,
|
|
147
|
+
adapter: config.adapter,
|
|
148
|
+
driver: config.driver,
|
|
149
|
+
extensionPacks: config.extensionPacks ?? []
|
|
150
|
+
});
|
|
151
|
+
try {
|
|
152
|
+
await client.connect(dbConnection);
|
|
153
|
+
const marker = await client.readMarker();
|
|
154
|
+
if (marker?.storageHash === EMPTY_CONTRACT_HASH) return notOk(errorRuntime("Database marker contains the empty sentinel hash", {
|
|
155
|
+
why: `The marker row exists but contains the empty sentinel value "${EMPTY_CONTRACT_HASH}". This should never happen — the marker should contain the hash of the last applied contract.`,
|
|
156
|
+
fix: "The marker is corrupted. Reset the database with `prisma-next db init`, or manually update the marker to the correct contract hash.",
|
|
157
|
+
meta: { markerHash: EMPTY_CONTRACT_HASH }
|
|
158
|
+
}));
|
|
159
|
+
const markerHash = marker?.storageHash ?? EMPTY_CONTRACT_HASH;
|
|
160
|
+
if (markerHash !== EMPTY_CONTRACT_HASH && !graph.nodes.has(markerHash)) return notOk(errorRuntime("Database marker does not match any known migration", {
|
|
161
|
+
why: `The database marker hash "${markerHash}" is not found in the migration history at ${migrationsRelative}`,
|
|
162
|
+
fix: "Ensure the migrations directory matches this database, or reset the database with `prisma-next db init`.",
|
|
163
|
+
meta: {
|
|
164
|
+
markerHash,
|
|
165
|
+
knownNodes: [...graph.nodes]
|
|
166
|
+
}
|
|
167
|
+
}));
|
|
168
|
+
if (!graph.nodes.has(destinationHash)) return notOk(errorRuntime("Current contract has no planned migration path", {
|
|
169
|
+
why: `Current contract hash "${destinationHash}" is not present in the migration history at ${migrationsRelative}`,
|
|
170
|
+
fix: "Run `prisma-next migration plan` to create a migration for the current contract, then re-run apply.",
|
|
171
|
+
meta: {
|
|
172
|
+
destinationHash,
|
|
173
|
+
knownNodes: [...graph.nodes]
|
|
174
|
+
}
|
|
175
|
+
}));
|
|
176
|
+
const pendingPath = findPath(graph, markerHash, destinationHash);
|
|
177
|
+
if (!pendingPath) return notOk(errorRuntime("No migration path from current state to target", {
|
|
178
|
+
why: `Cannot find a path from marker hash "${markerHash}" to target "${destinationHash}"`,
|
|
179
|
+
fix: "Check the migration history for gaps or inconsistencies.",
|
|
180
|
+
meta: {
|
|
181
|
+
markerHash,
|
|
182
|
+
destinationHash
|
|
183
|
+
}
|
|
184
|
+
}));
|
|
185
|
+
if (pendingPath.length === 0) return ok({
|
|
186
|
+
ok: true,
|
|
187
|
+
migrationsApplied: 0,
|
|
188
|
+
migrationsTotal: 0,
|
|
189
|
+
markerHash,
|
|
190
|
+
applied: [],
|
|
191
|
+
summary: "Already up to date",
|
|
192
|
+
timings: { total: Date.now() - startTime }
|
|
193
|
+
});
|
|
194
|
+
const packageByDir = new Map(packages.map((pkg) => [pkg.dirName, pkg]));
|
|
195
|
+
const pendingMigrations = [];
|
|
196
|
+
for (const migration of pendingPath) {
|
|
197
|
+
const pkg = packageByDir.get(migration.dirName);
|
|
198
|
+
if (!pkg) return notOk(errorRuntime(`Migration package not found: ${migration.dirName}`, {
|
|
199
|
+
why: `The migration directory for path segment ${migration.from} → ${migration.to} was not found`,
|
|
200
|
+
fix: "Ensure all migration directories are present and intact."
|
|
201
|
+
}));
|
|
202
|
+
pendingMigrations.push(packageToStep(pkg));
|
|
203
|
+
}
|
|
204
|
+
if (!flags.quiet && flags.json !== "object") for (const migration of pendingMigrations) console.log(` Applying ${migration.dirName}...`);
|
|
205
|
+
const applyResult = await client.migrationApply({
|
|
206
|
+
originHash: markerHash,
|
|
207
|
+
destinationHash,
|
|
208
|
+
pendingMigrations
|
|
209
|
+
});
|
|
210
|
+
if (!applyResult.ok) return notOk(mapApplyFailure(applyResult.failure));
|
|
211
|
+
const { value } = applyResult;
|
|
212
|
+
return ok({
|
|
213
|
+
ok: true,
|
|
214
|
+
migrationsApplied: value.migrationsApplied,
|
|
215
|
+
migrationsTotal: pendingPath.length,
|
|
216
|
+
markerHash: value.markerHash,
|
|
217
|
+
applied: value.applied,
|
|
218
|
+
summary: value.summary,
|
|
219
|
+
timings: { total: Date.now() - startTime }
|
|
220
|
+
});
|
|
221
|
+
} catch (error) {
|
|
222
|
+
if (CliStructuredError.is(error)) return notOk(error);
|
|
223
|
+
return notOk(errorUnexpected(error instanceof Error ? error.message : String(error), { why: `Unexpected error during migration apply: ${error instanceof Error ? error.message : String(error)}` }));
|
|
224
|
+
} finally {
|
|
225
|
+
await client.close();
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
function createMigrationApplyCommand() {
|
|
229
|
+
const command = new Command("apply");
|
|
230
|
+
setCommandDescriptions(command, "Apply planned migrations to the database", "Applies previously planned migrations (created by `migration plan`) to a live database.\nCompares the database marker against the migration chain to determine which\nmigrations are pending, then executes them sequentially. Each migration runs\nin its own transaction. Does not plan new migrations — run `migration plan` first.");
|
|
231
|
+
command.configureHelp({ formatHelp: (cmd) => {
|
|
232
|
+
return formatCommandHelp({
|
|
233
|
+
command: cmd,
|
|
234
|
+
flags: parseGlobalFlags({})
|
|
235
|
+
});
|
|
236
|
+
} }).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) => {
|
|
237
|
+
const flags = parseGlobalFlags(options);
|
|
238
|
+
const exitCode = handleResult(await executeMigrationApplyCommand(options, flags, Date.now()), flags, (applyResult) => {
|
|
239
|
+
if (flags.json === "object") console.log(JSON.stringify(applyResult, null, 2));
|
|
240
|
+
else if (!flags.quiet) console.log(formatMigrationApplyCommandOutput(applyResult, flags));
|
|
241
|
+
});
|
|
242
|
+
process.exit(exitCode);
|
|
243
|
+
});
|
|
244
|
+
return command;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
//#endregion
|
|
248
|
+
export { createMigrationApplyCommand };
|
|
249
|
+
//# sourceMappingURL=migration-apply.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-apply.mjs","names":["destinationHash: string","details: Array<{ label: string; value: string }>","packages: readonly MigrationPackage[]","client","graph: MigrationGraph","pendingMigrations: MigrationApplyStep[]"],"sources":["../../src/commands/migration-apply.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { EMPTY_CONTRACT_HASH } from '@prisma-next/core-control-plane/constants';\nimport { findPath, reconstructGraph } from '@prisma-next/migration-tools/dag';\nimport { readMigrationsDir } from '@prisma-next/migration-tools/io';\nimport type { MigrationGraph, MigrationPackage } from '@prisma-next/migration-tools/types';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/types';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { relative, resolve } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport type { MigrationApplyFailure, MigrationApplyStep } from '../control-api/types';\nimport {\n CliStructuredError,\n type CliStructuredError as CliStructuredErrorType,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorRuntime,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport {\n maskConnectionUrl,\n resolveContractPath,\n setCommandDescriptions,\n} from '../utils/command-helpers';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatMigrationApplyCommandOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\n\ninterface MigrationApplyCommandOptions {\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 interface MigrationApplyResult {\n readonly ok: boolean;\n readonly migrationsApplied: number;\n readonly migrationsTotal: number;\n readonly markerHash: string;\n readonly applied: readonly {\n readonly dirName: string;\n readonly from: string;\n readonly to: string;\n readonly operationsExecuted: number;\n }[];\n readonly summary: string;\n readonly timings: {\n readonly total: number;\n };\n}\n\nfunction mapMigrationToolsError(error: unknown): CliStructuredErrorType {\n if (MigrationToolsError.is(error)) {\n return errorRuntime(error.message, {\n why: error.why,\n fix: error.fix,\n meta: { code: error.code, ...(error.details ?? {}) },\n });\n }\n return errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during migration apply: ${error instanceof Error ? error.message : String(error)}`,\n });\n}\n\nfunction mapApplyFailure(failure: MigrationApplyFailure): CliStructuredErrorType {\n return errorRuntime(failure.summary, {\n why: failure.why ?? 'Migration runner failed',\n fix: 'Fix the issue and re-run `prisma-next migration apply` — previously applied migrations are preserved.',\n meta: failure.meta ?? {},\n });\n}\n\nfunction packageToStep(pkg: MigrationPackage): MigrationApplyStep {\n return {\n dirName: pkg.dirName,\n from: pkg.manifest.from,\n to: pkg.manifest.to,\n toContract: pkg.manifest.toContract,\n operations: pkg.ops as MigrationApplyStep['operations'],\n };\n}\n\nasync function executeMigrationApplyCommand(\n options: MigrationApplyCommandOptions,\n flags: GlobalFlags,\n startTime: number,\n): Promise<Result<MigrationApplyResult, CliStructuredErrorType>> {\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 const migrationsDir = resolve(\n options.config ? resolve(options.config, '..') : process.cwd(),\n config.migrations?.dir ?? 'migrations',\n );\n const migrationsRelative = relative(process.cwd(), migrationsDir);\n\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n return notOk(\n errorDatabaseConnectionRequired({\n why: `Database connection is required for migration apply (set db.connection in ${configPath}, or pass --db <url>)`,\n }),\n );\n }\n\n if (!config.driver) {\n return notOk(errorDriverRequired({ why: 'Config.driver is required for migration apply' }));\n }\n\n const targetWithMigrations = config.target as typeof config.target & {\n readonly migrations?: unknown;\n };\n if (!targetWithMigrations.migrations) {\n return notOk(\n errorTargetMigrationNotSupported({\n why: `Target \"${config.target.id}\" does not support migrations`,\n }),\n );\n }\n\n let destinationHash: string;\n try {\n const contractPathAbsolute = resolveContractPath(config);\n const contractRaw = JSON.parse(await readFile(contractPathAbsolute, 'utf-8')) as Record<\n string,\n unknown\n >;\n const contractHash = contractRaw['storageHash'];\n if (typeof contractHash !== 'string') {\n return notOk(\n errorRuntime('Current contract is missing storage hash', {\n why: `The contract at ${relative(process.cwd(), contractPathAbsolute)} does not contain a valid storageHash`,\n fix: 'Run `prisma-next contract emit` and re-run `prisma-next migration apply`.',\n }),\n );\n }\n destinationHash = contractHash;\n } catch (error) {\n return notOk(\n errorRuntime('Current contract is unavailable', {\n why: `Failed to read contract hash before apply: ${error instanceof Error ? error.message : String(error)}`,\n fix: 'Run `prisma-next contract emit` to generate a valid contract.json, then retry apply.',\n }),\n );\n }\n\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'migrations', value: migrationsRelative },\n ];\n if (typeof dbConnection === 'string') {\n details.push({ label: 'database', value: maskConnectionUrl(dbConnection) });\n }\n const header = formatStyledHeader({\n command: 'migration apply',\n description: 'Apply planned migrations to the database',\n url: 'https://pris.ly/migration-apply',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Read migrations and build migration chain model (offline — no DB needed)\n let packages: readonly MigrationPackage[];\n try {\n const allPackages = await readMigrationsDir(migrationsDir);\n packages = allPackages.filter((p) => typeof p.manifest.migrationId === 'string');\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n\n if (packages.length === 0) {\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 try {\n await client.connect(dbConnection);\n const marker = await client.readMarker();\n const markerHash = marker?.storageHash ?? EMPTY_CONTRACT_HASH;\n if (markerHash !== EMPTY_CONTRACT_HASH) {\n return notOk(\n errorRuntime('Database has state but no migrations exist', {\n why: `The database marker hash \"${markerHash}\" exists but no attested migrations were found in ${migrationsRelative}`,\n fix: 'Ensure the migrations directory is correct, or reset the database with `prisma-next db init`.',\n meta: { markerHash, migrationsDir: migrationsRelative },\n }),\n );\n }\n if (destinationHash !== EMPTY_CONTRACT_HASH) {\n return notOk(\n errorRuntime('Current contract has no planned migrations', {\n why: `No attested migrations were found in ${migrationsRelative}, but current contract hash is \"${destinationHash}\"`,\n fix: 'Run `prisma-next migration plan` to create an attested migration for the current contract.',\n meta: { destinationHash, migrationsDir: migrationsRelative },\n }),\n );\n }\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during migration apply: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n } finally {\n await client.close();\n }\n return ok({\n ok: true,\n migrationsApplied: 0,\n migrationsTotal: 0,\n markerHash: EMPTY_CONTRACT_HASH,\n applied: [],\n summary: 'No attested migrations found',\n timings: { total: Date.now() - startTime },\n });\n }\n\n let graph: MigrationGraph;\n try {\n graph = reconstructGraph(packages);\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n\n // Create control client for all DB operations\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 try {\n await client.connect(dbConnection);\n\n const marker = await client.readMarker();\n\n // Distinguish \"no marker row\" (null) from \"marker row exists with the\n // empty sentinel\". The sentinel should never appear in a real marker row —\n // if it does, the marker was corrupted and replaying all migrations would\n // be dangerous (the DB likely already has tables).\n if (marker?.storageHash === EMPTY_CONTRACT_HASH) {\n return notOk(\n errorRuntime('Database marker contains the empty sentinel hash', {\n why: `The marker row exists but contains the empty sentinel value \"${EMPTY_CONTRACT_HASH}\". This should never happen — the marker should contain the hash of the last applied contract.`,\n fix: 'The marker is corrupted. Reset the database with `prisma-next db init`, or manually update the marker to the correct contract hash.',\n meta: { markerHash: EMPTY_CONTRACT_HASH },\n }),\n );\n }\n\n const markerHash = marker?.storageHash ?? EMPTY_CONTRACT_HASH;\n\n if (markerHash !== EMPTY_CONTRACT_HASH && !graph.nodes.has(markerHash)) {\n return notOk(\n errorRuntime('Database marker does not match any known migration', {\n why: `The database marker hash \"${markerHash}\" is not found in the migration history at ${migrationsRelative}`,\n fix: 'Ensure the migrations directory matches this database, or reset the database with `prisma-next db init`.',\n meta: { markerHash, knownNodes: [...graph.nodes] },\n }),\n );\n }\n\n if (!graph.nodes.has(destinationHash)) {\n return notOk(\n errorRuntime('Current contract has no planned migration path', {\n why: `Current contract hash \"${destinationHash}\" is not present in the migration history at ${migrationsRelative}`,\n fix: 'Run `prisma-next migration plan` to create a migration for the current contract, then re-run apply.',\n meta: { destinationHash, knownNodes: [...graph.nodes] },\n }),\n );\n }\n\n const pendingPath = findPath(graph, markerHash, destinationHash);\n if (!pendingPath) {\n return notOk(\n errorRuntime('No migration path from current state to target', {\n why: `Cannot find a path from marker hash \"${markerHash}\" to target \"${destinationHash}\"`,\n fix: 'Check the migration history for gaps or inconsistencies.',\n meta: { markerHash, destinationHash },\n }),\n );\n }\n\n if (pendingPath.length === 0) {\n return ok({\n ok: true,\n migrationsApplied: 0,\n migrationsTotal: 0,\n markerHash,\n applied: [],\n summary: 'Already up to date',\n timings: { total: Date.now() - startTime },\n });\n }\n\n // Resolve graph edges to full apply-ready edges\n const packageByDir = new Map(packages.map((pkg) => [pkg.dirName, pkg]));\n const pendingMigrations: MigrationApplyStep[] = [];\n for (const migration of pendingPath) {\n const pkg = packageByDir.get(migration.dirName);\n if (!pkg) {\n return notOk(\n errorRuntime(`Migration package not found: ${migration.dirName}`, {\n why: `The migration directory for path segment ${migration.from} → ${migration.to} was not found`,\n fix: 'Ensure all migration directories are present and intact.',\n }),\n );\n }\n pendingMigrations.push(packageToStep(pkg));\n }\n\n if (!flags.quiet && flags.json !== 'object') {\n for (const migration of pendingMigrations) {\n console.log(` Applying ${migration.dirName}...`);\n }\n }\n\n const applyResult = await client.migrationApply({\n originHash: markerHash,\n destinationHash,\n pendingMigrations,\n });\n\n if (!applyResult.ok) {\n return notOk(mapApplyFailure(applyResult.failure));\n }\n\n const { value } = applyResult;\n\n return ok({\n ok: true,\n migrationsApplied: value.migrationsApplied,\n migrationsTotal: pendingPath.length,\n markerHash: value.markerHash,\n applied: value.applied,\n summary: value.summary,\n timings: { total: Date.now() - startTime },\n });\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during migration apply: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createMigrationApplyCommand(): Command {\n const command = new Command('apply');\n setCommandDescriptions(\n command,\n 'Apply planned migrations to the database',\n 'Applies previously planned migrations (created by `migration plan`) to a live database.\\n' +\n 'Compares the database marker against the migration chain to determine which\\n' +\n 'migrations are pending, then executes them sequentially. Each migration runs\\n' +\n 'in its own transaction. Does not plan new migrations — run `migration plan` first.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const defaultFlags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags: defaultFlags });\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: MigrationApplyCommandOptions) => {\n const flags = parseGlobalFlags(options);\n const startTime = Date.now();\n\n const result = await executeMigrationApplyCommand(options, flags, startTime);\n\n const exitCode = handleResult(result, flags, (applyResult) => {\n if (flags.json === 'object') {\n console.log(JSON.stringify(applyResult, null, 2));\n } else if (!flags.quiet) {\n console.log(formatMigrationApplyCommandOutput(applyResult, flags));\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;AAkEA,SAAS,uBAAuB,OAAwC;AACtE,KAAI,oBAAoB,GAAG,MAAM,CAC/B,QAAO,aAAa,MAAM,SAAS;EACjC,KAAK,MAAM;EACX,K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,6BAA6B,SAAS,OAFzC,KAAK,KAAK,CAEgD,EAEtC,QAAQ,gBAAgB;AAC5D,OAAI,MAAM,SAAS,SACjB,SAAQ,IAAI,KAAK,UAAU,aAAa,MAAM,EAAE,CAAC;YACxC,CAAC,MAAM,MAChB,SAAQ,IAAI,kCAAkC,aAAa,MAAM,CAAC;IAEpE;AAEF,UAAQ,KAAK,SAAS;GACtB;AAEJ,QAAO"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
|
|
3
|
+
//#region src/commands/migration-plan.d.ts
|
|
4
|
+
interface MigrationPlanResult {
|
|
5
|
+
readonly ok: boolean;
|
|
6
|
+
readonly noOp: boolean;
|
|
7
|
+
readonly from: string;
|
|
8
|
+
readonly to: string;
|
|
9
|
+
readonly migrationId?: string;
|
|
10
|
+
readonly dir?: string;
|
|
11
|
+
readonly operations: readonly {
|
|
12
|
+
readonly id: string;
|
|
13
|
+
readonly label: string;
|
|
14
|
+
readonly operationClass: string;
|
|
15
|
+
}[];
|
|
16
|
+
readonly sql?: readonly string[];
|
|
17
|
+
readonly summary: string;
|
|
18
|
+
readonly timings: {
|
|
19
|
+
readonly total: number;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
declare function createMigrationPlanCommand(): Command;
|
|
23
|
+
//#endregion
|
|
24
|
+
export { MigrationPlanResult, createMigrationPlanCommand };
|
|
25
|
+
//# sourceMappingURL=migration-plan.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-plan.d.mts","names":[],"sources":["../../src/commands/migration-plan.ts"],"sourcesContent":[],"mappings":";;;UAqDiB,mBAAA;;EAAA,SAAA,IAAA,EAAA,OAAmB;EAsRpB,SAAA,IAAA,EAAA,MAAA;;;;;;;;;;;;;;;iBAAA,0BAAA,CAAA,GAA8B"}
|