Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"db:migrate": "npx prisma migrate dev",
"db:push": "npx prisma db push",
"db:seed": "npx prisma db seed",
"db:check-drift": "prisma migrate diff --from-migrations prisma/migrations --to-schema prisma/schema.prisma --exit-code",
"db:check-drift": "node scripts/check-prisma-drift.mjs",
"postinstall": "prisma generate",
"worker": "tsx --env-file=.env scripts/start-worker.ts",
"worker:render": "tsx scripts/start-worker.ts",
Expand Down
7 changes: 6 additions & 1 deletion prisma/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,10 +216,15 @@ Opens at `http://localhost:5555`.
If your local database schema gets out of sync or encounters drift:

- **Check for schema vs. migration drift**:

```bash
npm run db:check-drift
```
_Diffs migrations against `schema.prisma` using `prisma migrate diff --exit-code`. Exits with code 0 when in sync or code 2 when drift is detected.

_Diffs migrations against `schema.prisma` using `prisma migrate diff --exit-code`. The runner stops the process after 60 seconds and reports connection or shadow-database failures. It exits with code 0 when in sync, 2 for schema drift, or 124 on timeout._

`--from-migrations` needs a temporary shadow database. Prisma creates and deletes one automatically when the database role has permission, including on Neon setups that support this, so a separate Neon shadow URL is not normally required. CI's local PostgreSQL job creates a dedicated shadow database. Never configure the application database itself as the shadow database. If the check times out or exits with another error, verify database connectivity and permissions before treating it as schema drift.

