1
0
Fork 0
polaris-task-force/tests/test-db.ts
Z8MB1E e828f50516 test(vitest): honor KEEP_TEST_DBS=0 as force-drop escape hatch
Plan wording kept clones on failure unless KEEP_TEST_DBS=0; teardown now
implements both ends explicitly (=1 always keep, =0 always drop, default
keep-on-failure). Verified with a deliberately failing spec both ways.
2026-10-21 13:04:15 -04:00

517 lines
20 KiB
TypeScript

import { execSync } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import { Client } from "pg";
import { applyAnalyticsDdl, ANALYTICS_TABLE_NAMES } from "../src/lib/analytics/schema";
// Global setup/teardown processes never load .env (only setupFiles do); load
// it here so every entry point sees the same variables. dotenv does not
// override variables that are already set.
import "dotenv/config";
/**
* Dedicated test database machinery for the vitest and Playwright suites.
*
* Tests never touch the development database. The topology:
*
* - `ptf_app_test_template` is built once per schema change by globalSetup:
* ensure db, drop analytics tables, drizzle push (auto-accepting warnings),
* analytics DDL, seedRoles + baseline seed, sequence repair. A hash of all
* schema-relevant inputs is cached in `.cache/testdb-template.json`; warm
* runs skip the push entirely.
* - Vitest workers each clone it into `ptf_app_test_w<ID>` at startup
* (`CREATE DATABASE ... TEMPLATE`, milliseconds because it holds only the
* empty baseline schema) and drop the clones at teardown unless the run
* failed. Two workers therefore never share tables.
* - `ptf_app_test` (the serial database, used by Playwright and by legacy
* serial vitest when no override is set) is recreated fresh from the
* template on every bootstrap instead of being truncated in place.
*
* >>> CLONING INVARIANT - DO NOT BREAK <<<
* `CREATE DATABASE ... TEMPLATE` fails while anything is connected to the
* template. Every clone happens after globalSetup finished building it and
* before any worker's tests import the Payload config, and no test code ever
* connects to the template database. If future tooling wants to "just peek"
* at `ptf_app_test_template` during a run, it must go through a snapshot
* clone instead - peeks re-break parallel worker startup.
*
* Override points:
* - `TEST_DATABASE_URI`: use this exact connection string instead of the
* derived one. This also forces LEGACY SERIAL behavior (single shared db,
* truncate per run, no templates or clones) for bisecting flakes.
* - `TEST_DB_HARD_RESET=1`: ignore the template cache and rebuild the
* template from scratch.
* - `KEEP_TEST_DBS=1`: teardown keeps worker clones even after green runs
* (postmortem hatch); `KEEP_TEST_DBS=0` forces dropping even after failures.
*/
/** Tables that must survive truncation: PostGIS internals and migration journals. */
const SKIP_TRUNCATE = new Set(["spatial_ref_sys", "__drizzle_migrations", "payload_migrations"]);
/** Template build cache; gitignored, disposable, rebuilt on hash mismatch. */
const TEMPLATE_CACHE_FILE = path.join(".cache", "testdb-template.json");
interface TemplateCache {
hash: string;
builtAt: string;
pgVersion: string;
dbName: string;
}
/** True when truncation should be skipped in favor of a full drop/recreate. */
export function hardResetRequested(): boolean {
return process.env.TEST_DB_HARD_RESET === "1";
}
/**
* Derive the test connection string: `TEST_DATABASE_URI` when set, otherwise
* the dev URI with its database name suffixed `_test`
* (`postgres://host/ptf_app_dev` -> `postgres://host/ptf_app_test`).
*/
export function resolveTestDatabaseUri(): string {
const override = process.env.TEST_DATABASE_URI;
if (override) return override;
const base = process.env.DATABASE_URI;
if (!base) {
throw new Error("DATABASE_URI (or TEST_DATABASE_URI) must be set to bootstrap the test database");
}
const url = new URL(base);
const segments = url.pathname.split("/").filter(Boolean);
const dbName = segments.pop();
if (!dbName) {
throw new Error("DATABASE_URI has no database name; cannot derive a test database");
}
url.pathname = [...segments, `${dbName}_test`].join("/");
return url.toString();
}
function testDatabaseName(testUri: string): string {
const name = new URL(testUri).pathname.split("/").filter(Boolean).pop();
if (!name) throw new Error("Test database URI has no database name");
return name;
}
/** Same connection string with its database name replaced. */
function withDatabaseName(testUri: string, dbName: string): string {
const url = new URL(testUri);
const segments = url.pathname.split("/").filter(Boolean);
if (segments.length === 0) throw new Error("Database URI has no database name");
segments[segments.length - 1] = dbName;
url.pathname = segments.join("/");
return url.toString();
}
/**
* Template database URI for a given serial test URI (`ptf_app_test` ->
* `ptf_app_test_template`). Defaults to resolving from the environment; pass
* an explicit URI when the caller's `process.env.DATABASE_URI` has already
* been repointed at the serial test db (worker setup files do exactly that,
* so re-resolving there would append `_test` twice).
*/
export function templateDatabaseUri(serialTestUri?: string): string {
const base = serialTestUri ?? resolveTestDatabaseUri();
return withDatabaseName(base, `${testDatabaseName(base)}_template`);
}
/**
* Per-fork-clone URI (`ptf_app_test` -> `ptf_app_test_w<PID>`). The id is the
* vitest fork process pid so one clone serves every file that scheduler
* assigns to the process (VITEST_WORKER_ID churns per task, not per process).
*/
export function workerDatabaseUri(workerId: string | number, serialTestUri?: string): string {
const base = serialTestUri ?? resolveTestDatabaseUri();
return withDatabaseName(base, `${testDatabaseName(base)}_w${workerId}`);
}
function quotedIdentifier(identifier: string): string {
return `"${identifier.replace(/"/g, '""')}"`;
}
/** Open a client to the server's maintenance database (`postgres`). */
async function withAdminClient(testUri: string, fn: (client: Client) => Promise<void>): Promise<void> {
const url = new URL(testUri);
url.pathname = "/postgres";
const client = new Client({ connectionString: url.toString() });
await client.connect();
try {
await fn(client);
} finally {
await client.end();
}
}
/**
* Drop a database even while client pools keep reconnecting to it. Postgres
* >= 13 (`WITH (FORCE)`) terminates conflicting sessions itself and waits for
* the lock, removing the terminate-then-drop race against vitest forks that
* are still shutting down when post-run cleanup runs.
*/
async function forceDropDatabase(admin: Client, dbName: string): Promise<void> {
await admin.query(`DROP DATABASE IF EXISTS ${quotedIdentifier(dbName)} WITH (FORCE)`);
}
/**
* Create the test database when missing. With `hardReset`, terminate
* connections, drop it and recreate from scratch instead.
*/
export async function ensureTestDatabase(testUri: string, hardReset: boolean): Promise<void> {
const dbName = testDatabaseName(testUri);
await withAdminClient(testUri, async (admin) => {
const existing = await admin.query("SELECT 1 FROM pg_database WHERE datname = $1", [dbName]);
if (hardReset && existing.rows.length > 0) {
await forceDropDatabase(admin, dbName);
existing.rows.length = 0;
}
if (existing.rows.length === 0) {
await admin.query(`CREATE DATABASE ${quotedIdentifier(dbName)}`);
}
});
}
/** Drop the database when present, terminating any lingering backends. */
export async function dropDatabaseIfPresent(uri: string): Promise<boolean> {
const dbName = testDatabaseName(uri);
let dropped = false;
await withAdminClient(uri, async (admin) => {
const existing = await admin.query("SELECT 1 FROM pg_database WHERE datname = $1", [dbName]);
if (existing.rows.length === 0) return;
await forceDropDatabase(admin, dbName);
dropped = true;
});
return dropped;
}
/**
* Create or diff the full schema via drizzle push. The migration chain
* assumes a schema that push originally created (its first migration alters
* existing tables), so a fresh database is built by pushing, not migrating.
* Warning/data-loss prompts are auto-accepted (see tests/push-schema.ts).
*/
export function pushSchema(testUri: string): void {
execSync("bun run tests/push-schema.ts", {
cwd: process.cwd(),
env: { ...process.env, DATABASE_URI: testUri, DB_PUSH: "1" },
stdio: "inherit",
});
}
/**
* Drop the plain-SQL analytics tables BEFORE drizzle push runs. Push treats
* tables outside the Payload schema as drift, and its introspector has a
* broken composite-primary-key query path (drizzle-kit 0.31.11), so it must
* never see these tables. They are recreated empty right after the push by
* `ensureAnalyticsTables`, so every run also starts from a clean slate here.
*/
export async function dropAnalyticsTables(testUri: string): Promise<void> {
const client = new Client({ connectionString: testUri });
await client.connect();
try {
for (const table of ANALYTICS_TABLE_NAMES) {
await client.query(`DROP TABLE IF EXISTS ${quotedIdentifier(table)} CASCADE`);
}
} finally {
await client.end();
}
}
/**
* Create the plain-SQL analytics tables. They live outside the Payload schema,
* so drizzle push never creates them; the shared DDL module (also executed by
* the add_analytics_tables migration) is applied here so tests exercise the
* same tables production has. Runs AFTER pushSchema because push drops tables
* it does not know about. Idempotent.
*/
export async function ensureAnalyticsTables(testUri: string): Promise<void> {
const client = new Client({ connectionString: testUri });
await client.connect();
try {
await applyAnalyticsDdl(client);
} finally {
await client.end();
}
}
/**
* Truncate every table in the public schema except migration journals and
* PostGIS internals. Only used by the legacy serial path (`TEST_DATABASE_URI`
* override) for bootstrap and teardown hygiene; template clones replace
* truncation everywhere else. Idempotent by construction.
*/
export async function truncateAllData(testUri: string): Promise<void> {
const client = new Client({ connectionString: testUri });
await client.connect();
try {
const tables = await client.query(
"SELECT tablename FROM pg_tables WHERE schemaname = 'public' ORDER BY tablename",
);
const names = tables.rows
.map((row: { tablename: string }) => row.tablename)
.filter((name) => !SKIP_TRUNCATE.has(name));
if (names.length === 0) return;
await client.query(`TRUNCATE TABLE ${names.map(quotedIdentifier).join(", ")} CASCADE`);
} finally {
await client.end();
}
}
/**
* Re-align every `<table>_id_seq` sequence with `MAX(id)` of its table.
* Migrations backfill baseline rows with explicit ids, which leaves fresh
* sequences behind the existing rows; without this repair the next create
* collides and fails with `ValidationError: field is invalid: id`.
*/
export async function repairSequences(testUri: string): Promise<void> {
const client = new Client({ connectionString: testUri });
await client.connect();
try {
const sequences = await client.query(
"SELECT sequencename FROM pg_sequences WHERE schemaname = 'public' AND sequencename LIKE '%\\_id\\_seq'",
);
for (const row of sequences.rows) {
const tableName = String(row.sequencename).replace(/_id_seq$/, "");
const tableExists = await client.query(
"SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = $1",
[tableName],
);
if (tableExists.rows.length === 0) continue;
await client.query(
`SELECT setval($1::regclass, COALESCE((SELECT MAX(id) FROM ${quotedIdentifier(tableName)}), 1), true)`,
[row.sequencename],
);
}
} finally {
await client.end();
}
}
/** Seed the shared baseline data tests rely on (RBAC roles, Game Rules). */
export function runSeedScripts(testUri: string): void {
// Self-executing scripts; run them as child processes so the bootstrap
// module graph stays free of @payload-config (which vitest globalSetup and
// Playwright's transpiler resolve differently).
for (const script of ["src/tools/seed/seedRoles.ts", "tests/seed-baseline.ts"]) {
execSync(`bun run ${script}`, {
cwd: process.cwd(),
env: { ...process.env, DATABASE_URI: testUri },
stdio: "inherit",
});
}
}
// ---------------------------------------------------------------------------
// Template database + schema-hash cache
// ---------------------------------------------------------------------------
/**
* Deliberately broad input set for the template cache key. False positives
* (rebuild with no real change) cost one cold build; misses produce loud but
* confusing "column does not exist" failures, recoverable via
* TEST_DB_HARD_RESET=1. When in doubt, add to the list.
*/
const SCHEMA_HASH_FILES = [
"src/payload.config.ts",
"src/payload-generated-schema.ts",
"drizzle.config.ts",
"package.json",
];
const SCHEMA_HASH_DIRS = ["src/collections", "src/globals", "src/utils", "src/migrations", "patches"];
const SCHEMA_HASH_PACKAGES = ["payload", "@payloadcms/drizzle", "drizzle-orm", "@payloadcms/plugin-mcp"];
function walkFiles(dir: string): string[] {
if (!existsSync(dir)) return [];
const out: string[] = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) out.push(...walkFiles(full));
else if (entry.isFile()) out.push(full);
}
return out;
}
async function pgServerVersion(): Promise<string> {
let version = "unknown";
await withAdminClient(resolveTestDatabaseUri(), async (admin) => {
const { rows } = await admin.query("SHOW server_version");
version = String(rows[0]?.server_version ?? "unknown");
});
return version;
}
/** sha256 over every schema-relevant input (see SCHEMA_HASH_* for the set). */
export async function schemaHash(): Promise<string> {
const pkg = JSON.parse(readFileSync(path.resolve("package.json"), "utf8")) as {
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
};
const cwd = process.cwd();
const files = [
...SCHEMA_HASH_FILES.map((file) => path.resolve(cwd, file)),
...SCHEMA_HASH_DIRS.flatMap((dir) => walkFiles(path.resolve(cwd, dir))),
]
.filter((file) => existsSync(file))
.map((file) => path.relative(cwd, file))
.sort();
const hash = createHash("sha256");
for (const rel of files) {
hash.update(rel);
hash.update("\0");
hash.update(readFileSync(path.resolve(cwd, rel)));
hash.update("\0");
}
for (const dep of SCHEMA_HASH_PACKAGES) {
hash.update(`${dep}@${pkg.dependencies?.[dep] ?? pkg.devDependencies?.[dep] ?? "missing"}\n`);
}
hash.update(`pg:${await pgServerVersion()}\n`);
return hash.digest("hex");
}
function readTemplateCache(): TemplateCache | null {
try {
return JSON.parse(readFileSync(path.resolve(TEMPLATE_CACHE_FILE), "utf8")) as TemplateCache;
} catch {
return null;
}
}
function writeTemplateCache(cache: TemplateCache): void {
const file = path.resolve(TEMPLATE_CACHE_FILE);
mkdirSync(path.dirname(file), { recursive: true });
writeFileSync(file, JSON.stringify(cache, null, 2));
}
/** Cheap liveness probe: does the template still exist and carry a schema? */
async function templateIsLive(templateUri: string): Promise<boolean> {
try {
const client = new Client({ connectionString: templateUri });
await client.connect();
try {
const { rows } = await client.query(
"SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'payload_migrations'",
);
return rows.length > 0;
} finally {
await client.end();
}
} catch {
return false;
}
}
/**
* Ensure `ptf_app_test_template` exists and matches the current schema hash.
* On cache miss (or `TEST_DB_HARD_RESET=1`, or a broken/missing template):
* drop/recreate it and run the full build (push, analytics DDL, seeds,
* sequence repair). On hit: return immediately after a liveness check.
* Never truncates - a template is a point-in-time image that clones inherit.
*/
export async function ensureTemplateDatabase(): Promise<string> {
const templateUri = templateDatabaseUri();
const templateName = testDatabaseName(templateUri);
const pgVersion = await pgServerVersion();
const hash = await schemaHash();
if (!hardResetRequested()) {
const cached = readTemplateCache();
if (cached && cached.hash === hash && cached.dbName === templateName && (await templateIsLive(templateUri))) {
console.log(`[test-db] template cache hit: ${templateName}`);
return templateUri;
}
}
const started = Date.now();
console.log(
`[test-db] building template ${templateName}${hardResetRequested() ? " (hard reset)" : ""}...`,
);
await ensureTestDatabase(templateUri, true);
await dropAnalyticsTables(templateUri);
pushSchema(templateUri);
await ensureAnalyticsTables(templateUri);
runSeedScripts(templateUri);
await repairSequences(templateUri);
writeTemplateCache({ hash, builtAt: new Date().toISOString(), pgVersion, dbName: templateName });
console.log(`[test-db] template ready: ${templateName} in ${((Date.now() - started) / 1000).toFixed(1)}s`);
return templateUri;
}
/**
* Replace the target database with an exact copy of the template. The
* template is addressed by name derived from the target (clone `_w<N>` suffix
* stripped, `_template` appended), so this never re-resolves the environment
* and works after DATABASE_URI mutations. Terminate leftover backends and
* drop first so a crashed run's state can never leak into a fresh clone.
* Subject to the CLONING INVARIANT at the top of this file: nothing may be
* connected to the template while this runs.
*/
export async function cloneTemplateInto(targetUri: string): Promise<void> {
const target = testDatabaseName(targetUri);
const template = `${target.replace(/_w[0-9]+$/, "")}_template`;
await withAdminClient(targetUri, async (admin) => {
await forceDropDatabase(admin, target);
await admin.query(`CREATE DATABASE ${quotedIdentifier(target)} TEMPLATE ${quotedIdentifier(template)}`);
});
}
/** Enumerate + drop `<base>_w<N>` clones left behind by crashed runs. */
export async function dropStaleWorkerDatabases(): Promise<number> {
const base = testDatabaseName(resolveTestDatabaseUri());
let dropped = 0;
await withAdminClient(resolveTestDatabaseUri(), async (admin) => {
// Postgres database names are [a-z0-9_]; none of those are regex
// specials, so the derived base can be interpolated directly.
const { rows } = await admin.query(
"SELECT datname FROM pg_database WHERE datname ~ $1",
[`^${base}_w[0-9]+$`],
);
for (const row of rows as { datname: string }[]) {
await forceDropDatabase(admin, row.datname);
dropped += 1;
}
});
if (dropped > 0) console.log(`[test-db] dropped ${dropped} stale worker database(s)`);
return dropped;
}
// ---------------------------------------------------------------------------
// Bootstrap entry points
// ---------------------------------------------------------------------------
/**
* Legacy serial bootstrap against one shared database, safe to call
* repeatedly: ensure (drop/recreate on hard reset), push, truncate leftover
* data, reseed baselines, repair sequences. Used when `TEST_DATABASE_URI`
* explicitly points the suite at a single db (bisect mode).
*/
export async function bootstrapSerialDatabase(testUri: string): Promise<string> {
const hardReset = hardResetRequested();
await ensureTestDatabase(testUri, hardReset);
await dropAnalyticsTables(testUri);
pushSchema(testUri);
await ensureAnalyticsTables(testUri);
await truncateAllData(testUri);
runSeedScripts(testUri);
await repairSequences(testUri);
console.log(`[test-db] ready: ${testDatabaseName(testUri)}${hardReset ? " (hard reset)" : ""}`);
return testUri;
}
/**
* Full bootstrap for the serial databases (Playwright; legacy vitest bisect
* mode). Without an explicit override it guarantees the template and hands
* back a FRESH clone of it - no truncate, no push in the steady state.
*/
export async function bootstrapTestDatabase(): Promise<string> {
const testUri = resolveTestDatabaseUri();
if (process.env.TEST_DATABASE_URI) {
return bootstrapSerialDatabase(testUri);
}
await ensureTemplateDatabase();
await cloneTemplateInto(testUri);
console.log(`[test-db] ready: ${testDatabaseName(testUri)} (cloned from template)`);
return testUri;
}