1
0
Fork 0

Compare commits

..

6 commits

Author SHA1 Message Date
15177b7765 v0.12.18 - fix admin document editing past the postgres 100-argument limit 2026-10-21 10:34:33 -04:00
77386eed3b docs: add v0.12.18 changelog entry 2026-10-21 10:31:18 -04:00
8174b32cd7 docs: document the postgres 100-argument lock limit and drizzle patch 2026-10-21 10:31:11 -04:00
e3926ab828 fix(db): chunk drizzle json_build_array under postgres argument cap
Postgres caps function arguments at 100. `payload_locked_documents_rels`
holds one foreign-key column per collection, and Drizzle hydrates the
locked document's polymorphic relationship with a single
`json_build_array(...)` over all of them. At 103 collections the query
throws 54023 and every admin edit view breaks while a lock row exists.

Patch drizzle-orm 0.45.2 to split the call into 100-argument groups
joined with `::jsonb || ::jsonb`, mirroring the unmerged upstream PR
drizzle-team/drizzle-orm#4495. Relations with 100 or fewer columns keep
the original code path unchanged.

Add tests/int/locked-documents-query.int.spec.ts, which creates a lock
row and reads it back at depth 1 (what getIsLocked and
handleFormStateLocking do). It fails on pristine drizzle with the exact
54023 error and passes with the patch.
2026-10-21 10:31:11 -04:00
6be14c9815 test(test-db): template database + schema-hash cache + clone primitives
Reworks the test-db module into explicit primitives: ensureTemplateDatabase
(dropped/recreated + built once per schema hash change, cached in
.cache/testdb-template.json), cloneTemplateInto, dropDatabaseIfPresent and
dropStaleWorkerDatabases. bootstrapTestDatabase() keeps its export but is
re-expressed as guarantee-template + fresh clone for the serial databases
(vitest pre-stage-2, Playwright), so repeated runs skip drizzle push
entirely. The legacy truncate+push flow survives verbatim as
bootstrapSerialDatabase for the TEST_DATABASE_URI bisect mode. Nothing may
connect to the template while clones run (loud invariant comment).
2026-10-21 10:03:33 -04:00
859f6d4310 test(int-suite): auto-accept drizzle push prompts in tests/push-schema.ts
payload's pushDevSchema() awaits prompts() whenever drizzle push reports
warnings (incl. DATA LOSS); under non-TTY stdin that await hangs forever
(2026-10-19 bootstrap hang). Inject confirmations through the single
hoisted prompts copy before getPayload boots; stdio stays inherit so all
other push output remains visible.
2026-10-21 10:03:33 -04:00
10 changed files with 466 additions and 28 deletions

View file

@ -222,6 +222,7 @@ never to dense data UI, tables, forms, dialogs, buttons, or shadcn-styled surfac
- `.npmrc` sets `legacy-peer-deps=true` for dependency resolution compatibility.
- `bun run db push` fails with `must be owner of table spatial_ref_sys` (a PostGIS table owned by the DB superuser) — drizzle-kit push does a full-schema diff and trips on it. Workaround: apply the needed `ALTER TABLE` directly (via node + `pg` reading `DATABASE_URI` from `.env`) or use Payload's migration runner (`bun run payload migrate`).
- **Payload 3 field-level access never rejects an update request**: when a field's `access` fn returns `false`, Payload silently deletes that field from the incoming data (`node_modules/payload/dist/fields/hooks/beforeValidate/promise.js`) and the save SUCCEEDS with the previous value. No 403, "Updated successfully." toast, other fields still save. It is enforcement without feedback; if you need a loud rejection or hidden dropdown options, that requires a collection `beforeChange` hook or a custom admin field component.
- **Admin edit views throw `54023 cannot pass more than 100 arguments` once the unit approaches 100 collections**: `payload_locked_documents_rels` gains one FK column per collection and Drizzle hydrates the lock's polymorphic relationship with a single `json_build_array(...)`, which Postgres caps at 100 arguments. `drizzle-orm@0.45.2` is bun-patched (`patches/drizzle-orm@0.45.2.patch`) to chunk that call into 100-argument groups joined with `::jsonb ||`; keep the patch (and its `patchedDependencies` entry) when upgrading drizzle, and `tests/int/locked-documents-query.int.spec.ts` fails loudly if it is missing.
- **Admin-panel-visible access bugs that contradict passing API tests**: check the actual role permission rows in the DB first, then the field-strip semantics above. The dev DB once had `system:admin-access` hand-granted to division roles (tests build clean roles, so tests pass while the panel misbehaves). The 30s `loadUserPermissions` cache is per-user-id and safe, but remember it exists when editing role data.
- PATCHing a document that is open in someone's admin edit tab returns **423 Locked** (Payload document locks). Test with a different document or wait for the lock to clear.
- For replaying admin-panel requests from the terminal: `/api/access` returns the caller's resolved permission map (collection `read` results are either a bare boolean like `true` or `{ permission, where }`; handle both shapes), and an officer-grade JWT can be crafted exactly like the impersonation route does (add a session `sid` to the target user, then `jwtSign` with `getFieldsToSign`).

View file

@ -1,5 +1,13 @@
# Changelog
# v0.12.18
### Fixes
- Various bug fixes and improvements.
---
# v0.12.17
The Superstructure has an interior now. Members walk a floorplan, clear rubble for scrap, force open sealed rooms, upgrade spaces, keep stations running, and collect job output even while offline.

View file

@ -103,6 +103,7 @@
"patchedDependencies": {
"@payloadcms/ui@3.88.0": "patches/@payloadcms%2Fui@3.88.0.patch",
"@ai-stack/payloadcms@3.2.30": "patches/@ai-stack%2Fpayloadcms@3.2.30.patch",
"drizzle-orm@0.45.2": "patches/drizzle-orm@0.45.2.patch",
},
"packages": {
"@acemir/cssom": ["@acemir/cssom@0.9.29", "", {}, "sha512-G90x0VW+9nW4dFajtjCoT+NM0scAfH9Mb08IcjgFHYbfiL/lU04dTF9JuVOi3/OH+DJCQdcIseSXkdCB9Ky6JA=="],

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.12.17",
"version": "0.12.18",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",
@ -141,6 +141,7 @@
"packageManager": "pnpm@9.15.4+sha512.b2dc20e2fc72b3e18848459b37359a32064663e5627a51e4c74b2c29dd8e8e0491483c3abb40789cfd578bf362fb6ba8261b05f0387d76792ed6e23ea3b1b6a0",
"patchedDependencies": {
"@ai-stack/payloadcms@3.2.30": "patches/@ai-stack%2Fpayloadcms@3.2.30.patch",
"@payloadcms/ui@3.88.0": "patches/@payloadcms%2Fui@3.88.0.patch"
"@payloadcms/ui@3.88.0": "patches/@payloadcms%2Fui@3.88.0.patch",
"drizzle-orm@0.45.2": "patches/drizzle-orm@0.45.2.patch"
}
}

View file

@ -0,0 +1,54 @@
diff --git a/pg-core/dialect.js b/pg-core/dialect.js
--- a/pg-core/dialect.js
+++ b/pg-core/dialect.js
@@ -1061,12 +1061,17 @@
let result;
where = and(joinOn, where);
if (nestedQueryRelation) {
- let field = sql`json_build_array(${sql.join(
- selection.map(
- ({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2
- ),
- sql`, `
- )})`;
+ const fieldChunks = [];
+ for (let i = 0; i < selection.length; i += 100) {
+ const chunk = selection.slice(i, i + 100);
+ fieldChunks.push(sql`json_build_array(${sql.join(
+ chunk.map(
+ ({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2
+ ),
+ sql`, `
+ )})`);
+ }
+ let field = fieldChunks.length === 1 ? fieldChunks[0] : fieldChunks.reduce((acc, chunk) => sql`${acc}::jsonb || ${chunk}::jsonb`);
if (is(nestedQueryRelation, Many)) {
field = sql`coalesce(json_agg(${field}${orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : void 0}), '[]'::json)`;
}
diff --git a/pg-core/dialect.cjs b/pg-core/dialect.cjs
--- a/pg-core/dialect.cjs
+++ b/pg-core/dialect.cjs
@@ -1063,12 +1063,17 @@
let result;
where = (0, import_sql.and)(joinOn, where);
if (nestedQueryRelation) {
- let field = import_sql2.sql`json_build_array(${import_sql2.sql.join(
- selection.map(
- ({ field: field2, tsKey, isJson }) => isJson ? import_sql2.sql`${import_sql2.sql.identifier(`${tableAlias}_${tsKey}`)}.${import_sql2.sql.identifier("data")}` : (0, import_entity.is)(field2, import_sql2.SQL.Aliased) ? field2.sql : field2
- ),
- import_sql2.sql`, `
- )})`;
+ const fieldChunks = [];
+ for (let i = 0; i < selection.length; i += 100) {
+ const chunk = selection.slice(i, i + 100);
+ fieldChunks.push(import_sql2.sql`json_build_array(${import_sql2.sql.join(
+ chunk.map(
+ ({ field: field2, tsKey, isJson }) => isJson ? import_sql2.sql`${import_sql2.sql.identifier(`${tableAlias}_${tsKey}`)}.${import_sql2.sql.identifier("data")}` : (0, import_entity.is)(field2, import_sql2.SQL.Aliased) ? field2.sql : field2
+ ),
+ import_sql2.sql`, `
+ )})`);
+ }
+ let field = fieldChunks.length === 1 ? fieldChunks[0] : fieldChunks.reduce((acc, chunk) => import_sql2.sql`${acc}::jsonb || ${chunk}::jsonb`);
if ((0, import_entity.is)(nestedQueryRelation, import_relations.Many)) {
field = import_sql2.sql`coalesce(json_agg(${field}${orderBy.length > 0 ? import_sql2.sql` order by ${import_sql2.sql.join(orderBy, import_sql2.sql`, `)}` : void 0}), '[]'::json)`;
}

View file

@ -2,10 +2,11 @@ import { bootstrapTestDatabase } from "../test-db";
import { resolveTestDatabaseUri } from "../test-db";
/**
* Playwright global setup: ensure the dedicated test database exists, is
* migrated, seeded and emptied before the dev server (started by webServer
* with DATABASE_URI pointed at it) serves the e2e suite. Then seed the shared
* e2e login ("dev" / "Test123"): every authed spec logs in with it, and the
* Playwright global setup: ensure the dedicated test database exists and is
* freshly built from the cached schema template (push runs only when the
* schema hash changed) before the dev server (started by webServer with
* DATABASE_URI pointed at it) serves the e2e suite. Then seed the shared e2e
* login ("dev" / "Test123"): every authed spec logs in with it, and the
* dashboard smoke expects the "Welcome back, J. Fraley." heading.
*/
export default async function globalSetup(): Promise<void> {

View file

@ -0,0 +1,81 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { beforeAll, describe, expect, it } from "vitest";
let payload: Payload;
/**
* Regression test for the Postgres `FUNC_MAX_ARGS` limit (error 54023,
* "cannot pass more than 100 arguments to a function").
*
* Document locking stores one foreign-key column per collection in
* `payload_locked_documents_rels`. Drizzle hydrates polymorphic relationships
* with a single `json_build_array(...)` that includes every one of those
* columns; once the unit has more than ~100 collections that call exceeds
* Postgres' hard limit and every admin edit view throws while a lock row
* exists. The local bun patch on drizzle-orm chunks the call into groups of
* 100 joined with `||`.
*
* This test creates a real lock row so the hydration query actually runs
* (with zero matching locks Payload skips the wide relational select), then
* reads it back with `depth: 1`, which is exactly what `getIsLocked` and
* `handleFormStateLocking` do.
*/
describe("payload-locked-documents relational query", () => {
beforeAll(async () => {
payload = await getPayload({ config: await config });
});
it("hydrates a lock document at depth 1 without exceeding the argument limit", async () => {
const roles = await payload.find({ collection: "roles", limit: 1, overrideAccess: true });
expect(roles.docs.length).toBeGreaterThan(0);
const roleId = roles.docs[0].id;
const username = `lock-query-${Date.now()}`;
const user = await payload.create({
collection: "users",
overrideAccess: true,
data: {
username,
discordUsername: username,
displayName: "Lock Query Tester",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
},
});
const lock = await payload.create({
collection: "payload-locked-documents",
overrideAccess: true,
data: {
document: { relationTo: "roles", value: roleId },
user: { relationTo: "users", value: user.id },
},
});
try {
const lockDocs = await payload.find({
collection: "payload-locked-documents",
depth: 1,
limit: 1,
overrideAccess: true,
where: {
and: [
{ "document.relationTo": { equals: "roles" } },
{ "document.value": { equals: roleId } },
],
},
});
expect(lockDocs.docs).toHaveLength(1);
expect(lockDocs.docs[0].id).toBe(lock.id);
} finally {
await payload.delete({
collection: "payload-locked-documents",
id: lock.id,
overrideAccess: true,
});
}
});
});

View file

@ -1,3 +1,5 @@
// @ts-expect-error - the `prompts` package ships no bundled types; only `.inject()` is used here.
import prompts from "prompts";
import { getPayload } from "payload";
import config from "@payload-config";
@ -6,7 +8,24 @@ import config from "@payload-config";
* DATABASE_URI pointing at the test database (tests/test-db.ts does this);
* initializing the Payload adapter with push: true makes drizzle create or
* diff the full schema. Exits immediately after initialization.
*
* Non-interactive by construction: when drizzle push reports warnings
* (including DATA LOSS ones), @payloadcms/drizzle's pushDevSchema asks via
* `prompts()`. Under a non-TTY stdin that await hangs forever, so we pre-load
* the SAME hoisted `prompts` module Payload imports and inject confirmations
* for it. The injected queue never empties in practice (one confirm per run,
* ten prepared); if it ever did, prompts would fall back to stdin, which is
* exactly why the queue is generous rather than exactly one.
*
* This relies on module identity: bun's loader resolves every `import
* prompts from "prompts"` to the single hoisted copy in node_modules (verified
* no nested copies under payload's own node_modules subtree). If a future
* dependency bump nests a second copy, the injection silently stops applying
* and pushes with warnings hang again - watch for that when touching deps.
*/
prompts.inject(Array(10).fill(true));
console.log("[push-schema] non-interactive mode: any drizzle push warnings/data-loss confirmations are auto-accepted");
const payload = await getPayload({ config });
void payload;
process.exit(0);

View file

@ -1,4 +1,7 @@
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";
@ -10,21 +13,52 @@ import "dotenv/config";
/**
* Dedicated test database machinery for the vitest and Playwright suites.
*
* Tests never touch the development database: they run against a sibling
* `<name>_test` database that is ensured, migrated, seeded and truncated per
* run. All operations are idempotent, so a crashed run's leftovers are wiped
* by the next run no matter what leaked.
* 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.
* - `TEST_DB_HARD_RESET=1` — drop and recreate the test database (fresh
* schema from migrations) instead of the default truncate flow.
* - `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).
*/
/** 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";
@ -59,6 +93,28 @@ function testDatabaseName(testUri: string): string {
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 (`ptf_app_test` -> `ptf_app_test_template`). */
export function templateDatabaseUri(): string {
const base = resolveTestDatabaseUri();
return withDatabaseName(base, `${testDatabaseName(base)}_template`);
}
/** Per-vitest-worker clone URI (`ptf_app_test` -> `ptf_app_test_w<ID>`). */
export function workerDatabaseUri(workerId: string | number): string {
const base = resolveTestDatabaseUri();
return withDatabaseName(base, `${testDatabaseName(base)}_w${workerId}`);
}
function quotedIdentifier(identifier: string): string {
return `"${identifier.replace(/"/g, '""')}"`;
}
@ -76,6 +132,14 @@ async function withAdminClient(testUri: string, fn: (client: Client) => Promise<
}
}
/** Terminate every backend connected to `dbName` so it can be dropped/cloned. */
async function terminateBackends(admin: Client, dbName: string): Promise<void> {
await admin.query(
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 AND pid <> pg_backend_pid()",
[dbName],
);
}
/**
* Create the test database when missing. With `hardReset`, terminate
* connections, drop it and recreate from scratch instead.
@ -85,10 +149,7 @@ export async function ensureTestDatabase(testUri: string, hardReset: boolean): P
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 admin.query(
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 AND pid <> pg_backend_pid()",
[dbName],
);
await terminateBackends(admin, dbName);
await admin.query(`DROP DATABASE ${quotedIdentifier(dbName)}`);
existing.rows.length = 0;
}
@ -98,10 +159,25 @@ export async function ensureTestDatabase(testUri: string, hardReset: boolean): P
});
}
/** 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 terminateBackends(admin, dbName);
await admin.query(`DROP DATABASE ${quotedIdentifier(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", {
@ -149,8 +225,9 @@ export async function ensureAnalyticsTables(testUri: string): Promise<void> {
/**
* Truncate every table in the public schema except migration journals and
* PostGIS internals. Idempotent by construction: the result is the same empty
* database no matter how many rows leaked from earlier runs.
* 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 });
@ -213,13 +290,190 @@ export function runSeedScripts(testUri: string): void {
}
}
// ---------------------------------------------------------------------------
// Template database + schema-hash cache
// ---------------------------------------------------------------------------
/**
* Full bootstrap, safe to call repeatedly: ensure the database (drop/recreate
* on hard reset), apply migrations, truncate leftover data, reseed baselines
* and repair sequences.
* 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.
*/
export async function bootstrapTestDatabase(): Promise<string> {
const testUri = resolveTestDatabaseUri();
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. 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 = testDatabaseName(templateDatabaseUri());
await withAdminClient(targetUri, async (admin) => {
await terminateBackends(admin, target);
await admin.query(`DROP DATABASE IF EXISTS ${quotedIdentifier(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 terminateBackends(admin, row.datname);
await admin.query(`DROP DATABASE ${quotedIdentifier(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);
@ -230,7 +484,23 @@ export async function bootstrapTestDatabase(): Promise<string> {
runSeedScripts(testUri);
await repairSequences(testUri);
const dbName = testDatabaseName(testUri);
console.log(`[test-db] ready: ${dbName}${hardReset ? " (hard reset)" : ""}`);
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;
}

View file

@ -3,7 +3,9 @@ import { bootstrapTestDatabase } from "./test-db";
/**
* Vitest global setup: point the suite at the dedicated test database and
* leave it in a known state (ensured, migrated, truncated, seeded, sequences
* repaired) before any test file loads.
* repaired) before any test file loads. Stage 2 rewires this entry point to
* the template + per-fork clone lifecycle; until then it bootstraps the one
* serial test database exactly as before.
*/
export default async function globalSetup(): Promise<void> {
await bootstrapTestDatabase();