@prisma/cli 3.0.0-dev.58.1 → 3.0.0-dev.60.1

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.
@@ -1,3 +1,4 @@
1
+ import { usageError } from "../../shell/errors.js";
1
2
  import { attachCommandDescriptor } from "../../shell/command-meta.js";
2
3
  import { addCompactGlobalFlags, addGlobalFlags } from "../../shell/global-flags.js";
3
4
  import { configureRuntimeCommand } from "../../shell/runtime.js";
@@ -64,7 +65,7 @@ function createDeployCommand(runtime) {
64
65
  "hono",
65
66
  "tanstack-start",
66
67
  "bun"
67
- ])).addOption(new Option("--entry <path>", "Entrypoint path for Bun deploys")).addOption(new Option("--http-port <port>", "HTTP port override for the deployed app")).addOption(new Option("--env <name=value>", "Environment variable").argParser(collectRepeatableValues)).addOption(new Option("--prod", "Confirm intent to deploy to production"));
68
+ ])).addOption(new Option("--entry <path>", "Entrypoint path for Bun deploys")).addOption(new Option("--http-port <port>", "HTTP port override for the deployed app")).addOption(new Option("--env <name=value>", "Environment variable").argParser(collectRepeatableValues)).addOption(new Option("--db", "Create and wire an isolated database for the preview Branch")).addOption(new Option("--no-db", "Skip branch database setup")).addOption(new Option("--prod", "Confirm intent to deploy to production"));
68
69
  addGlobalFlags(command);
69
70
  command.action(async (options) => {
70
71
  const appName = options.app;
@@ -76,22 +77,31 @@ function createDeployCommand(runtime) {
76
77
  const projectRef = options.project;
77
78
  const createProjectName = options.createProject;
78
79
  const prod = options.prod;
79
- await runCommand(runtime, "app.deploy", options, (context) => runAppDeploy(context, appName, {
80
- projectRef,
81
- createProjectName,
82
- branchName,
83
- entrypoint: entry,
84
- framework,
85
- httpPort,
86
- envAssignments,
87
- prod: prod === true
88
- }), {
80
+ const db = options.db;
81
+ const hasDbConflict = hasFlag(runtime.argv, "--db") && hasFlag(runtime.argv, "--no-db");
82
+ await runCommand(runtime, "app.deploy", options, (context) => {
83
+ if (hasDbConflict) throw usageError("app deploy accepts either --db or --no-db", "--db requests branch database setup, while --no-db disables it.", "Pass exactly one database setup flag.", ["prisma-cli app deploy --db", "prisma-cli app deploy --no-db"], "app");
84
+ return runAppDeploy(context, appName, {
85
+ projectRef,
86
+ createProjectName,
87
+ branchName,
88
+ entrypoint: entry,
89
+ framework,
90
+ httpPort,
91
+ envAssignments,
92
+ prod: prod === true,
93
+ db
94
+ });
95
+ }, {
89
96
  renderHuman: (context, descriptor, result) => renderAppDeploy(context, descriptor, result),
90
97
  renderJson: (result) => serializeAppDeploy(result)
91
98
  });
92
99
  });
93
100
  return command;
94
101
  }
102
+ function hasFlag(argv, flag) {
103
+ return argv.some((arg) => arg === flag || arg.startsWith(`${flag}=`));
104
+ }
95
105
  function createShowCommand(runtime) {
96
106
  const command = attachCommandDescriptor(configureRuntimeCommand(new Command("show"), runtime), "app.show");
97
107
  command.addOption(new Option("--app <name>", "App name")).addOption(new Option("--project <id-or-name>", "Project id or name"));
@@ -19,6 +19,7 @@ import { promptForProjectSetupChoice } from "../lib/project/interactive-setup.js
19
19
  import { readLocalGitBranch } from "../lib/git/local-branch.js";
20
20
  import { PREVIEW_BUILD_TYPES, RESOLVED_PREVIEW_BUILD_TYPES, executePreviewBuild } from "../lib/app/preview-build.js";
21
21
  import { PREVIEW_DEFAULT_REGION } from "../lib/app/preview-interaction.js";
22
+ import { maybeSetupBranchDatabase } from "../lib/app/branch-database-deploy.js";
22
23
  import { createPreviewDeployProgress, createPreviewDeployProgressState, createPreviewPromoteProgress } from "../lib/app/preview-progress.js";
23
24
  import { PreviewDomainApiError, createPreviewAppProvider } from "../lib/app/preview-provider.js";
24
25
  import { enforceProductionDeployGate } from "../lib/app/production-deploy-gate.js";
@@ -170,6 +171,10 @@ async function runAppDeploy(context, appName, options) {
170
171
  assertSupportedEntrypoint(buildType, options?.entrypoint, "deploy");
171
172
  const entrypoint = await resolveDeployEntrypoint(context.runtime.cwd, framework, options?.entrypoint, context.runtime.signal);
172
173
  const portMapping = parseDeployPortMapping(String(runtime.port));
174
+ const branchDatabaseSetup = await maybeSetupBranchDatabase(context, provider, projectId, toBranchDatabaseDeployBranch(target.branch), {
175
+ db: options?.db,
176
+ inlineEnvVars: envVars
177
+ });
173
178
  const progressState = createPreviewDeployProgressState();
174
179
  const deployStartedAt = Date.now();
175
180
  const deployResult = await provider.deployApp({
@@ -200,8 +205,9 @@ async function runAppDeploy(context, appName, options) {
200
205
  result: {
201
206
  workspace: target.workspace,
202
207
  project: target.project,
203
- branch: target.branch,
208
+ branch: toResultBranch(target.branch),
204
209
  resolution: target.resolution,
210
+ branchDatabase: branchDatabaseSetup.result,
205
211
  app: {
206
212
  id: deployResult.app.id,
207
213
  name: deployResult.app.name
@@ -210,7 +216,7 @@ async function runAppDeploy(context, appName, options) {
210
216
  durationMs: deployDurationMs,
211
217
  localPin: localPinResult
212
218
  },
213
- warnings: [],
219
+ warnings: branchDatabaseSetup.warnings,
214
220
  nextSteps: ["prisma-cli app list-deploys", `prisma-cli app show-deploy ${deployResult.deployment.id}`]
215
221
  };
216
222
  }
@@ -757,7 +763,7 @@ async function resolveAppDomainTarget(context, options, commandName = "app domai
757
763
  resultTarget: {
758
764
  workspace: target.workspace,
759
765
  project: target.project,
760
- branch: target.branch,
766
+ branch: toResultBranch(target.branch),
761
767
  app: {
762
768
  id: selectedApp.id,
763
769
  name: selectedApp.name
@@ -1320,6 +1326,7 @@ async function resolveProjectContext(context, client, explicitProject, options)
1320
1326
  return {
1321
1327
  ...resolved,
1322
1328
  branch: {
1329
+ id: null,
1323
1330
  name: branch.name,
1324
1331
  kind: toBranchKind(branch.name)
1325
1332
  }
@@ -1446,6 +1453,7 @@ async function withRemoteDeployBranch(provider, target, branch, signal) {
1446
1453
  return {
1447
1454
  ...target,
1448
1455
  branch: {
1456
+ id: remoteBranch.id,
1449
1457
  name: remoteBranch.name,
1450
1458
  kind: remoteBranch.role
1451
1459
  }
@@ -1454,6 +1462,20 @@ async function withRemoteDeployBranch(provider, target, branch, signal) {
1454
1462
  function toBranchKind(name) {
1455
1463
  return name === "production" || name === "main" ? "production" : "preview";
1456
1464
  }
1465
+ function toResultBranch(branch) {
1466
+ return {
1467
+ name: branch.name,
1468
+ kind: branch.kind
1469
+ };
1470
+ }
1471
+ function toBranchDatabaseDeployBranch(branch) {
1472
+ if (!branch.id) throw new Error(`Deploy branch "${branch.name}" was not resolved remotely.`);
1473
+ return {
1474
+ id: branch.id,
1475
+ name: branch.name,
1476
+ kind: branch.kind
1477
+ };
1478
+ }
1457
1479
  function assertExclusiveDeployProjectInputs(options) {
1458
1480
  const provided = [
1459
1481
  options.projectRef ? "--project" : null,
@@ -0,0 +1,287 @@
1
+ import { CliError, usageError } from "../../shell/errors.js";
2
+ import { renderSummaryLine } from "../../shell/ui.js";
3
+ import { canPrompt } from "../../shell/runtime.js";
4
+ import { confirmPrompt } from "../../shell/prompt.js";
5
+ import { formatCommandArgument } from "../../shell/command-arguments.js";
6
+ import { hasBranchDatabaseSignal, inspectBranchDatabaseSignal, runBranchDatabaseSchemaSetup } from "./branch-database.js";
7
+ import path from "node:path";
8
+ //#region src/lib/app/branch-database-deploy.ts
9
+ async function maybeSetupBranchDatabase(context, provider, projectId, branch, options) {
10
+ if (options.db === false) return emptyBranchDatabaseSetupOutcome();
11
+ if (hasInlineDatabaseEnvVars(options.inlineEnvVars)) {
12
+ if (options.db === true) throw usageError("Branch database setup cannot be combined with inline database env vars", "The deploy command received --db and an inline DATABASE_URL or DIRECT_URL value.", "Remove the inline --env database value to let --db create a branch override, or remove --db to deploy with the provided value.", ["prisma-cli app deploy --db", "prisma-cli app deploy --env DATABASE_URL=postgresql://example"], "app");
13
+ return emptyBranchDatabaseSetupOutcome();
14
+ }
15
+ if (branch.kind === "production") {
16
+ if (options.db === true) throw usageError("Branch database setup is only available for preview branches", "Production database wiring is a durable environment decision and is not created implicitly by app deploy.", "Use project env commands to manage production DATABASE_URL, or deploy a preview branch with --db.", ["prisma-cli project env add DATABASE_URL=<value> --role production", "prisma-cli app deploy --branch feature/db --db"], "app");
17
+ return emptyBranchDatabaseSetupOutcome();
18
+ }
19
+ const localSignal = await inspectBranchDatabaseSignal(context.runtime.cwd, context.runtime.signal);
20
+ const envState = await inspectBranchDatabaseEnv(provider, projectId, branch.id, context.runtime.signal);
21
+ const branchEnvVars = [envState.branchDatabaseUrl, envState.branchDirectUrl].filter((variable) => Boolean(variable)).map((variable) => variable.key).sort();
22
+ if (envState.branchDatabaseUrl) {
23
+ const warning = options.db === true ? `Branch "${branch.name}" already has DATABASE_URL. Leaving branch database env vars unchanged.` : null;
24
+ if (warning) emitBranchDatabaseWarning(context, warning);
25
+ return {
26
+ result: options.db === true ? {
27
+ status: "skipped",
28
+ reason: "branch-env-exists",
29
+ envVars: branchEnvVars,
30
+ schema: null
31
+ } : void 0,
32
+ warnings: warning ? [warning] : []
33
+ };
34
+ }
35
+ const hasSignal = hasBranchDatabaseSignal(localSignal) || Boolean(envState.previewDatabaseUrl);
36
+ if (options.db !== true) {
37
+ if (!hasSignal) return emptyBranchDatabaseSetupOutcome();
38
+ if (!canPrompt(context) || context.flags.yes) {
39
+ const warning = "This app appears to use DATABASE_URL. Run prisma-cli app deploy --db to create an isolated database for this preview branch.";
40
+ emitBranchDatabaseWarning(context, warning);
41
+ return {
42
+ result: void 0,
43
+ warnings: [warning]
44
+ };
45
+ }
46
+ maybeRenderBranchDatabaseSignal(context, branch.name, localSignal, envState);
47
+ if (!await confirmPrompt({
48
+ input: context.runtime.stdin,
49
+ output: context.output.stderr,
50
+ message: `Create an isolated database for branch "${branch.name}"?`,
51
+ initialValue: false
52
+ })) return emptyBranchDatabaseSetupOutcome();
53
+ }
54
+ return setupBranchDatabase(context, provider, projectId, branch, localSignal, envState);
55
+ }
56
+ async function setupBranchDatabase(context, provider, projectId, branch, signal, envState) {
57
+ emitBranchDatabaseProgress(context, "pending", "Creating branch database");
58
+ const database = await provider.createBranchDatabase({
59
+ projectId,
60
+ branchId: branch.id,
61
+ branchName: branch.name,
62
+ signal: context.runtime.signal
63
+ }).catch((error) => {
64
+ throw branchDatabaseSetupFailedError("Failed to create branch database", error, branch.name);
65
+ });
66
+ emitBranchDatabaseProgress(context, "success", "Created branch database");
67
+ try {
68
+ let schemaSetup = null;
69
+ const warnings = [];
70
+ let skippedSchemaWarning = null;
71
+ if (signal.schema) {
72
+ emitBranchDatabaseProgress(context, "pending", `Applying database schema with ${formatSchemaSetupCommand(signal.schema.command)}`);
73
+ schemaSetup = await runBranchDatabaseSchemaSetup({
74
+ context,
75
+ schema: signal.schema,
76
+ databaseUrl: database.databaseUrl,
77
+ directUrl: database.directUrl
78
+ }).catch((error) => {
79
+ throw schemaSetupFailedError(error, signal.schema, branch.name);
80
+ });
81
+ emitBranchDatabaseProgress(context, "success", "Applied database schema");
82
+ } else skippedSchemaWarning = "No schema.prisma file was found. Branch database env vars were created, but schema setup was skipped.";
83
+ const envVars = await upsertBranchDatabaseEnvVars(context, provider, projectId, branch, database, envState);
84
+ emitBranchDatabaseProgress(context, "success", `Added branch env override${envVars.length === 1 ? "" : "s"} ${envVars.join(", ")}`);
85
+ if (skippedSchemaWarning) {
86
+ emitBranchDatabaseWarning(context, skippedSchemaWarning);
87
+ warnings.push(skippedSchemaWarning);
88
+ }
89
+ return {
90
+ result: {
91
+ status: "created",
92
+ database: {
93
+ id: database.id,
94
+ name: database.name
95
+ },
96
+ envVars,
97
+ schema: schemaSetup ? {
98
+ command: schemaSetup.command,
99
+ path: schemaSetup.schemaPath
100
+ } : null
101
+ },
102
+ warnings
103
+ };
104
+ } catch (error) {
105
+ throw await cleanupCreatedBranchDatabaseAfterFailure(context, provider, database, branch.name, error);
106
+ }
107
+ }
108
+ async function upsertBranchDatabaseEnvVars(context, provider, projectId, branch, database, envState) {
109
+ const written = [];
110
+ await upsertBranchDatabaseEnvVar(context, provider, {
111
+ projectId,
112
+ branchId: branch.id,
113
+ className: "preview",
114
+ key: "DATABASE_URL",
115
+ value: database.databaseUrl,
116
+ existing: envState.branchDatabaseUrl,
117
+ branchName: branch.name
118
+ });
119
+ written.push("DATABASE_URL");
120
+ if (database.directUrl) {
121
+ await upsertBranchDatabaseEnvVar(context, provider, {
122
+ projectId,
123
+ branchId: branch.id,
124
+ className: "preview",
125
+ key: "DIRECT_URL",
126
+ value: database.directUrl,
127
+ existing: envState.branchDirectUrl,
128
+ branchName: branch.name
129
+ });
130
+ written.push("DIRECT_URL");
131
+ } else if (envState.branchDirectUrl) await provider.deleteEnvironmentVariable({
132
+ envVarId: envState.branchDirectUrl.id,
133
+ signal: context.runtime.signal
134
+ }).catch((error) => {
135
+ throw branchDatabaseSetupFailedError("Failed to remove stale DIRECT_URL", error, branch.name);
136
+ });
137
+ return written;
138
+ }
139
+ async function upsertBranchDatabaseEnvVar(context, provider, options) {
140
+ if (options.existing) {
141
+ await provider.updateEnvironmentVariable({
142
+ envVarId: options.existing.id,
143
+ value: options.value,
144
+ signal: context.runtime.signal
145
+ }).catch((error) => {
146
+ throw branchDatabaseSetupFailedError(`Failed to update ${options.key}`, error, options.branchName);
147
+ });
148
+ return;
149
+ }
150
+ await provider.createEnvironmentVariable({
151
+ projectId: options.projectId,
152
+ branchId: options.branchId,
153
+ className: options.className,
154
+ key: options.key,
155
+ value: options.value,
156
+ signal: context.runtime.signal
157
+ }).catch((error) => {
158
+ throw branchDatabaseSetupFailedError(`Failed to write ${options.key}`, error, options.branchName);
159
+ });
160
+ }
161
+ async function inspectBranchDatabaseEnv(provider, projectId, branchId, signal) {
162
+ const [databaseUrlRows, directUrlRows] = await Promise.all([provider.listEnvironmentVariables({
163
+ projectId,
164
+ className: "preview",
165
+ key: "DATABASE_URL",
166
+ signal
167
+ }), provider.listEnvironmentVariables({
168
+ projectId,
169
+ className: "preview",
170
+ key: "DIRECT_URL",
171
+ signal
172
+ })]);
173
+ return {
174
+ branchDatabaseUrl: findEnvVar(databaseUrlRows, { branchId }),
175
+ branchDirectUrl: findEnvVar(directUrlRows, { branchId }),
176
+ previewDatabaseUrl: findEnvVar(databaseUrlRows, { branchId: null })
177
+ };
178
+ }
179
+ function findEnvVar(rows, options) {
180
+ return rows.find((row) => row.branchId === options.branchId) ?? null;
181
+ }
182
+ function hasInlineDatabaseEnvVars(envVars) {
183
+ return Boolean(envVars && ("DATABASE_URL" in envVars || "DIRECT_URL" in envVars));
184
+ }
185
+ function maybeRenderBranchDatabaseSignal(context, branchName, signal, envState) {
186
+ if (context.flags.json || context.flags.quiet) return;
187
+ const rows = [
188
+ signal.schema ? ` Schema ${path.relative(context.runtime.cwd, signal.schema.path) || "schema.prisma"}` : null,
189
+ signal.databaseUrlReferences.length > 0 ? ` Code ${signal.databaseUrlReferences.slice(0, 3).join(", ")}` : null,
190
+ envState.previewDatabaseUrl ? " Env preview DATABASE_URL is inherited by this branch" : null
191
+ ].filter((row) => Boolean(row));
192
+ context.output.stderr.write(`Database signal found for branch "${branchName}"\n${rows.join("\n")}\n\n`);
193
+ }
194
+ function emitBranchDatabaseProgress(context, status, message) {
195
+ if (context.flags.json || context.flags.quiet) return;
196
+ const line = status === "pending" ? `${context.ui.warning("◇")} ${message}...` : renderSummaryLine(context.ui, "success", message);
197
+ context.output.stderr.write(`${line}\n`);
198
+ }
199
+ function emitBranchDatabaseWarning(context, warning) {
200
+ if (context.flags.json || context.flags.quiet) return;
201
+ context.output.stderr.write(`${renderSummaryLine(context.ui, "warning", warning)}\n`);
202
+ }
203
+ function emptyBranchDatabaseSetupOutcome() {
204
+ return {
205
+ result: void 0,
206
+ warnings: []
207
+ };
208
+ }
209
+ function formatSchemaSetupCommand(command) {
210
+ return command === "migrate-deploy" ? "prisma migrate deploy" : "prisma db push";
211
+ }
212
+ function branchDatabaseSetupFailedError(summary, error, branchName) {
213
+ return new CliError({
214
+ code: "BRANCH_DATABASE_SETUP_FAILED",
215
+ domain: "app",
216
+ summary,
217
+ why: error instanceof Error ? error.message : String(error),
218
+ fix: "Retry the command, or create the branch database and env vars manually with project env commands.",
219
+ debug: formatDebugDetails(error),
220
+ meta: { branch: branchName },
221
+ exitCode: 1,
222
+ nextSteps: [`prisma-cli app deploy --branch ${formatCommandArgument(branchName)} --db`, `prisma-cli project env list --branch ${formatCommandArgument(branchName)}`]
223
+ });
224
+ }
225
+ async function cleanupCreatedBranchDatabaseAfterFailure(context, provider, database, branchName, error) {
226
+ const setupError = error instanceof CliError ? error : branchDatabaseSetupFailedError("Branch database setup failed", error, branchName);
227
+ emitBranchDatabaseProgress(context, "pending", "Removing branch database after setup failed");
228
+ try {
229
+ await provider.deleteBranchDatabase({
230
+ databaseId: database.id,
231
+ signal: context.runtime.signal
232
+ });
233
+ emitBranchDatabaseProgress(context, "success", "Removed branch database after setup failed");
234
+ } catch (cleanupError) {
235
+ return branchDatabaseCleanupFailedError(setupError, cleanupError, database, branchName);
236
+ }
237
+ return setupError;
238
+ }
239
+ function branchDatabaseCleanupFailedError(setupError, cleanupError, database, branchName) {
240
+ const cleanupWhy = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
241
+ const setupWhy = setupError.why ?? "Branch database setup failed.";
242
+ return new CliError({
243
+ code: setupError.code,
244
+ domain: setupError.domain,
245
+ summary: setupError.summary,
246
+ why: `${setupWhy} Prisma could not delete the created database "${database.name}" (${database.id}): ${cleanupWhy}`,
247
+ fix: "Delete the created branch database from Console or contact Prisma support, then rerun deploy with --db.",
248
+ debug: formatCombinedDebugDetails(setupError, cleanupError),
249
+ meta: {
250
+ ...setupError.meta,
251
+ branch: branchName,
252
+ databaseId: database.id,
253
+ databaseName: database.name,
254
+ cleanupFailed: true
255
+ },
256
+ exitCode: setupError.exitCode,
257
+ nextSteps: []
258
+ });
259
+ }
260
+ function schemaSetupFailedError(error, schema, branchName) {
261
+ return new CliError({
262
+ code: "SCHEMA_SETUP_FAILED",
263
+ domain: "app",
264
+ summary: "Database schema setup failed",
265
+ why: error instanceof Error ? error.message : String(error),
266
+ fix: "Fix the Prisma schema or migrations, then rerun deploy with --db.",
267
+ debug: formatDebugDetails(error),
268
+ meta: {
269
+ branch: branchName,
270
+ schemaPath: schema.path,
271
+ command: schema.command
272
+ },
273
+ exitCode: 1,
274
+ nextSteps: [schema.command === "migrate-deploy" ? "npx --no-install prisma migrate deploy" : "npx --no-install prisma db push --skip-generate", `prisma-cli app deploy --branch ${formatCommandArgument(branchName)} --db`]
275
+ });
276
+ }
277
+ function formatDebugDetails(error) {
278
+ if (error instanceof Error) return error.stack ?? error.message;
279
+ return typeof error === "string" ? error : null;
280
+ }
281
+ function formatCombinedDebugDetails(setupError, cleanupError) {
282
+ const setupDebug = setupError.debug ?? setupError.stack ?? setupError.message;
283
+ const cleanupDebug = formatDebugDetails(cleanupError);
284
+ return [setupDebug ? `Setup error:\n${setupDebug}` : null, cleanupDebug ? `Cleanup error:\n${cleanupDebug}` : null].filter((line) => Boolean(line)).join("\n\n") || null;
285
+ }
286
+ //#endregion
287
+ export { maybeSetupBranchDatabase };
@@ -0,0 +1,184 @@
1
+ import { access, readFile, readdir, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { spawn } from "node:child_process";
4
+ //#region src/lib/app/branch-database.ts
5
+ const SKIPPED_DIRECTORIES = new Set([
6
+ ".git",
7
+ ".next",
8
+ ".nuxt",
9
+ ".output",
10
+ ".prisma",
11
+ ".turbo",
12
+ ".vercel",
13
+ "build",
14
+ "coverage",
15
+ "dist",
16
+ "node_modules",
17
+ "out"
18
+ ]);
19
+ const DATABASE_URL_SCAN_EXTENSIONS = new Set([
20
+ ".cjs",
21
+ ".cts",
22
+ ".env",
23
+ ".js",
24
+ ".json",
25
+ ".jsx",
26
+ ".mjs",
27
+ ".mts",
28
+ ".prisma",
29
+ ".ts",
30
+ ".tsx"
31
+ ]);
32
+ const MAX_SCAN_DEPTH = 6;
33
+ const MAX_SCAN_FILES = 1e3;
34
+ const MAX_DATABASE_URL_REFERENCE_FILES = 10;
35
+ const MAX_TEXT_FILE_BYTES = 1024 * 1024;
36
+ async function inspectBranchDatabaseSignal(cwd, signal) {
37
+ const state = {
38
+ filesVisited: 0,
39
+ schemaCandidates: [],
40
+ databaseUrlReferences: []
41
+ };
42
+ await scanDirectory(cwd, cwd, 0, state, signal);
43
+ const schemaPath = selectSchemaPath(cwd, state.schemaCandidates);
44
+ const hasMigrations = schemaPath ? await hasMigrationsDirectory(path.dirname(schemaPath), signal) : false;
45
+ return {
46
+ schema: schemaPath ? {
47
+ path: schemaPath,
48
+ hasMigrations,
49
+ command: hasMigrations ? "migrate-deploy" : "db-push"
50
+ } : null,
51
+ databaseUrlReferences: state.databaseUrlReferences
52
+ };
53
+ }
54
+ function hasBranchDatabaseSignal(signal) {
55
+ return Boolean(signal.schema || signal.databaseUrlReferences.length > 0);
56
+ }
57
+ async function runBranchDatabaseSchemaSetup(options) {
58
+ const schemaPath = path.relative(options.context.runtime.cwd, options.schema.path) || "schema.prisma";
59
+ const args = buildPrismaSchemaCommandArgs(options.schema.command, schemaPath);
60
+ await runPrismaCommand({
61
+ context: options.context,
62
+ args,
63
+ env: {
64
+ DATABASE_URL: options.databaseUrl,
65
+ ...options.directUrl ? { DIRECT_URL: options.directUrl } : {}
66
+ }
67
+ });
68
+ return {
69
+ command: options.schema.command,
70
+ schemaPath
71
+ };
72
+ }
73
+ async function scanDirectory(cwd, directory, depth, state, signal) {
74
+ signal.throwIfAborted();
75
+ if (depth > MAX_SCAN_DEPTH || state.filesVisited >= MAX_SCAN_FILES) return;
76
+ let entries;
77
+ try {
78
+ entries = await readdir(directory, { withFileTypes: true });
79
+ } catch (error) {
80
+ if (error.code === "ENOENT") return;
81
+ throw error;
82
+ }
83
+ entries.sort((left, right) => left.name.localeCompare(right.name));
84
+ for (const entry of entries) {
85
+ signal.throwIfAborted();
86
+ if (state.filesVisited >= MAX_SCAN_FILES) return;
87
+ const entryPath = path.join(directory, entry.name);
88
+ if (entry.isDirectory()) {
89
+ if (!SKIPPED_DIRECTORIES.has(entry.name)) await scanDirectory(cwd, entryPath, depth + 1, state, signal);
90
+ continue;
91
+ }
92
+ if (!entry.isFile()) continue;
93
+ state.filesVisited += 1;
94
+ if (entry.name === "schema.prisma") state.schemaCandidates.push(entryPath);
95
+ if (state.databaseUrlReferences.length < MAX_DATABASE_URL_REFERENCE_FILES && shouldScanForDatabaseUrl(entry.name) && await fileContainsDatabaseUrl(entryPath, signal)) state.databaseUrlReferences.push(path.relative(cwd, entryPath) || entry.name);
96
+ }
97
+ }
98
+ function selectSchemaPath(cwd, candidates) {
99
+ return candidates.map((candidate) => ({
100
+ absolute: candidate,
101
+ relative: path.relative(cwd, candidate) || "schema.prisma"
102
+ })).sort((left, right) => {
103
+ if (left.relative === "schema.prisma") return -1;
104
+ if (right.relative === "schema.prisma") return 1;
105
+ return left.relative.length - right.relative.length || left.relative.localeCompare(right.relative);
106
+ })[0]?.absolute ?? null;
107
+ }
108
+ async function hasMigrationsDirectory(schemaDirectory, signal) {
109
+ signal.throwIfAborted();
110
+ const migrationsPath = path.join(schemaDirectory, "migrations");
111
+ try {
112
+ await access(migrationsPath);
113
+ return (await readdir(migrationsPath)).length > 0;
114
+ } catch (error) {
115
+ if (error.code === "ENOENT") return false;
116
+ throw error;
117
+ }
118
+ }
119
+ function shouldScanForDatabaseUrl(fileName) {
120
+ if (fileName === ".env" || fileName.startsWith(".env.")) return true;
121
+ return DATABASE_URL_SCAN_EXTENSIONS.has(path.extname(fileName));
122
+ }
123
+ async function fileContainsDatabaseUrl(filePath, signal) {
124
+ signal.throwIfAborted();
125
+ if ((await stat(filePath)).size > MAX_TEXT_FILE_BYTES) return false;
126
+ return (await readFile(filePath, {
127
+ encoding: "utf8",
128
+ signal
129
+ })).includes("DATABASE_URL");
130
+ }
131
+ function buildPrismaSchemaCommandArgs(command, schemaPath) {
132
+ if (command === "migrate-deploy") return [
133
+ "--no-install",
134
+ "prisma",
135
+ "migrate",
136
+ "deploy",
137
+ "--schema",
138
+ schemaPath
139
+ ];
140
+ return [
141
+ "--no-install",
142
+ "prisma",
143
+ "db",
144
+ "push",
145
+ "--skip-generate",
146
+ "--schema",
147
+ schemaPath
148
+ ];
149
+ }
150
+ async function runPrismaCommand(options) {
151
+ const shouldPipeOutput = !options.context.flags.json && !options.context.flags.quiet;
152
+ const child = spawn("npx", options.args, {
153
+ cwd: options.context.runtime.cwd,
154
+ env: {
155
+ ...options.context.runtime.env,
156
+ ...options.env
157
+ },
158
+ signal: options.context.runtime.signal,
159
+ stdio: shouldPipeOutput ? [
160
+ "ignore",
161
+ "pipe",
162
+ "pipe"
163
+ ] : [
164
+ "ignore",
165
+ "ignore",
166
+ "ignore"
167
+ ]
168
+ });
169
+ if (shouldPipeOutput) {
170
+ child.stdout?.pipe(options.context.output.stderr, { end: false });
171
+ child.stderr?.pipe(options.context.output.stderr, { end: false });
172
+ }
173
+ const exit = await new Promise((resolve, reject) => {
174
+ child.once("error", reject);
175
+ child.once("close", (code, signal) => resolve({
176
+ code,
177
+ signal
178
+ }));
179
+ });
180
+ if (exit.signal) throw new Error(`npx prisma was terminated by ${exit.signal}.`);
181
+ if (exit.code !== 0) throw new Error(`npx prisma exited with code ${exit.code ?? 1}.`);
182
+ }
183
+ //#endregion
184
+ export { hasBranchDatabaseSignal, inspectBranchDatabaseSignal, runBranchDatabaseSchemaSetup };
@@ -0,0 +1,102 @@
1
+ //#region src/lib/app/preview-branch-database.ts
2
+ async function createBranchDatabase(client, options) {
3
+ const result = await client.POST("/v1/databases", {
4
+ body: {
5
+ projectId: options.projectId,
6
+ branchId: options.branchId,
7
+ name: options.branchName,
8
+ source: { type: "empty" }
9
+ },
10
+ signal: options.signal
11
+ });
12
+ if (result.error || !result.data) throw apiCallError(`Failed to create database for branch "${options.branchName}"`, result.response, result.error);
13
+ return normalizeBranchDatabaseRecord(result.data.data);
14
+ }
15
+ async function listEnvironmentVariables(client, options) {
16
+ const variables = [];
17
+ let cursor;
18
+ while (true) {
19
+ const result = await client.GET("/v1/environment-variables", {
20
+ params: { query: {
21
+ projectId: options.projectId,
22
+ class: options.className,
23
+ key: options.key,
24
+ branchId: options.branchId,
25
+ cursor
26
+ } },
27
+ signal: options.signal
28
+ });
29
+ if (result.error || !result.data) throw apiCallError("Failed to list environment variables", result.response, result.error);
30
+ variables.push(...result.data.data);
31
+ if (!result.data.pagination.hasMore || !result.data.pagination.nextCursor) break;
32
+ cursor = result.data.pagination.nextCursor;
33
+ }
34
+ return variables.map((variable) => normalizeEnvironmentVariable(variable));
35
+ }
36
+ async function createEnvironmentVariable(client, options) {
37
+ const result = await client.POST("/v1/environment-variables", {
38
+ body: {
39
+ projectId: options.projectId,
40
+ class: options.className,
41
+ key: options.key,
42
+ value: options.value,
43
+ ...options.branchId ? { branchId: options.branchId } : {}
44
+ },
45
+ signal: options.signal
46
+ });
47
+ if (result.error || !result.data) throw apiCallError(`Failed to add ${options.key}`, result.response, result.error);
48
+ return normalizeEnvironmentVariable(result.data.data);
49
+ }
50
+ async function deleteBranchDatabase(client, options) {
51
+ const result = await client.DELETE("/v1/databases/{databaseId}", {
52
+ params: { path: { databaseId: options.databaseId } },
53
+ signal: options.signal
54
+ });
55
+ if (result.error) throw apiCallError("Failed to delete branch database", result.response, result.error);
56
+ }
57
+ async function updateEnvironmentVariable(client, options) {
58
+ const result = await client.PATCH("/v1/environment-variables/{envVarId}", {
59
+ params: { path: { envVarId: options.envVarId } },
60
+ body: { value: options.value },
61
+ signal: options.signal
62
+ });
63
+ if (result.error || !result.data) throw apiCallError("Failed to update environment variable", result.response, result.error);
64
+ return normalizeEnvironmentVariable(result.data.data);
65
+ }
66
+ async function deleteEnvironmentVariable(client, options) {
67
+ const result = await client.DELETE("/v1/environment-variables/{envVarId}", {
68
+ params: { path: { envVarId: options.envVarId } },
69
+ signal: options.signal
70
+ });
71
+ if (result.error) throw apiCallError("Failed to delete environment variable", result.response, result.error);
72
+ }
73
+ function normalizeEnvironmentVariable(variable) {
74
+ return {
75
+ id: variable.id,
76
+ key: variable.key,
77
+ branchId: variable.branchId,
78
+ className: variable.class,
79
+ isManagedBySystem: variable.isManagedBySystem
80
+ };
81
+ }
82
+ function normalizeBranchDatabaseRecord(database) {
83
+ const connection = database.connections?.[0];
84
+ const databaseUrl = connection?.endpoints?.pooled?.connectionString;
85
+ const directUrl = connection?.endpoints?.direct?.connectionString ?? null;
86
+ if (!databaseUrl) throw new Error("Created database did not return a pooled connection string.");
87
+ return {
88
+ id: database.id,
89
+ name: database.name,
90
+ branchId: database.branchId,
91
+ databaseUrl,
92
+ directUrl
93
+ };
94
+ }
95
+ function apiCallError(summary, response, error) {
96
+ if (response.status === 404) return /* @__PURE__ */ new Error("Resource Not Found");
97
+ const message = error.error?.message ?? `Management API returned HTTP ${response.status}.`;
98
+ const hint = error.error?.hint ? ` ${error.error.hint}` : "";
99
+ return /* @__PURE__ */ new Error(`${summary}: ${message}${hint}`);
100
+ }
101
+ //#endregion
102
+ export { createBranchDatabase, createEnvironmentVariable, deleteBranchDatabase, deleteEnvironmentVariable, listEnvironmentVariables, updateEnvironmentVariable };
@@ -1,5 +1,6 @@
1
1
  import { envVarNames } from "./env-vars.js";
2
2
  import { PreviewBuildStrategy } from "./preview-build.js";
3
+ import { createBranchDatabase, createEnvironmentVariable, deleteBranchDatabase, deleteEnvironmentVariable, listEnvironmentVariables, updateEnvironmentVariable } from "./preview-branch-database.js";
3
4
  import path from "node:path";
4
5
  import { ApiError, CancelledError, ComputeClient, streamLogs } from "@prisma/compute-sdk";
5
6
  //#region src/lib/app/preview-provider.ts
@@ -48,6 +49,24 @@ function createPreviewAppProvider(client, options) {
48
49
  role: branch.role
49
50
  };
50
51
  },
52
+ async createBranchDatabase(options) {
53
+ return createBranchDatabase(client, options);
54
+ },
55
+ async deleteBranchDatabase(options) {
56
+ return deleteBranchDatabase(client, options);
57
+ },
58
+ async listEnvironmentVariables(options) {
59
+ return listEnvironmentVariables(client, options);
60
+ },
61
+ async createEnvironmentVariable(options) {
62
+ return createEnvironmentVariable(client, options);
63
+ },
64
+ async updateEnvironmentVariable(options) {
65
+ return updateEnvironmentVariable(client, options);
66
+ },
67
+ async deleteEnvironmentVariable(options) {
68
+ return deleteEnvironmentVariable(client, options);
69
+ },
51
70
  async removeApp(appId, options) {
52
71
  const appResult = await sdk.showService({
53
72
  serviceId: appId,
@@ -30,6 +30,7 @@ function renderAppDeploy(context, descriptor, result) {
30
30
  return [
31
31
  `Live in ${formatDuration(result.durationMs)}`,
32
32
  ...result.deployment.url ? [context.ui.link(result.deployment.url)] : [],
33
+ ...renderBranchDatabaseDeploySummary(context, result),
33
34
  "",
34
35
  ...renderDeployOutputRows(context.ui, [{
35
36
  label: "Logs",
@@ -41,6 +42,23 @@ function serializeAppDeploy(result) {
41
42
  const { localPin: _localPin, ...serialized } = result;
42
43
  return serialized;
43
44
  }
45
+ function renderBranchDatabaseDeploySummary(context, result) {
46
+ if (!result.branchDatabase || result.branchDatabase.status !== "created") return [];
47
+ return ["", ...renderDeployOutputRows(context.ui, [
48
+ {
49
+ label: "Database",
50
+ value: result.branchDatabase.database?.name ?? "created"
51
+ },
52
+ {
53
+ label: "Env",
54
+ value: result.branchDatabase.envVars.join(", ")
55
+ },
56
+ ...result.branchDatabase.schema ? [{
57
+ label: "Schema",
58
+ value: result.branchDatabase.schema.command === "migrate-deploy" ? "prisma migrate deploy" : "prisma db push"
59
+ }] : []
60
+ ])];
61
+ }
44
62
  function formatDuration(durationMs) {
45
63
  if (durationMs < 1e3) return `${durationMs}ms`;
46
64
  return `${(durationMs / 1e3).toFixed(1)}s`;
@@ -194,6 +194,8 @@ const DESCRIPTORS = [
194
194
  "prisma-cli app deploy --project proj_123",
195
195
  "prisma-cli app deploy --create-project my-app --yes",
196
196
  "prisma-cli app deploy --app my-app --env DATABASE_URL=postgresql://example",
197
+ "prisma-cli app deploy --db",
198
+ "prisma-cli app deploy --db --yes",
197
199
  "prisma-cli app deploy --app my-app --framework nextjs --http-port 3000",
198
200
  "prisma-cli app deploy --branch feat-login --framework hono",
199
201
  "prisma-cli app deploy --prod --yes",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/cli",
3
- "version": "3.0.0-dev.58.1",
3
+ "version": "3.0.0-dev.60.1",
4
4
  "description": "Command-line interface for the Prisma Developer Platform.",
5
5
  "type": "module",
6
6
  "bin": {