- **Check migration status**:
```bash
npx prisma migrate status
Expand Down
72 changes: 72 additions & 0 deletions scripts/check-prisma-drift.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { spawnSync } from "node:child_process";
import { createRequire } from "node:module";
import path from "node:path";
import { fileURLToPath } from "node:url";

const require = createRequire(import.meta.url);
const prismaCli = require.resolve("prisma/build/index.js");
export const DRIFT_TIMEOUT_MS = 60_000;
export const DRIFT_ARGS = [
"migrate",
"diff",
"--from-migrations",
"prisma/migrations",
"--to-schema",
"prisma/schema.prisma",
"--exit-code",
];

/** @typedef {{ status: number | null, error?: Error & { code?: string }, stdout?: string | null, stderr?: string | null, signal?: string | null }} PrismaProcessResult */

/**
* @param {string[]} args
* @param {{ timeoutMs?: number, spawn?: (command: string, args: string[], options: { cwd: string, encoding: "utf8", timeout: number, maxBuffer: number }) => PrismaProcessResult }} options
* @returns {PrismaProcessResult}
*/
export function runPrismaDiff(
args = DRIFT_ARGS,
{ timeoutMs = DRIFT_TIMEOUT_MS, spawn = spawnSync } = {},
) {
return spawn(process.execPath, [prismaCli, ...args], {
cwd: process.cwd(),
encoding: "utf8",
timeout: timeoutMs,
maxBuffer: 2 * 1024 * 1024,
});
}

/** @param {PrismaProcessResult} result */
export function describePrismaDiffResult(result, timeoutMs = DRIFT_TIMEOUT_MS) {
if (result.error?.code === "ETIMEDOUT") {
return {
exitCode: 124,
message: `Prisma migrate diff timed out after ${timeoutMs / 1000}s. Check database connectivity and shadow database permissions. On Neon, a separate shadow URL is unnecessary when Prisma can create its temporary database; never point SHADOW_DATABASE_URL at the application database.`,
};
}
if (result.status === 0) return { exitCode: 0, message: "No schema drift detected." };
if (result.status === 2) {
return {
exitCode: 2,
message:
"Schema drift detected. Run 'npx prisma migrate dev --name <change>' and commit the new migration.",
};
}
const reason =
result.error?.message ||
result.stderr?.trim() ||
result.signal ||
"No Prisma diagnostics were returned.";
const safeReason = reason.replace(/(postgres(?:ql)?:\/\/)[^\s@]+@/gi, "$1[redacted]@");
return {
exitCode: 1,
message: `Prisma migrate diff failed (exit ${result.status ?? "unknown"}). Check database connectivity, shadow database permissions, and the schema. ${safeReason.slice(0, 2000)}`,
};
}

if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
const result = runPrismaDiff();
if (result.stdout) process.stdout.write(result.stdout);
const outcome = describePrismaDiffResult(result);
if (outcome.exitCode !== 0) console.error(outcome.message);
process.exitCode = outcome.exitCode;
}
133 changes: 67 additions & 66 deletions tests/prisma-drift-check.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { describe, it, expect } from "vitest";
import { describe, it, expect, vi } from "vitest";
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import {
DRIFT_ARGS,
describePrismaDiffResult,
runPrismaDiff,
} from "../scripts/check-prisma-drift.mjs";

describe("Prisma Schema Drift Check (#1691)", () => {
const rootDir = process.cwd();
Expand All @@ -18,10 +22,16 @@ describe("Prisma Schema Drift Check (#1691)", () => {

expect(pkg.scripts).toHaveProperty("db:check-drift");
const script = pkg.scripts["db:check-drift"];
expect(script).toContain("prisma migrate diff");
expect(script).toContain("--from-migrations prisma/migrations");
expect(script).toContain("--to-schema prisma/schema.prisma");
expect(script).toContain("--exit-code");
expect(script).toBe("node scripts/check-prisma-drift.mjs");
expect(DRIFT_ARGS).toEqual([
"migrate",
"diff",
"--from-migrations",
"prisma/migrations",
"--to-schema",
"prisma/schema.prisma",
"--exit-code",
]);
});
});

Expand Down Expand Up @@ -73,74 +83,65 @@ describe("Prisma Schema Drift Check (#1691)", () => {
describe("Prisma migrate diff exit code contract", () => {
it("exits with 0 when comparing schema to itself (no drift)", () => {
expect(fs.existsSync(schemaPath)).toBe(true);
const isWindows = process.platform === "win32";
const cmd = isWindows ? "cmd.exe" : "npx";
const args = isWindows
? [
"/c",
"npx",
"prisma",
"migrate",
"diff",
"--from-schema",
"prisma/schema.prisma",
"--to-schema",
"prisma/schema.prisma",
"--exit-code",
]
: [
"prisma",
"migrate",
"diff",
"--from-schema",
"prisma/schema.prisma",
"--to-schema",
"prisma/schema.prisma",
"--exit-code",
];

const res = spawnSync(cmd, args, {
cwd: rootDir,
encoding: "utf8",
});
const res = runPrismaDiff(
[
"migrate",
"diff",
"--from-schema",
"prisma/schema.prisma",
"--to-schema",
"prisma/schema.prisma",
"--exit-code",
],
{ timeoutMs: 20_000 },
);

expect(res.status).toBe(0);
expect(res.status, describePrismaDiffResult(res, 20_000).message).toBe(0);
expect(res.stdout).toContain("No difference detected");
}, 30000);

it("exits with 2 when diff detects unmigrated changes", () => {
expect(fs.existsSync(schemaPath)).toBe(true);
const isWindows = process.platform === "win32";
const cmd = isWindows ? "cmd.exe" : "npx";
const args = isWindows
? [
"/c",
"npx",
"prisma",
"migrate",
"diff",
"--from-empty",
"--to-schema",
"prisma/schema.prisma",
"--exit-code",
]
: [
"prisma",
"migrate",
"diff",
"--from-empty",
"--to-schema",
"prisma/schema.prisma",
"--exit-code",
];

const res = spawnSync(cmd, args, {
cwd: rootDir,
encoding: "utf8",
});
const res = runPrismaDiff(
["migrate", "diff", "--from-empty", "--to-schema", "prisma/schema.prisma", "--exit-code"],
{ timeoutMs: 20_000 },
);

expect(res.status).toBe(2);
expect(res.status, describePrismaDiffResult(res, 20_000).message).toBe(2);
expect(res.stdout).toContain("[+] Added");
}, 30000);

it("passes a process timeout and reports timeouts separately from schema drift", () => {
const timedOut = Object.assign(new Error("process timed out"), { code: "ETIMEDOUT" });
const spawn = vi.fn((command: string, args: string[], options: { timeout: number }) => {
expect(command).toBe(process.execPath);
expect(args).toHaveLength(1);
expect(options.timeout).toBe(1234);
return { status: null, error: timedOut, stdout: "", stderr: "" };
});
const result = runPrismaDiff([], { timeoutMs: 1234, spawn });

expect(spawn.mock.calls[0][2]).toMatchObject({ timeout: 1234, encoding: "utf8" });
expect(describePrismaDiffResult(result, 1234)).toMatchObject({
exitCode: 124,
message: expect.stringContaining("timed out"),
});
});

it("reports non-drift Prisma failures with their cause", () => {
const result = describePrismaDiffResult({ status: 1, stderr: "connection refused" });
expect(result.exitCode).toBe(1);
expect(result.message).toContain("connection refused");
expect(result.message).toContain("shadow database permissions");
});

it("redacts database credentials from Prisma diagnostics", () => {
const result = describePrismaDiffResult({
status: 1,
stderr: "connection failed: postgresql://alice:secret@localhost:5432/secureflow",
});
expect(result.message).toContain("postgresql://[redacted]@localhost");
expect(result.message).not.toContain("secret");
});
});
});