Compare commits
No commits in common. "15177b776595df36ab2a203663b1bc705c5557b3" and "c64d56b8309d3a330da21f1dddf86cb8567bf186" have entirely different histories.
15177b7765
...
c64d56b830
10 changed files with 28 additions and 466 deletions
|
|
@ -222,7 +222,6 @@ never to dense data UI, tables, forms, dialogs, buttons, or shadcn-styled surfac
|
||||||
- `.npmrc` sets `legacy-peer-deps=true` for dependency resolution compatibility.
|
- `.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`).
|
- `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.
|
- **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.
|
- **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.
|
- 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`).
|
- 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`).
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,5 @@
|
||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
# v0.12.18
|
|
||||||
|
|
||||||
### Fixes
|
|
||||||
|
|
||||||
- Various bug fixes and improvements.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# v0.12.17
|
# 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.
|
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.
|
||||||
|
|
|
||||||
1
bun.lock
1
bun.lock
|
|
@ -103,7 +103,6 @@
|
||||||
"patchedDependencies": {
|
"patchedDependencies": {
|
||||||
"@payloadcms/ui@3.88.0": "patches/@payloadcms%2Fui@3.88.0.patch",
|
"@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",
|
"@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": {
|
"packages": {
|
||||||
"@acemir/cssom": ["@acemir/cssom@0.9.29", "", {}, "sha512-G90x0VW+9nW4dFajtjCoT+NM0scAfH9Mb08IcjgFHYbfiL/lU04dTF9JuVOi3/OH+DJCQdcIseSXkdCB9Ky6JA=="],
|
"@acemir/cssom": ["@acemir/cssom@0.9.29", "", {}, "sha512-G90x0VW+9nW4dFajtjCoT+NM0scAfH9Mb08IcjgFHYbfiL/lU04dTF9JuVOi3/OH+DJCQdcIseSXkdCB9Ky6JA=="],
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "polaris-task-force",
|
"name": "polaris-task-force",
|
||||||
"version": "0.12.18",
|
"version": "0.12.17",
|
||||||
"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.",
|
"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",
|
"license": "MIT",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|
@ -141,7 +141,6 @@
|
||||||
"packageManager": "pnpm@9.15.4+sha512.b2dc20e2fc72b3e18848459b37359a32064663e5627a51e4c74b2c29dd8e8e0491483c3abb40789cfd578bf362fb6ba8261b05f0387d76792ed6e23ea3b1b6a0",
|
"packageManager": "pnpm@9.15.4+sha512.b2dc20e2fc72b3e18848459b37359a32064663e5627a51e4c74b2c29dd8e8e0491483c3abb40789cfd578bf362fb6ba8261b05f0387d76792ed6e23ea3b1b6a0",
|
||||||
"patchedDependencies": {
|
"patchedDependencies": {
|
||||||
"@ai-stack/payloadcms@3.2.30": "patches/@ai-stack%2Fpayloadcms@3.2.30.patch",
|
"@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"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,54 +0,0 @@
|
||||||
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)`;
|
|
||||||
}
|
|
||||||
|
|
@ -2,11 +2,10 @@ import { bootstrapTestDatabase } from "../test-db";
|
||||||
import { resolveTestDatabaseUri } from "../test-db";
|
import { resolveTestDatabaseUri } from "../test-db";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Playwright global setup: ensure the dedicated test database exists and is
|
* Playwright global setup: ensure the dedicated test database exists, is
|
||||||
* freshly built from the cached schema template (push runs only when the
|
* migrated, seeded and emptied before the dev server (started by webServer
|
||||||
* schema hash changed) before the dev server (started by webServer with
|
* with DATABASE_URI pointed at it) serves the e2e suite. Then seed the shared
|
||||||
* DATABASE_URI pointed at it) serves the e2e suite. Then seed the shared e2e
|
* e2e login ("dev" / "Test123"): every authed spec logs in with it, and the
|
||||||
* login ("dev" / "Test123"): every authed spec logs in with it, and the
|
|
||||||
* dashboard smoke expects the "Welcome back, J. Fraley." heading.
|
* dashboard smoke expects the "Welcome back, J. Fraley." heading.
|
||||||
*/
|
*/
|
||||||
export default async function globalSetup(): Promise<void> {
|
export default async function globalSetup(): Promise<void> {
|
||||||
|
|
|
||||||
|
|
@ -1,81 +0,0 @@
|
||||||
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,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,5 +1,3 @@
|
||||||
// @ts-expect-error - the `prompts` package ships no bundled types; only `.inject()` is used here.
|
|
||||||
import prompts from "prompts";
|
|
||||||
import { getPayload } from "payload";
|
import { getPayload } from "payload";
|
||||||
import config from "@payload-config";
|
import config from "@payload-config";
|
||||||
|
|
||||||
|
|
@ -8,24 +6,7 @@ import config from "@payload-config";
|
||||||
* DATABASE_URI pointing at the test database (tests/test-db.ts does this);
|
* DATABASE_URI pointing at the test database (tests/test-db.ts does this);
|
||||||
* initializing the Payload adapter with push: true makes drizzle create or
|
* initializing the Payload adapter with push: true makes drizzle create or
|
||||||
* diff the full schema. Exits immediately after initialization.
|
* 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 });
|
const payload = await getPayload({ config });
|
||||||
void payload;
|
void payload;
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
|
|
|
||||||
312
tests/test-db.ts
312
tests/test-db.ts
|
|
@ -1,7 +1,4 @@
|
||||||
import { execSync } from "node:child_process";
|
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 { Client } from "pg";
|
||||||
import { applyAnalyticsDdl, ANALYTICS_TABLE_NAMES } from "../src/lib/analytics/schema";
|
import { applyAnalyticsDdl, ANALYTICS_TABLE_NAMES } from "../src/lib/analytics/schema";
|
||||||
|
|
||||||
|
|
@ -13,52 +10,21 @@ import "dotenv/config";
|
||||||
/**
|
/**
|
||||||
* Dedicated test database machinery for the vitest and Playwright suites.
|
* Dedicated test database machinery for the vitest and Playwright suites.
|
||||||
*
|
*
|
||||||
* Tests never touch the development database. The topology:
|
* Tests never touch the development database: they run against a sibling
|
||||||
*
|
* `<name>_test` database that is ensured, migrated, seeded and truncated per
|
||||||
* - `ptf_app_test_template` is built once per schema change by globalSetup:
|
* run. All operations are idempotent, so a crashed run's leftovers are wiped
|
||||||
* ensure db, drop analytics tables, drizzle push (auto-accepting warnings),
|
* by the next run no matter what leaked.
|
||||||
* 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:
|
* Override points:
|
||||||
* - `TEST_DATABASE_URI`: use this exact connection string instead of the
|
* - `TEST_DATABASE_URI` — use this exact connection string instead of the
|
||||||
* derived one. This also forces LEGACY SERIAL behavior (single shared db,
|
* derived one.
|
||||||
* truncate per run, no templates or clones) for bisecting flakes.
|
* - `TEST_DB_HARD_RESET=1` — drop and recreate the test database (fresh
|
||||||
* - `TEST_DB_HARD_RESET=1`: ignore the template cache and rebuild the
|
* schema from migrations) instead of the default truncate flow.
|
||||||
* 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. */
|
/** Tables that must survive truncation: PostGIS internals and migration journals. */
|
||||||
const SKIP_TRUNCATE = new Set(["spatial_ref_sys", "__drizzle_migrations", "payload_migrations"]);
|
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. */
|
/** True when truncation should be skipped in favor of a full drop/recreate. */
|
||||||
export function hardResetRequested(): boolean {
|
export function hardResetRequested(): boolean {
|
||||||
return process.env.TEST_DB_HARD_RESET === "1";
|
return process.env.TEST_DB_HARD_RESET === "1";
|
||||||
|
|
@ -93,28 +59,6 @@ function testDatabaseName(testUri: string): string {
|
||||||
return 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 (`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 {
|
function quotedIdentifier(identifier: string): string {
|
||||||
return `"${identifier.replace(/"/g, '""')}"`;
|
return `"${identifier.replace(/"/g, '""')}"`;
|
||||||
}
|
}
|
||||||
|
|
@ -132,14 +76,6 @@ 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
|
* Create the test database when missing. With `hardReset`, terminate
|
||||||
* connections, drop it and recreate from scratch instead.
|
* connections, drop it and recreate from scratch instead.
|
||||||
|
|
@ -149,7 +85,10 @@ export async function ensureTestDatabase(testUri: string, hardReset: boolean): P
|
||||||
await withAdminClient(testUri, async (admin) => {
|
await withAdminClient(testUri, async (admin) => {
|
||||||
const existing = await admin.query("SELECT 1 FROM pg_database WHERE datname = $1", [dbName]);
|
const existing = await admin.query("SELECT 1 FROM pg_database WHERE datname = $1", [dbName]);
|
||||||
if (hardReset && existing.rows.length > 0) {
|
if (hardReset && existing.rows.length > 0) {
|
||||||
await terminateBackends(admin, dbName);
|
await admin.query(
|
||||||
|
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 AND pid <> pg_backend_pid()",
|
||||||
|
[dbName],
|
||||||
|
);
|
||||||
await admin.query(`DROP DATABASE ${quotedIdentifier(dbName)}`);
|
await admin.query(`DROP DATABASE ${quotedIdentifier(dbName)}`);
|
||||||
existing.rows.length = 0;
|
existing.rows.length = 0;
|
||||||
}
|
}
|
||||||
|
|
@ -159,25 +98,10 @@ 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
|
* Create or diff the full schema via drizzle push. The migration chain
|
||||||
* assumes a schema that push originally created (its first migration alters
|
* assumes a schema that push originally created (its first migration alters
|
||||||
* existing tables), so a fresh database is built by pushing, not migrating.
|
* 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 {
|
export function pushSchema(testUri: string): void {
|
||||||
execSync("bun run tests/push-schema.ts", {
|
execSync("bun run tests/push-schema.ts", {
|
||||||
|
|
@ -225,9 +149,8 @@ export async function ensureAnalyticsTables(testUri: string): Promise<void> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Truncate every table in the public schema except migration journals and
|
* Truncate every table in the public schema except migration journals and
|
||||||
* PostGIS internals. Only used by the legacy serial path (`TEST_DATABASE_URI`
|
* PostGIS internals. Idempotent by construction: the result is the same empty
|
||||||
* override) for bootstrap and teardown hygiene; template clones replace
|
* database no matter how many rows leaked from earlier runs.
|
||||||
* truncation everywhere else. Idempotent by construction.
|
|
||||||
*/
|
*/
|
||||||
export async function truncateAllData(testUri: string): Promise<void> {
|
export async function truncateAllData(testUri: string): Promise<void> {
|
||||||
const client = new Client({ connectionString: testUri });
|
const client = new Client({ connectionString: testUri });
|
||||||
|
|
@ -290,190 +213,13 @@ export function runSeedScripts(testUri: string): void {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Template database + schema-hash cache
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deliberately broad input set for the template cache key. False positives
|
* Full bootstrap, safe to call repeatedly: ensure the database (drop/recreate
|
||||||
* (rebuild with no real change) cost one cold build; misses produce loud but
|
* on hard reset), apply migrations, truncate leftover data, reseed baselines
|
||||||
* confusing "column does not exist" failures, recoverable via
|
* and repair sequences.
|
||||||
* TEST_DB_HARD_RESET=1. When in doubt, add to the list.
|
|
||||||
*/
|
*/
|
||||||
const SCHEMA_HASH_FILES = [
|
export async function bootstrapTestDatabase(): Promise<string> {
|
||||||
"src/payload.config.ts",
|
const testUri = resolveTestDatabaseUri();
|
||||||
"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();
|
const hardReset = hardResetRequested();
|
||||||
|
|
||||||
await ensureTestDatabase(testUri, hardReset);
|
await ensureTestDatabase(testUri, hardReset);
|
||||||
|
|
@ -484,23 +230,7 @@ export async function bootstrapSerialDatabase(testUri: string): Promise<string>
|
||||||
runSeedScripts(testUri);
|
runSeedScripts(testUri);
|
||||||
await repairSequences(testUri);
|
await repairSequences(testUri);
|
||||||
|
|
||||||
console.log(`[test-db] ready: ${testDatabaseName(testUri)}${hardReset ? " (hard reset)" : ""}`);
|
const dbName = testDatabaseName(testUri);
|
||||||
return testUri;
|
console.log(`[test-db] ready: ${dbName}${hardReset ? " (hard reset)" : ""}`);
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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;
|
return testUri;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,7 @@ import { bootstrapTestDatabase } from "./test-db";
|
||||||
/**
|
/**
|
||||||
* Vitest global setup: point the suite at the dedicated test database and
|
* Vitest global setup: point the suite at the dedicated test database and
|
||||||
* leave it in a known state (ensured, migrated, truncated, seeded, sequences
|
* leave it in a known state (ensured, migrated, truncated, seeded, sequences
|
||||||
* repaired) before any test file loads. Stage 2 rewires this entry point to
|
* repaired) before any test file loads.
|
||||||
* 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> {
|
export default async function globalSetup(): Promise<void> {
|
||||||
await bootstrapTestDatabase();
|
await bootstrapTestDatabase();
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue