From dda0cfda1ab42f2a53d04c075da5112245be5656 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 19:55:46 -0500 Subject: [PATCH 1/7] feat(cli): meta verify --uuid-values lists stored uuids the 1.3 write check refuses A read-only pre-upgrade check. With --db or --dialect d1, it reads every field.uuid column (keys, foreign keys, each isArray element) in the governed tables and lists those holding values that are not canonical 8-4-4-4-12 uuids, with a count and samples, exiting 1 when any are found. A native Postgres uuid column is reported as guaranteed and not read. Columns come from the same schema builder meta migrate uses. Node CLI only, like the other live-database checks. --- CHANGELOG.md | 14 +- docs/features/cli.md | 1 + docs/features/migrations-and-drift.md | 24 ++ .../packages/cli/src/commands/verify.ts | 165 +++++++++-- server/typescript/packages/cli/src/index.ts | 14 + .../typescript/packages/cli/src/lib/args.ts | 18 +- .../packages/cli/src/lib/uuid-values-check.ts | 279 ++++++++++++++++++ .../cli/test/__snapshots__/cli.test.ts.snap | 7 + .../cli/test/unit/args-verify.test.ts | 10 +- .../cli/test/verify-uuid-values.test.ts | 267 +++++++++++++++++ .../packages/migrate-ts/src/index.ts | 2 +- .../packages/migrate-ts/src/introspect/d1.ts | 5 +- 12 files changed, 768 insertions(+), 38 deletions(-) create mode 100644 server/typescript/packages/cli/src/lib/uuid-values-check.ts create mode 100644 server/typescript/packages/cli/test/verify-uuid-values.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index a4931d13ba..7d5aa3ba54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,16 @@ here.** ## [Unreleased] +- **`meta verify --uuid-values` lists the stored uuids that 1.3.0's write check refuses.** It is + a read-only check to run before upgrading. With `--db ` (SQLite, libSQL or Postgres), or with + `--dialect d1 [--d1 ] [--remote]`, it reads every `field.uuid` column (keys, foreign keys + and each element of an `isArray` list) in the tables `meta migrate` governs. For each column + holding values that are not canonical 8-4-4-4-12 uuids, such as `"mbr1"` on SQLite or D1, it gives + the count and up to five samples, and it exits 1 when it finds any. A native Postgres `uuid` + column is reported as guaranteed and is not read. The check never writes. With `--uuid-values`, + `--db` is used for this check only, not for the schema gate, and `--format json` carries the + findings in `uuidValues[]`. It is in the Node CLI only, like the other checks that read a live + database. See `docs/features/migrations-and-drift.md`, "`meta verify --uuid-values`". - **C# and Rust render dotted names, a list's `length` and `0` as TypeScript does.** C# resolves a dotted name whole against each context, innermost outward, so a context holding only the first segment no longer hides an outer match (`render-shadowed-dotted-prefix`). The Rust @@ -371,7 +381,9 @@ there is described in full here. This list is where to start. 201 or 200. Check seed scripts, fixtures, imported rows and hand-inserted ids before you upgrade: a row already stored with such an id still reads, and `GET //` on SQLite still answers it, but no client can write that value again. Rewrite the ids to canonical - uuids, or declare the field `field.string` if it was never a uuid. + uuids, or declare the field `field.string` if it was never a uuid. Since 1.3.1, + `meta verify --uuid-values --db ` (or `--dialect d1`) lists those stored values for you, + with a count and samples per column, without writing anything. - **By hand for owned generators, every port: the code writer refuses text that starts with whitespace.** `line`, `open` and `close` (and TypeScript's and Kotlin's `reopen`) throw `ERR_WRITER_LEADING_WHITESPACE` when handed indented text, because the writer indents from the diff --git a/docs/features/cli.md b/docs/features/cli.md index 2461ddc870..a7aa5b852a 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -56,6 +56,7 @@ vocabulary everywhere, each port implementing the modes it supports. | Subverb | What it checks | Touches a DB? | |---|---|---| | `verify --db` | **Schema drift** — does the live database (or snapshot) match the metadata? (migrate engine, ADR-0015) | yes | +| `verify --uuid-values` | **Stored uuid values** (since 1.3.1). This is a read-only check to run before upgrading. With `--db ` or `--dialect d1`, it reads every `field.uuid` column and lists the values that are not canonical 8-4-4-4-12 uuids, which the 1.3 write check refuses. It exits 1 when it finds any. With this flag, `--db` is used for this check only. **Node `meta` only.** See [`migrations-and-drift.md`](migrations-and-drift.md#meta-verify---uuid-values--stored-values-the-uuid-write-check-refuses). | yes (read-only) | | `verify --codegen` | **Codegen drift** — regenerate from metadata in memory and fail if it differs from the committed generated output. Catches "metadata changed but `meta gen` wasn't re-run". **A hand-edited generated file** (Node `meta`): `meta gen` three-way-merges hand edits, so the gate compares the *generated contribution* against the committed `.gen-state/.hashes/` and reports each edited file separately, by path, with how to see the edit and how to drop it. What that report does to the exit code is the `verify.handEdits` key in `.metaobjects/config.json`: `"fail"` exits 1, `"notice"` (and a project without the key, as before 1.3) prints it and exits 0. `meta init` writes `"fail"` for a new project. `--allow-hand-edits` relaxes `fail` to a notice for one run; `--forbid-hand-edits` makes a hand edit fail for one run whatever the key says. The other ports compare the generated files byte for byte, so any edit is drift and fails: `dotnet meta verify --codegen`, `mvn metaobjects:verify` (Java and Kotlin) and `metaobjects verify --codegen` each exit non-zero and name the file. | no | | `verify --templates` | **Template/prompt drift** — `Renderer.verify` checks each `template.*` node's `{{field}}` references against its payload VO (FR-004). A Jinja body (Python and TypeScript, ADR-0061) is checked the same way. | no | | `verify --docs` | **Removed in 1.1.0** (ADR-0034 Amendment 9). It prints where the check went and exits 2: documentation is written by entries in `generators`, so `verify --codegen` checks it with the rest of the declared output. | — | diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index a9ea20bf94..aff63daafe 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -796,6 +796,30 @@ ports reject `--db` (C#, Python, Rust and the Maven goal exit 2 or fail with a p TypeScript CLI); the live-DB-schema `metaobjects:verify` goal was removed along with the runtime auto-create validator. +### `meta verify --uuid-values` — stored values the uuid write check refuses + +```bash +meta verify --uuid-values --db # SQLite, libSQL or Postgres +meta verify --uuid-values --dialect d1 [--d1 DB] [--remote] +``` + +Since 1.3.0 the generated create and update models refuse a `field.uuid` value that is not the +8-4-4-4-12 hex shape, on every dialect. SQLite and D1 store a uuid as text and accepted any +string, so a database may already hold ids such as `"mbr1"`: those rows still read, but no +client can write the value again. Run this check before upgrading. It reads every `field.uuid` +column (keys, foreign keys and `isArray` lists, each element checked) of the tables `meta migrate` +governs, and lists each column holding values that are not canonical, with the count and up to +five of them. It exits 1 when it finds any and never writes. A native Postgres `uuid` (or `uuid[]`) +column is reported as guaranteed and not read, because the database cannot store anything else. +A `field.string` is not read, even one declared `@dbColumnType: uuid`, because no write check +applies to it. + +Fix what it lists in one of two ways. Either rewrite each value to a canonical uuid, along with +every foreign key that points at it, or declare the field `field.string` if it never held uuids. +With `--uuid-values`, the `--db` connection is used for this check only. Run `meta verify --db ` +separately for schema drift. Under `--format json` the findings are in `uuidValues[]`, one row per +column. Only the Node CLI has this check, as it has the other checks that read a live database. + ## Generated-vs-runtime: Kotlin startup validator `KotlinSpringConfigGenerator` emits a `@Configuration` class that re-loads diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index 0a9be5d163..e6753b85f7 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -95,6 +95,7 @@ import { snapshotPath, type SchemaSnapshot, introspectD1, + parseD1Rows, findWranglerConfig, parseWranglerConfig, resolveD1Binding, @@ -155,6 +156,10 @@ import { } from "@metaobjectsdev/render"; import { describeLoadError, reportLoadError } from "../lib/load-error.js"; import { describeError } from "../lib/error-text.js"; +import { + scanUuidColumns, uuidColumnsOf, UUID_SAMPLE_LIMIT, uuidValuesReport, type UuidColumn, type UuidColumnResult, +} from "../lib/uuid-values-check.js"; +import { sql } from "kysely"; const DEFAULT_PROMPTS_DIR = "prompts"; @@ -261,7 +266,8 @@ export async function verifyCommand( "meta verify — running --codegen --templates (default). Explicit subverbs: " + "--templates (prompt drift), --db/--dialect d1 (schema drift), " + "--codegen (drift of everything `generators` declares, documentation included), --deps (dependency drift), " + - "--replay/--replay-snapshot (the committed migration chain replays from empty).", + "--replay/--replay-snapshot (the committed migration chain replays from empty), " + + "--uuid-values with --db/--dialect d1 (stored field.uuid values the 1.3 write check refuses).", ); } @@ -491,7 +497,7 @@ export async function verifyCommand( // internally (it is selected by --db or --dialect d1, not by a subverb flag); // naming it here lets the structured payload report "ran" from the SAME // expression rather than a second guess at it. - const ranSchemaGate = (flags.db !== undefined || flags.dialect === "d1") && !flags.skipSchema; + const ranSchemaGate = (flags.db !== undefined || flags.dialect === "d1") && !flags.skipSchema && !flags.uuidValues; // Exit-code composition: the overall result is the MAX across every selected // subverb so ANY kind of drift fails CI. Each gate only runs when its mode is @@ -503,9 +509,14 @@ export async function verifyCommand( // The schema gate's findings, for the structured payload: what differs, not only that // something does. Left undefined when the gate did not compare anything. let schemaDrift: SchemaDriftSection | undefined; + // Set when the uuid-values scan could not reach or read the database: a failure, not a finding. + let uuidValuesRunError: string | undefined; const schemaExit = await runSchemaVerify(); const codegenExit = runCodegen ? await runCodegenVerify() : 0; const depsExit = runDeps ? await runDepsVerify() : 0; + // The pre-upgrade uuid scan: what it found, for the structured payload. + let uuidValueResults: UuidColumnResult[] | undefined; + const uuidValuesExit = flags.uuidValues ? await runUuidValuesVerify() : 0; // Requirements have no subverb: `requirement.*` nodes are metadata, so they // are checked on every `meta verify`. Opt-in by DECLARATION — a model with no // requirement nodes is silent, not in drift. @@ -553,6 +564,7 @@ export async function verifyCommand( requirementExit, rulesExit, replayExit, + uuidValuesExit, ); const gates: VerifyGateRow[] = [ @@ -569,6 +581,9 @@ export async function verifyCommand( // with nothing to check would change every existing project's payload. ...(rulesSummary !== undefined ? [{ gate: "rules", ran: true, ok: rulesExit === 0 }] : []), { gate: "replay", ran: flags.replay || flags.replaySnapshot, ok: replayExit === 0 }, + // Listed only when selected, like `rules`: a row for an opt-in pre-upgrade scan would + // change every existing project's payload. + ...(flags.uuidValues ? [{ gate: "uuid-values", ran: true, ok: uuidValuesExit === 0 }] : []), ]; // Naming a gate runs ONLY the gates named (ADR-0021 D2), so `verify --codegen --db ` @@ -577,7 +592,7 @@ export async function verifyCommand( // too, at the END where the verdict is read: its opening note scrolls past, and on a model // with no templates the only other line was "nothing to check" over a green exit — easy to // wire into CI believing it guards everything. Never changes the exit code. - const note = notRunNote(gates, { bare: !flags.anyExplicit }); + const note = notRunNote(gates, { bare: !flags.anyExplicit, uuidValues: flags.uuidValues }); if (note !== undefined) say(note); if (structured) { @@ -596,7 +611,11 @@ export async function verifyCommand( ...(rulesSection !== undefined ? { rules: rulesSection } : {}), ...(rulesSummary !== undefined ? { rulesCounts: rulesSummary } : {}), ...(schemaDrift !== undefined ? { schemaDrift } : {}), - errors: schemaRunError !== undefined ? [{ gate: "schema", error: schemaRunError }] : [], + ...(uuidValueResults !== undefined ? { uuidValues: uuidValueResults } : {}), + errors: [ + ...(schemaRunError !== undefined ? [{ gate: "schema", error: schemaRunError }] : []), + ...(uuidValuesRunError !== undefined ? [{ gate: "uuid-values", error: uuidValuesRunError }] : []), + ], }), fmt, ); @@ -1422,7 +1441,7 @@ export async function verifyCommand( // returning 0 — the DB-free default behavior is unchanged. async function runSchemaVerify(): Promise { const usingD1 = flags.dialect === "d1"; - if ((flags.db === undefined && !usingD1) || flags.skipSchema) return 0; + if (!ranSchemaGate) return 0; // A `migrate.scope` matching nothing it could govern is refused, not tolerated — // it would make this gate compare zero objects and report "in sync" (see @@ -1599,6 +1618,47 @@ export async function verifyCommand( // computeDriftFromActual and the SAME reportSchemaDrift the sqlite/postgres // path uses — no forked reporting/exit-code logic. async function runD1SchemaVerify(ledgerDrift: string[]): Promise { + const d1 = await openD1(); + if (typeof d1 === "number") return d1; + const { binding, remote, runner: d1Runner, wranglerConfigPath, displayUrl } = d1; + + let actual; + try { + actual = await introspectD1({ runner: d1Runner, binding: binding.binding, remote, configPath: wranglerConfigPath }); + } catch (err) { + log.error(`verify: failed to introspect D1 binding '${binding.binding}': ${describeError(err)}`); + return 1; + } + + const allow = tokensToAllowOptions(flags.allow); + const expectedViews = buildProjectionViews(root, { dialect: "d1" }); + let driftResult; + try { + driftResult = await computeDriftFromActual(actual, "d1", root, { + ...schema, + allow, + views: expectedViews, + ...(schemaScope !== undefined ? { inScope: schemaScope } : {}), + // Same option bag on the D1 path, for the same reason. + ...importedOption(collection), + }); + } catch (err) { + log.error(`verify: ${describeError(err)}`); + return 1; + } + + return reportSchemaDrift(driftResult, ledgerDrift, displayUrl); + } + + /** + * The D1 database `--dialect d1 [--d1 ] [--remote]` names, reached through the same + * wrangler runner `meta migrate` uses — or the exit code when it cannot be resolved (reported). + * Shared by the schema gate and the uuid-values scan. + */ + async function openD1(): Promise< + | { binding: D1Binding; remote: boolean; runner: D1Runner; wranglerConfigPath: string | undefined; displayUrl: string } + | number + > { const d1Config = await resolveD1Config({ d1Binding: flags.d1, remote: flags.remote }, projectRoot); const wranglerConfigPath = d1Config.wranglerConfigPath @@ -1635,34 +1695,71 @@ export async function verifyCommand( const { stdout } = await activeWranglerRunner(wranglerArgs, projectRoot); return stdout; }; + const displayUrl = `d1:${binding.binding}${remote ? " (--remote)" : " (local)"}`; + return { binding, remote, runner: d1Runner, wranglerConfigPath, displayUrl }; + } - let actual; - try { - actual = await introspectD1({ runner: d1Runner, binding: binding.binding, remote, configPath: wranglerConfigPath }); - } catch (err) { - log.error(`verify: failed to introspect D1 binding '${binding.binding}': ${describeError(err)}`); - return 1; + // -- uuid values (pre-upgrade data check) ------------------------------------ + // Reads every `field.uuid` column of the --db / --dialect d1 database and reports the + // stored values the 1.3 write check refuses. Read-only; see lib/uuid-values-check.ts. + async function runUuidValuesVerify(): Promise { + if (flags.dialect === "d1" && flags.db !== undefined) { + log.error(`verify: --db is not used for dialect 'd1' — wrangler.toml owns the connection; pass --d1 instead`); + return 2; } - - const allow = tokensToAllowOptions(flags.allow); - const expectedViews = buildProjectionViews(root, { dialect: "d1" }); - let driftResult; + let columns: UuidColumn[]; try { - driftResult = await computeDriftFromActual(actual, "d1", root, { - ...schema, - allow, - views: expectedViews, - ...(schemaScope !== undefined ? { inScope: schemaScope } : {}), - // Same option bag on the D1 path, for the same reason. - ...importedOption(collection), - }); + columns = uuidColumnsOf(root, schema, schemaScope); } catch (err) { + if (isEnumLengthRefusal(err)) return refuseEnumLength(err); log.error(`verify: ${describeError(err)}`); return 1; } - const displayUrl = `d1:${binding.binding}${remote ? " (--remote)" : " (local)"}`; - return reportSchemaDrift(driftResult, ledgerDrift, displayUrl); + let report: { lines: string[]; failed: boolean }; + if (flags.dialect === "d1") { + const d1 = await openD1(); + if (typeof d1 === "number") return d1; + try { + uuidValueResults = await scanUuidColumns(columns, "sqlite", async (q) => parseD1Rows(await d1.runner(q))); + } catch (err) { + uuidValuesRunError = `failed to read ${d1.displayUrl}: ${describeError(err)}`; + log.error(`verify: ${uuidValuesRunError}`); + return 1; + } + report = uuidValuesReport(uuidValueResults, d1.displayUrl); + } else { + let kysely; + try { + kysely = await buildKyselyFromUrl(flags.db as string, flags.dialect as Dialect | undefined); + } catch (err) { + uuidValuesRunError = describeError(err); + log.error(`verify: ${uuidValuesRunError}`); + return 1; + } + try { + const db = kysely.db; + const query = async (q: string): Promise[]> => + (await sql.raw>(q).execute(db)).rows; + uuidValueResults = await scanUuidColumns(columns, kysely.dialect === "postgres" ? "postgres" : "sqlite", query); + report = uuidValuesReport(uuidValueResults, kysely.displayUrl); + } catch (err) { + uuidValuesRunError = `failed to read ${kysely.displayUrl}: ${describeError(err)}`; + log.error(`verify: ${uuidValuesRunError}`); + return 1; + } finally { + try { + await kysely.close(); + } catch (err) { + log.warn(`verify: failed to close DB cleanly: ${describeError(err)}`); + } + } + } + for (const line of report.lines) { + if (report.failed) log.error(line); + else say(line); + } + return report.failed ? 1 : 0; } // Shared drift-reporting + exit-code logic for BOTH schema-drift paths (sqlite/ @@ -2301,12 +2398,16 @@ const GATE_SELECTOR: Record = { */ export function notRunNote( gates: readonly VerifyGateRow[], - opts: { bare?: boolean } = {}, + opts: { bare?: boolean; uuidValues?: boolean } = {}, ): string | undefined { const skipped = gates.filter((g) => !g.ran); if (skipped.length === 0) return undefined; const named = skipped.map((g) => { - const flag = GATE_SELECTOR[g.gate]; + // Under --uuid-values the --db connection serves that scan alone, so naming --db as the + // schema gate's selector would tell the reader to pass a flag they already passed. + const flag = opts.uuidValues === true && g.gate === "schema" + ? "a separate 'meta verify --db ' run" + : GATE_SELECTOR[g.gate]; return flag !== undefined ? `${g.gate} (${flag})` : g.gate; }); const tail = opts.bare === true @@ -2368,6 +2469,8 @@ function buildVerifyPayload(input: { rulesCounts?: RulesSummary; /** What the schema gate found, when it compared anything. */ schemaDrift?: SchemaDriftSection; + /** What the uuid-values scan found, one row per field.uuid column, when it ran. */ + uuidValues?: readonly UuidColumnResult[]; /** Gates that could not run at all (an unreachable database) — failures, not drift. */ errors?: readonly { gate: string; error: string }[]; }): Record { @@ -2417,7 +2520,12 @@ function buildVerifyPayload(input: { `the schema gate's differences are in schemaDrift — changes[] (metadata vs database, one row per change) and findings[] (migration ledger and committed snapshot)`, ); } - if (drifted.some((g) => g.gate !== "schema")) { + if (drifted.some((g) => g.gate === "uuid-values") && input.uuidValues !== undefined) { + help.push( + `the uuid-values scan's findings are in uuidValues[] — one row per field.uuid column, with the count of stored values that are not canonical uuids and up to ${UUID_SAMPLE_LIMIT} of them; rewrite them to canonical uuids or declare the field field.string`, + ); + } + if (drifted.some((g) => g.gate !== "schema" && g.gate !== "uuid-values")) { help.push( `the failing gate's drift DETAIL is printed as text on stderr — this payload carries the verdict only`, ); @@ -2480,6 +2588,7 @@ function buildVerifyPayload(input: { ...(input.requirementCounts !== undefined ? { requirementCounts: input.requirementCounts } : {}), ...(input.requirementLedger !== undefined ? { requirementLedger: input.requirementLedger } : {}), ...(input.schemaDrift !== undefined ? { schemaDrift: input.schemaDrift } : {}), + ...(input.uuidValues !== undefined ? { uuidValues: input.uuidValues } : {}), // The honest boundary. Everything named here is REACHABLE — it is printed as // text on stderr — but it is not in this document, and a reader must not have // to discover that by its absence. diff --git a/server/typescript/packages/cli/src/index.ts b/server/typescript/packages/cli/src/index.ts index 6dfbd7ea2a..46dc4b93d2 100644 --- a/server/typescript/packages/cli/src/index.ts +++ b/server/typescript/packages/cli/src/index.ts @@ -127,6 +127,13 @@ VERIFY FLAGS (ADR-0021 D2 — explicit subverbs; combine any; exit 1 on ANY drif Default: CREATE DATABASE on the --db server (dropped afterwards), else the temp-object probe on the target. Also SHADOW_DATABASE_URL or migrate.shadowDatabaseUrl in .metaobjects/config.json. + --uuid-values Pre-upgrade data check, read-only: with --db (or --dialect d1), + read every field.uuid column and list each one whose stored values + are not canonical 8-4-4-4-12 uuids, with a count and samples. Since + 1.3.0 a create or update carrying such a value is refused. Exits 1 + when any is found. A native Postgres uuid column is not read (the + type already guarantees it). With this flag --db serves the scan + only; run 'meta verify --db ' for schema drift. --prompts Directory of provider-resolved template text (default: prompts) --dialect sqlite|postgres|d1 Optional override (auto-detected from --db URL scheme) --allow Accepted for parity with 'migrate'; does NOT affect the @@ -386,6 +393,13 @@ FLAGS: no longer builds the recorded schema. Does NOT apply to a project adopted with 'migrate baseline --from-db' (its chain does not build the schema); use --replay there. + --uuid-values Pre-upgrade data check, read-only: with --db (or --dialect d1), + read every field.uuid column and list each one whose stored values + are not canonical 8-4-4-4-12 uuids, with a count and samples. Since + 1.3.0 a create or update carrying such a value is refused. Exits 1 + when any is found. A native Postgres uuid column is not read (the + type already guarantees it). With this flag --db serves the scan + only; run 'meta verify --db ' for schema drift. --prompts Directory of provider-resolved template text (default: prompts) --dialect sqlite|postgres|d1 Optional override (auto-detected from --db URL scheme) --allow Accepted for parity with 'migrate'; does NOT affect the drift gate diff --git a/server/typescript/packages/cli/src/lib/args.ts b/server/typescript/packages/cli/src/lib/args.ts index 99bbaa1bce..cbca22f4db 100644 --- a/server/typescript/packages/cli/src/lib/args.ts +++ b/server/typescript/packages/cli/src/lib/args.ts @@ -491,7 +491,15 @@ export interface VerifyFlags { * gate. */ deps: boolean; - /** Whether ANY explicit subverb flag (--templates/--db/--codegen/--docs/--deps/--replay*) was passed. */ + /** + * Read the values already stored in every `field.uuid` column of the `--db` (or + * `--dialect d1`) database and report those that are not canonical 8-4-4-4-12 uuids — + * the values the 1.3 write check refuses. Read-only. When it is passed the connection + * serves this check alone: the schema gate is not also selected by `--db`, because a + * pre-upgrade scan must not fail on schema drift the upgrade itself is about to settle. + */ + uuidValues: boolean; + /** Whether ANY explicit subverb flag (--templates/--db/--codegen/--docs/--deps/--replay, --replay-snapshot, --uuid-values) was passed. */ anyExplicit: boolean; /** Suppress the advisory anti-pattern (verify-as-teacher) pass. */ noAntipatterns: boolean; @@ -591,6 +599,7 @@ export const VERIFY_OPTIONS = { // where the check went instead of an unknown-flag error. docs: { type: "boolean", default: false }, deps: { type: "boolean", default: false }, + "uuid-values": { type: "boolean", default: false }, replay: { type: "boolean", default: false }, "replay-snapshot": { type: "boolean", default: false }, "no-antipatterns": { type: "boolean", default: false }, @@ -667,6 +676,12 @@ export function parseVerifyArgs(argv: string[]): VerifyFlags { const deps = !!values.deps; const replay = !!values.replay; const replaySnapshot = !!values["replay-snapshot"]; + const uuidValues = !!values["uuid-values"]; + if (uuidValues && values.db === undefined && dialect !== "d1") { + throw new Error( + "--uuid-values reads a database: pass --db , or --dialect d1 [--d1 ] [--remote]. Run: meta verify --uuid-values --db ", + ); + } // --db is itself an explicit subverb selector: passing a connection URL means // "run the schema-drift mode". So is `--dialect d1` (D1 has no --db connection // URL — see the `d1` field doc above). The replay flags are subverbs too, and @@ -691,6 +706,7 @@ export function parseVerifyArgs(argv: string[]): VerifyFlags { full: !!values.full, docs, deps, + uuidValues, replay, replaySnapshot, anyExplicit, diff --git a/server/typescript/packages/cli/src/lib/uuid-values-check.ts b/server/typescript/packages/cli/src/lib/uuid-values-check.ts new file mode 100644 index 0000000000..f88216411c --- /dev/null +++ b/server/typescript/packages/cli/src/lib/uuid-values-check.ts @@ -0,0 +1,279 @@ +// `meta verify --uuid-values` — a read-only scan of the values already stored in every +// `field.uuid` column. +// +// 1.3.0 made the generated create and update schemas refuse a `field.uuid` value that is +// not the 8-4-4-4-12 hex shape, on every dialect. Postgres stores a uuid in a native +// `uuid` column, which could never hold anything else; SQLite and D1 store it as text and +// accepted any string. A project whose rows carry ids such as `"mbr1"` still reads them +// after the upgrade, but no client can write those values again. This scan finds them +// BEFORE the upgrade: per column, how many stored values are not canonical and a few of +// them. It never writes. +// +// The columns come from the schema builder `meta migrate` and `verify --db` use, so a +// table and column are named exactly as the database names them; the fields come from the +// loaded metadata, so only a `field.uuid` is checked (a `field.string @dbColumnType: uuid` +// has no write check to fall foul of). + +import { + FIELD_ATTR_OBJECT_REF, + FIELD_ATTR_STORAGE, + FIELD_SUBTYPE_OBJECT, + FIELD_SUBTYPE_UUID, + OBJECT_ATTR_DISCRIMINATOR, + STORAGE_FLATTENED, + TYPE_OBJECT, + isMetaObject, + physicalNamingOf, + refTarget, + resolveColumnName, + resolveFlattenedColumnName, + type MetaData, +} from "@metaobjectsdev/metadata"; +import { buildExpectedSchemaWithProvenance, qualifiedDbName, type SchemaBuildSettings } from "@metaobjectsdev/migrate-ts"; + +/** The canonical shape the 1.3 write check accepts: 8-4-4-4-12 hex digits, either case. */ +export const CANONICAL_UUID_PATTERN = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"; + +/** How many distinct offending values a finding quotes. */ +export const UUID_SAMPLE_LIMIT = 5; + +/** One physical column that holds a `field.uuid` (a key, a foreign key or any other uuid field). */ +export interface UuidColumn { + schema?: string; + table: string; + column: string; + /** `field.uuid @isArray`: the column holds a list, each element checked. */ + isArray: boolean; + /** Every field stored in this column, as `Object.field` (a TPH table can fold several). */ + fields: string[]; +} + +/** What the scan found in one column. */ +export interface UuidColumnResult { + table: string; + column: string; + fields: string[]; + /** `native`: the database column type guarantees canonical values, so it was not read. */ + status: "scanned" | "native" | "missing"; + nonCanonical: number; + samples: string[]; +} + +/** Runs one read-only query and returns its rows. */ +export type RowQuery = (sql: string) => Promise[]>; + +/** The SQL family the scan speaks: Postgres, or SQLite (which D1 is). */ +export type UuidScanDialect = "postgres" | "sqlite"; + +/** + * Every governed table column that stores a `field.uuid`. `inScope` is the `migrate.scope` + * predicate `verify --db` honours, so the scan reads the tables `meta migrate` owns and no + * others. The schema is built for Postgres only to name things: table and column names do + * not depend on the dialect, and the Postgres build refuses nothing SQLite accepts here. + */ +export function uuidColumnsOf( + root: MetaData, + settings: SchemaBuildSettings, + inScope?: (fqn: string) => boolean, +): UuidColumn[] { + const built = buildExpectedSchemaWithProvenance(root, { ...settings, dialect: "postgres" }); + const strategy = physicalNamingOf(root).columns; + + // The table each table-owning object writes, keyed by its resolution key. + const tableOf = new Map }>(); + for (const t of built.snapshot.tables) { + const owner = built.provenance.get(qualifiedDbName(t)); + if (owner === undefined) continue; + if (inScope !== undefined && !inScope(owner)) continue; + tableOf.set(owner, { + ...(t.schema !== undefined ? { schema: t.schema } : {}), + table: t.name, + columns: new Set(t.columns.map((c) => c.name)), + }); + } + + const found = new Map(); + const add = ( + target: { schema?: string; table: string; columns: Set }, + column: string, + isArray: boolean, + label: string, + ): void => { + // A column the schema builder does not emit (a derived field, a name this walk got + // wrong) is not read: only what `meta migrate` creates is scanned. + if (!target.columns.has(column)) return; + const key = `${target.schema ?? ""}\u0000${target.table}\u0000${column}`; + const existing = found.get(key); + if (existing !== undefined) { + if (!existing.fields.includes(label)) existing.fields.push(label); + return; + } + found.set(key, { + ...(target.schema !== undefined ? { schema: target.schema } : {}), + table: target.table, + column, + isArray, + fields: [label], + }); + }; + + // ADR-0039: effective children of the root and effective fields of each object, so a + // field inherited through `extends` is found where its table stores it. + for (const obj of root.children()) { + if (obj.type !== TYPE_OBJECT || !isMetaObject(obj) || obj.isAbstract) continue; + const target = tableOf.get(obj.resolutionKey()) ?? tableOf.get(tphBaseKey(obj) ?? ""); + if (target === undefined) continue; + for (const field of obj.fields()) { + if (field.isDerived()) continue; + const label = `${obj.name}.${field.name}`; + if (field.subType === FIELD_SUBTYPE_UUID) { + add(target, resolveColumnName(field, strategy), field.resolvedIsArray(), label); + } else if ( + field.subType === FIELD_SUBTYPE_OBJECT && + // ADR-0039: resolving — @storage may be inherited via extends. + field.attr(FIELD_ATTR_STORAGE) === STORAGE_FLATTENED + ) { + const vo = refTarget(field, FIELD_ATTR_OBJECT_REF); + if (vo === undefined || !isMetaObject(vo)) continue; + for (const member of vo.fields()) { + if (member.subType !== FIELD_SUBTYPE_UUID) continue; + add(target, resolveFlattenedColumnName(field, member, strategy), member.resolvedIsArray(), `${label}.${member.name}`); + } + } + } + } + return [...found.values()].sort((a, b) => + `${a.schema ?? ""}.${a.table}.${a.column}`.localeCompare(`${b.schema ?? ""}.${b.table}.${b.column}`)); +} + +/** The resolution key of the TPH discriminator base whose table `obj`'s rows live in. */ +function tphBaseKey(obj: MetaData): string | undefined { + let a = obj.superResolved; + while (a !== undefined) { + // ADR-0039 category 3: a super-resolution walk reads each ancestor's OWN @discriminator. + if (a.ownAttr(OBJECT_ATTR_DISCRIMINATOR) !== undefined) return a.resolutionKey(); + a = a.superResolved; + } + return undefined; +} + +const ident = (name: string): string => `"${name.replaceAll(`"`, `""`)}"`; +const literal = (value: string): string => `'${value.replaceAll("'", "''")}'`; + +/** SQLite has no regular expressions by default; GLOB with one class per digit is exact. */ +const SQLITE_UUID_GLOB = [8, 4, 4, 4, 12].map((n) => "[0-9a-fA-F]".repeat(n)).join("-"); + +/** Scan every column; reads only, and never more than a count and a few samples per column. */ +export async function scanUuidColumns( + columns: readonly UuidColumn[], + dialect: UuidScanDialect, + query: RowQuery, +): Promise { + const results: UuidColumnResult[] = []; + for (const col of columns) { + results.push(dialect === "postgres" ? await scanPostgres(col, query) : await scanSqlite(col, query)); + } + return results; +} + +async function scanSqlite(col: UuidColumn, query: RowQuery): Promise { + const table = ident(col.table); + const column = `${table}.${ident(col.column)}`; + const base = { table: col.table, column: col.column, fields: col.fields }; + const exists = await query(`SELECT 1 AS ok FROM pragma_table_info(${literal(col.table)}) WHERE name = ${literal(col.column)}`); + if (exists.length === 0) return { ...base, status: "missing", nonCanonical: 0, samples: [] }; + + const notCanonical = (v: string, type: string): string => + `(${type} <> 'text' OR ${v} NOT GLOB ${literal(SQLITE_UUID_GLOB)})`; + // A scalar column: each non-null value. An array column holds JSON text: each element + // of a well-formed array, and the whole stored value when it is not a JSON array at all. + const offenders = col.isArray + ? [ + `SELECT CAST(j.value AS TEXT) AS v FROM ${table}, json_each(${column}) AS j ` + + `WHERE json_valid(${column}) AND json_type(${column}) = 'array' AND j.value IS NOT NULL AND ${notCanonical("j.value", "j.type")}`, + `SELECT CAST(${column} AS TEXT) AS v FROM ${table} ` + + `WHERE ${column} IS NOT NULL AND (NOT json_valid(${column}) OR json_type(${column}) <> 'array')`, + ].join(" UNION ALL ") + : `SELECT CAST(${column} AS TEXT) AS v FROM ${table} WHERE ${column} IS NOT NULL AND ${notCanonical(column, `typeof(${column})`)}`; + return { ...base, status: "scanned", ...(await countAndSample(offenders, query)) }; +} + +async function scanPostgres(col: UuidColumn, query: RowQuery): Promise { + const base = { table: col.table, column: col.column, fields: col.fields }; + const schema = col.schema !== undefined ? literal(col.schema) : "current_schema()"; + const typeRows = await query( + `SELECT udt_name FROM information_schema.columns WHERE table_schema = ${schema} ` + + `AND table_name = ${literal(col.table)} AND column_name = ${literal(col.column)}`, + ); + if (typeRows.length === 0) return { ...base, status: "missing", nonCanonical: 0, samples: [] }; + const udt = String(typeRows[0]?.udt_name ?? ""); + // A native uuid (or uuid[]) column holds nothing else: the database already guarantees it. + if (udt === "uuid" || udt === "_uuid") return { ...base, status: "native", nonCanonical: 0, samples: [] }; + + const table = col.schema !== undefined ? `${ident(col.schema)}.${ident(col.table)}` : ident(col.table); + const column = `t.${ident(col.column)}`; + const pattern = literal(CANONICAL_UUID_PATTERN); + let offenders: string; + if (col.isArray && udt.startsWith("_")) { + offenders = `SELECT e.v::text AS v FROM ${table} AS t, unnest(${column}) AS e(v) WHERE e.v IS NOT NULL AND e.v::text !~ ${pattern}`; + } else if (col.isArray && (udt === "jsonb" || udt === "json")) { + offenders = `SELECT e.v AS v FROM ${table} AS t, jsonb_array_elements_text(${column}::jsonb) AS e(v) ` + + `WHERE jsonb_typeof(${column}::jsonb) = 'array' AND e.v IS NOT NULL AND e.v !~ ${pattern}`; + } else { + offenders = `SELECT ${column}::text AS v FROM ${table} AS t WHERE ${column} IS NOT NULL AND ${column}::text !~ ${pattern}`; + } + return { ...base, status: "scanned", ...(await countAndSample(offenders, query)) }; +} + +async function countAndSample( + offenders: string, + query: RowQuery, +): Promise<{ nonCanonical: number; samples: string[] }> { + const countRows = await query(`SELECT COUNT(*) AS n FROM (${offenders}) AS o`); + const nonCanonical = Number(countRows[0]?.n ?? 0); + if (nonCanonical === 0) return { nonCanonical, samples: [] }; + const sampleRows = await query(`SELECT DISTINCT o.v AS v FROM (${offenders}) AS o ORDER BY o.v LIMIT ${UUID_SAMPLE_LIMIT}`); + return { nonCanonical, samples: sampleRows.map((r) => String(r.v)) }; +} + +/** A stored value as a finding quotes it: JSON-quoted, and cut short when it is long. */ +export function quoteSample(value: string): string { + const max = 60; + return JSON.stringify(value.length > max ? `${value.slice(0, max)}…` : value); +} + +/** The printed report: one line per column, then the verdict. Exported for its test. */ +export function uuidValuesReport(results: readonly UuidColumnResult[], displayUrl: string): { lines: string[]; failed: boolean } { + const lines: string[] = []; + if (results.length === 0) { + lines.push(`meta verify --uuid-values — no field.uuid column in ${displayUrl}'s governed tables; nothing to scan.`); + return { lines, failed: false }; + } + lines.push(`meta verify --uuid-values — ${results.length} field.uuid column(s) in ${displayUrl}:`); + let offending = 0; + let total = 0; + for (const r of results) { + const where = ` ${r.table}.${r.column} (${r.fields.join(", ")})`; + if (r.status === "native") { + lines.push(`${where}: native uuid column — the database only stores canonical uuids, not scanned`); + } else if (r.status === "missing") { + lines.push(`${where}: column not in the database — not scanned (meta verify --db reports schema drift)`); + } else if (r.nonCanonical === 0) { + lines.push(`${where}: every stored value is a canonical uuid`); + } else { + offending++; + total += r.nonCanonical; + lines.push(`${where}: ${r.nonCanonical} value(s) not a canonical uuid, e.g. ${r.samples.map(quoteSample).join(", ")}`); + } + } + if (offending === 0) { + lines.push("meta verify --uuid-values — every stored field.uuid value is canonical; the 1.3 uuid write check refuses none of them."); + return { lines, failed: false }; + } + lines.push( + `meta verify --uuid-values — ${total} stored value(s) in ${offending} column(s) are not canonical 8-4-4-4-12 uuids. ` + + "The rows still read, but since 1.3.0 a create or update carrying such a value is refused (400 validation). " + + "Rewrite each value to a canonical uuid (and every foreign key that points at it), or declare the field field.string if it never held uuids.", + ); + return { lines, failed: true }; +} diff --git a/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap b/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap index c332533737..916fdce725 100644 --- a/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap +++ b/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap @@ -105,6 +105,13 @@ VERIFY FLAGS (ADR-0021 D2 — explicit subverbs; combine any; exit 1 on ANY drif Default: CREATE DATABASE on the --db server (dropped afterwards), else the temp-object probe on the target. Also SHADOW_DATABASE_URL or migrate.shadowDatabaseUrl in .metaobjects/config.json. + --uuid-values Pre-upgrade data check, read-only: with --db (or --dialect d1), + read every field.uuid column and list each one whose stored values + are not canonical 8-4-4-4-12 uuids, with a count and samples. Since + 1.3.0 a create or update carrying such a value is refused. Exits 1 + when any is found. A native Postgres uuid column is not read (the + type already guarantees it). With this flag --db serves the scan + only; run 'meta verify --db ' for schema drift. --prompts Directory of provider-resolved template text (default: prompts) --dialect sqlite|postgres|d1 Optional override (auto-detected from --db URL scheme) --allow Accepted for parity with 'migrate'; does NOT affect the diff --git a/server/typescript/packages/cli/test/unit/args-verify.test.ts b/server/typescript/packages/cli/test/unit/args-verify.test.ts index 57d44374d0..8e87f11b2c 100644 --- a/server/typescript/packages/cli/test/unit/args-verify.test.ts +++ b/server/typescript/packages/cli/test/unit/args-verify.test.ts @@ -6,7 +6,7 @@ describe("parseVerifyArgs", () => { test("defaults: prompts/db/dialect undefined, allow empty, skipSchema false, no explicit subverb", () => { expect(parseVerifyArgs([])).toEqual({ prompts: undefined, db: undefined, dialect: undefined, allow: [], skipSchema: false, migrationFormat: undefined, - templates: false, codegen: false, forbidHandEdits: false, allowHandEdits: false, full: false, docs: false, deps: false, anyExplicit: false, noAntipatterns: false, noRequirementLint: false, requireImplementers: false, noOverlayLint: false, noNameLint: false, noDeprecationLint: false, noFieldLint: false, lax: false, + templates: false, codegen: false, forbidHandEdits: false, allowHandEdits: false, full: false, docs: false, deps: false, uuidValues: false, anyExplicit: false, noAntipatterns: false, noRequirementLint: false, requireImplementers: false, noOverlayLint: false, noNameLint: false, noDeprecationLint: false, noFieldLint: false, lax: false, replay: false, replaySnapshot: false, d1: undefined, remote: false, limit: DEFAULT_ADVISORY_LIMIT, }); @@ -14,7 +14,7 @@ describe("parseVerifyArgs", () => { test("--prompts is captured", () => { expect(parseVerifyArgs(["--prompts", "templates"])).toEqual({ prompts: "templates", db: undefined, dialect: undefined, allow: [], skipSchema: false, migrationFormat: undefined, - templates: false, codegen: false, forbidHandEdits: false, allowHandEdits: false, full: false, docs: false, deps: false, anyExplicit: false, noAntipatterns: false, noRequirementLint: false, requireImplementers: false, noOverlayLint: false, noNameLint: false, noDeprecationLint: false, noFieldLint: false, lax: false, + templates: false, codegen: false, forbidHandEdits: false, allowHandEdits: false, full: false, docs: false, deps: false, uuidValues: false, anyExplicit: false, noAntipatterns: false, noRequirementLint: false, requireImplementers: false, noOverlayLint: false, noNameLint: false, noDeprecationLint: false, noFieldLint: false, lax: false, replay: false, replaySnapshot: false, d1: undefined, remote: false, limit: DEFAULT_ADVISORY_LIMIT, }); @@ -22,7 +22,7 @@ describe("parseVerifyArgs", () => { test("--db / --dialect / --skip-schema are captured", () => { expect(parseVerifyArgs(["--db", "file:x.db", "--dialect", "sqlite", "--skip-schema"])).toEqual({ prompts: undefined, db: "file:x.db", dialect: "sqlite", allow: [], skipSchema: true, migrationFormat: undefined, - templates: false, codegen: false, forbidHandEdits: false, allowHandEdits: false, full: false, docs: false, deps: false, anyExplicit: true, noAntipatterns: false, noRequirementLint: false, requireImplementers: false, noOverlayLint: false, noNameLint: false, noDeprecationLint: false, noFieldLint: false, lax: false, + templates: false, codegen: false, forbidHandEdits: false, allowHandEdits: false, full: false, docs: false, deps: false, uuidValues: false, anyExplicit: true, noAntipatterns: false, noRequirementLint: false, requireImplementers: false, noOverlayLint: false, noNameLint: false, noDeprecationLint: false, noFieldLint: false, lax: false, replay: false, replaySnapshot: false, d1: undefined, remote: false, limit: DEFAULT_ADVISORY_LIMIT, }); @@ -32,7 +32,7 @@ describe("parseVerifyArgs", () => { test("--dialect d1 --d1 --remote are captured; --dialect d1 alone is an explicit subverb", () => { expect(parseVerifyArgs(["--dialect", "d1", "--d1", "DB", "--remote"])).toEqual({ prompts: undefined, db: undefined, dialect: "d1", allow: [], skipSchema: false, migrationFormat: undefined, - templates: false, codegen: false, forbidHandEdits: false, allowHandEdits: false, full: false, docs: false, deps: false, anyExplicit: true, noAntipatterns: false, noRequirementLint: false, requireImplementers: false, noOverlayLint: false, noNameLint: false, noDeprecationLint: false, noFieldLint: false, lax: false, + templates: false, codegen: false, forbidHandEdits: false, allowHandEdits: false, full: false, docs: false, deps: false, uuidValues: false, anyExplicit: true, noAntipatterns: false, noRequirementLint: false, requireImplementers: false, noOverlayLint: false, noNameLint: false, noDeprecationLint: false, noFieldLint: false, lax: false, replay: false, replaySnapshot: false, d1: "DB", remote: true, limit: DEFAULT_ADVISORY_LIMIT, }); @@ -77,7 +77,7 @@ describe("parseVerifyArgs", () => { expect(parseVerifyArgs(["--allow", "drop-column,drop-table"])).toEqual({ prompts: undefined, db: undefined, dialect: undefined, allow: ["drop-column", "drop-table"], skipSchema: false, migrationFormat: undefined, - templates: false, codegen: false, forbidHandEdits: false, allowHandEdits: false, full: false, docs: false, deps: false, anyExplicit: false, noAntipatterns: false, noRequirementLint: false, requireImplementers: false, noOverlayLint: false, noNameLint: false, noDeprecationLint: false, noFieldLint: false, lax: false, + templates: false, codegen: false, forbidHandEdits: false, allowHandEdits: false, full: false, docs: false, deps: false, uuidValues: false, anyExplicit: false, noAntipatterns: false, noRequirementLint: false, requireImplementers: false, noOverlayLint: false, noNameLint: false, noDeprecationLint: false, noFieldLint: false, lax: false, replay: false, replaySnapshot: false, d1: undefined, remote: false, limit: DEFAULT_ADVISORY_LIMIT, }); diff --git a/server/typescript/packages/cli/test/verify-uuid-values.test.ts b/server/typescript/packages/cli/test/verify-uuid-values.test.ts new file mode 100644 index 0000000000..fc83f7017b --- /dev/null +++ b/server/typescript/packages/cli/test/verify-uuid-values.test.ts @@ -0,0 +1,267 @@ +/** + * `meta verify --uuid-values` — the read-only pre-upgrade scan of stored `field.uuid` values. + * + * 1.3.0 refuses a create or update whose `field.uuid` value is not the 8-4-4-4-12 shape. SQLite + * and D1 store a uuid as text and accepted anything, so a database can already hold ids such as + * "mbr1" that no client can write again after the upgrade. The scan lists them, per column, and + * exits 1; it never writes. On Postgres a native uuid column is reported as guaranteed, not read. + */ +import { describe, test, expect, afterAll } from "bun:test"; +import { Database } from "bun:sqlite"; +import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import pg from "pg"; +import { verifyCommand } from "../src/commands/verify.js"; +import { uuidColumnsOf, uuidValuesReport } from "../src/lib/uuid-values-check.js"; +import { parseVerifyArgs } from "../src/lib/args.js"; +import { loadMemory } from "@metaobjectsdev/sdk"; + +const dirs: string[] = []; +afterAll(async () => { for (const d of dirs) await rm(d, { recursive: true, force: true }); }); + +const CANONICAL_A = "3f2b8c1e-9d4a-4b7e-8c21-5a6f0e9d1b23"; +const CANONICAL_B = "00000000-0000-0000-0000-000000000001"; + +/** Member (uuid key), Claim (uuid key, uuid FK, uuid list, a string column the scan must ignore). */ +const MODEL = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Member", children: [ + { "source.rdb": { "@table": "members" } }, + { "field.uuid": { name: "id" } }, + { "field.string": { name: "name" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + { "object.entity": { name: "Claim", children: [ + { "source.rdb": { "@table": "claims" } }, + { "field.uuid": { name: "id" } }, + { "field.uuid": { name: "memberId" } }, + { "field.uuid": { name: "witnessIds", isArray: true } }, + { "field.string": { name: "legacyRef", "@dbColumnType": "uuid" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + { "identity.reference": { name: "ref_member", "@fields": ["memberId"], "@references": "Member" } }, + ] } }, +] } }; + +async function project(model: unknown = MODEL): Promise { + const root = await mkdtemp(join(tmpdir(), "verify-uuid-values-")); + dirs.push(root); + await mkdir(join(root, "metaobjects"), { recursive: true }); + await writeFile(join(root, "metaobjects", "meta.acme.json"), JSON.stringify(model), "utf8"); + await mkdir(join(root, ".metaobjects"), { recursive: true }); + await writeFile(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1 }), "utf8"); + return root; +} + +/** A SQLite file shaped like the model's tables, holding the given rows. */ +function sqliteDb(path: string, members: string[], claims: [string, string, string | null, string | null][]): void { + const db = new Database(path); + db.run("CREATE TABLE members (id TEXT PRIMARY KEY, name TEXT)"); + db.run("CREATE TABLE claims (id TEXT PRIMARY KEY, member_id TEXT, witness_ids TEXT, legacy_ref TEXT)"); + for (const id of members) db.run("INSERT INTO members (id, name) VALUES (?, 'x')", [id]); + for (const row of claims) db.run("INSERT INTO claims (id, member_id, witness_ids, legacy_ref) VALUES (?, ?, ?, ?)", row); + db.close(); +} + +async function capture(fn: () => Promise): Promise<{ code: number; out: string; stdout: string }> { + const lines: string[] = []; + const stdout: string[] = []; + const log = console.log; + const err = console.error; + const write = process.stdout.write.bind(process.stdout); + console.log = (...a: unknown[]) => { const s = a.map(String).join(" "); lines.push(s); stdout.push(s); }; + console.error = (...a: unknown[]) => { lines.push(a.map(String).join(" ")); }; + process.stdout.write = ((chunk: string | Uint8Array) => { stdout.push(String(chunk)); return true; }) as typeof process.stdout.write; + try { + const code = await fn(); + return { code, out: lines.join("\n"), stdout: stdout.join("") }; + } finally { + console.log = log; + console.error = err; + process.stdout.write = write; + } +} + +describe("meta verify --uuid-values — which columns it reads", () => { + test("every field.uuid column: keys, foreign keys and lists; never a field.string, even one stored as uuid", async () => { + const root = await project(); + const loaded = await loadMemory(root); + const cols = uuidColumnsOf(loaded, {}); + expect(cols.map((c) => `${c.table}.${c.column}${c.isArray ? "[]" : ""} ${c.fields.join(",")}`)).toEqual([ + "claims.id Claim.id", + "claims.member_id Claim.memberId", + "claims.witness_ids[] Claim.witnessIds", + "members.id Member.id", + ]); + }); + + test("a TPH subtype's uuid field is read in its base's table, and an inherited one where the extender stores it", async () => { + const root = await project({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Keyed", abstract: true, children: [ + { "field.uuid": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + { "object.entity": { name: "Party", extends: "Keyed", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "parties" } }, + { "field.string": { name: "kind" } }, + ] } }, + { "object.entity": { name: "Person", extends: "Party", "@discriminatorValue": "person", children: [ + { "field.uuid": { name: "householdId" } }, + ] } }, + ] } }); + const loaded = await loadMemory(root); + const cols = uuidColumnsOf(loaded, {}); + expect(cols.map((c) => `${c.table}.${c.column} ${c.fields.join(",")}`)).toEqual([ + "parties.household_id Person.householdId", + "parties.id Party.id,Person.id", + ]); + }); + + test("--uuid-values without a database is refused at parse time", () => { + expect(() => parseVerifyArgs(["--uuid-values"])).toThrow(/--uuid-values reads a database/); + expect(parseVerifyArgs(["--uuid-values", "--dialect", "d1"]).uuidValues).toBe(true); + }); + + test("the report: nothing to scan, all canonical, and findings", () => { + expect(uuidValuesReport([], "file:x").failed).toBe(false); + const clean = uuidValuesReport([{ table: "t", column: "id", fields: ["T.id"], status: "scanned", nonCanonical: 0, samples: [] }], "file:x"); + expect(clean.failed).toBe(false); + const bad = uuidValuesReport([{ table: "t", column: "id", fields: ["T.id"], status: "scanned", nonCanonical: 2, samples: ["a", "b"] }], "file:x"); + expect(bad.failed).toBe(true); + expect(bad.lines.join("\n")).toContain(`t.id (T.id): 2 value(s) not a canonical uuid, e.g. "a", "b"`); + }); +}); + +describe("meta verify --uuid-values — SQLite", () => { + test("non-canonical keys, foreign keys and list elements are counted and quoted; exit 1", async () => { + const root = await project(); + const file = join(root, "app.db"); + sqliteDb(file, ["mbr1", CANONICAL_A], [ + [CANONICAL_B, "mbr1", JSON.stringify([CANONICAL_A, "w-1"]), "not-checked"], + ["clm2", CANONICAL_A, "not json", null], + [CANONICAL_A.toUpperCase().replace("3F", "4F"), CANONICAL_A, null, null], + ]); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); + + expect(code).toBe(1); + expect(out).toContain(`members.id (Member.id): 1 value(s) not a canonical uuid, e.g. "mbr1"`); + expect(out).toContain(`claims.member_id (Claim.memberId): 1 value(s) not a canonical uuid, e.g. "mbr1"`); + expect(out).toContain(`claims.id (Claim.id): 1 value(s) not a canonical uuid, e.g. "clm2"`); + // One bad element of a well-formed list, and one stored value that is not a JSON list at all. + expect(out).toContain(`claims.witness_ids (Claim.witnessIds): 2 value(s) not a canonical uuid, e.g. "not json", "w-1"`); + expect(out).not.toContain("legacy_ref"); + expect(out).toContain("5 stored value(s) in 4 column(s) are not canonical"); + // `--db` served the scan alone: the hand-made tables differ from the expected schema, + // and the schema gate was not run to say so. + expect(out).not.toContain("schema drift"); + }); + + test("a database holding only canonical uuids (either case) passes; the database is unchanged", async () => { + const root = await project(); + const file = join(root, "clean.db"); + sqliteDb(file, [CANONICAL_A, CANONICAL_A.toUpperCase().replace("3F", "5F")], [ + [CANONICAL_B, CANONICAL_A, JSON.stringify([CANONICAL_B]), "anything"], + ]); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); + expect(code).toBe(0); + expect(out).toContain("every stored field.uuid value is canonical"); + const db = new Database(file, { readonly: true }); + expect((db.query("SELECT COUNT(*) AS n FROM members").get() as { n: number }).n).toBe(2); + db.close(); + }); + + test("--format json carries one row per column and the gate verdict", async () => { + const root = await project(); + const file = join(root, "json.db"); + sqliteDb(file, ["mbr1"], []); + const { code, stdout } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root, undefined, "json")); + expect(code).toBe(1); + const payload = JSON.parse(stdout) as { + verify: { gate: string; ran: boolean; ok: boolean }[]; + uuidValues: { table: string; column: string; status: string; nonCanonical: number; samples: string[] }[]; + help: string[]; + }; + expect(payload.verify).toContainEqual({ gate: "uuid-values", ran: true, ok: false }); + expect(payload.verify.find((g) => g.gate === "schema")?.ran).toBe(false); + expect(payload.uuidValues.find((r) => r.table === "members")).toMatchObject({ status: "scanned", nonCanonical: 1, samples: ["mbr1"] }); + expect(payload.help.some((h) => h.includes("uuidValues[]"))).toBe(true); + }); + + test("a column missing from the database is named, not read, and does not fail the scan", async () => { + const root = await project(); + const file = join(root, "partial.db"); + const db = new Database(file); + db.run("CREATE TABLE members (id TEXT PRIMARY KEY, name TEXT)"); + db.close(); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); + expect(code).toBe(0); + expect(out).toContain("claims.member_id (Claim.memberId): column not in the database"); + }); +}); + +describe("meta verify --uuid-values — D1", () => { + const WRANGLER_TOML = [ + `name = "test-app"`, + `[[d1_databases]]`, + `binding = "DB"`, + `database_name = "test-db"`, + `database_id = "test-id"`, + ].join("\n"); + + test("reads through wrangler with the SQLite queries, and fails on what it finds", async () => { + const root = await project(); + await writeFile(join(root, "wrangler.toml"), WRANGLER_TOML, "utf8"); + const seen: string[] = []; + const runner = async (args: string[]): Promise<{ stdout: string; stderr: string }> => { + const q = args[args.indexOf("--command") + 1] ?? ""; + seen.push(q); + const results = + q.includes("pragma_table_info") ? [{ ok: 1 }] + : q.startsWith("SELECT COUNT(*)") ? [{ n: q.includes(`"members"`) ? 2 : 0 }] + : q.startsWith("SELECT DISTINCT") ? [{ v: "mbr1" }, { v: "mbr2" }] + : []; + return { stdout: JSON.stringify([{ success: true, results }]), stderr: "" }; + }; + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--dialect", "d1"], root, runner)); + expect(code).toBe(1); + expect(out).toContain(`members.id (Member.id): 2 value(s) not a canonical uuid, e.g. "mbr1", "mbr2"`); + expect(out).toContain("d1:DB (local)"); + // Read-only: every statement it sent is a SELECT. + expect(seen.length).toBeGreaterThan(0); + for (const q of seen) expect(q.trimStart().startsWith("SELECT")).toBe(true); + }); +}); + +describe("meta verify --uuid-values — Postgres (env-gated: MIGRATE_TS_PG_URL)", () => { + test("a native uuid column is guaranteed and not read; a text column is scanned", async () => { + const pgUrl = process.env.MIGRATE_TS_PG_URL; + if (pgUrl === undefined || pgUrl.length === 0) return; + const admin = new pg.Client({ connectionString: pgUrl }); + await admin.connect(); + const name = `mt_uuidv_${Date.now()}_${Math.floor(Math.random() * 1e6)}`; + await admin.query(`CREATE DATABASE ${name}`); + try { + const url = new URL(pgUrl); + url.pathname = `/${name}`; + const c = new pg.Client({ connectionString: url.toString() }); + await c.connect(); + try { + // members.id native uuid; claims stored as text, as an older hand-made schema might. + await c.query("CREATE TABLE members (id uuid PRIMARY KEY, name text)"); + await c.query("CREATE TABLE claims (id uuid PRIMARY KEY, member_id text, witness_ids uuid[], legacy_ref uuid)"); + await c.query(`INSERT INTO members VALUES ('${CANONICAL_A}', 'x')`); + await c.query(`INSERT INTO claims VALUES ('${CANONICAL_B}', 'mbr1', ARRAY['${CANONICAL_A}']::uuid[], NULL)`); + } finally { + await c.end(); + } + const root = await project(); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", url.toString()], root)); + expect(code).toBe(1); + expect(out).toContain("members.id (Member.id): native uuid column"); + expect(out).toContain("claims.witness_ids (Claim.witnessIds): native uuid column"); + expect(out).toContain(`claims.member_id (Claim.memberId): 1 value(s) not a canonical uuid, e.g. "mbr1"`); + } finally { + await admin.query(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); + await admin.end(); + } + }); +}); diff --git a/server/typescript/packages/migrate-ts/src/index.ts b/server/typescript/packages/migrate-ts/src/index.ts index d3e2f6ef22..1a7f07923b 100644 --- a/server/typescript/packages/migrate-ts/src/index.ts +++ b/server/typescript/packages/migrate-ts/src/index.ts @@ -131,7 +131,7 @@ export { export type { D1RebuildRefusal } from "./emit/d1-fk-refuse.js"; // D1 introspection -export { introspectD1, type D1Runner, type IntrospectD1Options } from "./introspect/d1.js"; +export { introspectD1, parseD1Rows, type D1Runner, type IntrospectD1Options } from "./introspect/d1.js"; // Migration-history ledger + ordered transactional apply (postgres/sqlite) export { diff --git a/server/typescript/packages/migrate-ts/src/introspect/d1.ts b/server/typescript/packages/migrate-ts/src/introspect/d1.ts index b14afc35e7..66f8c3dbd7 100644 --- a/server/typescript/packages/migrate-ts/src/introspect/d1.ts +++ b/server/typescript/packages/migrate-ts/src/introspect/d1.ts @@ -33,7 +33,7 @@ export interface IntrospectD1Options { export async function introspectD1(opts: IntrospectD1Options): Promise { const exec: Exec = async (sql: string) => { const stdout = await opts.runner(sql); - return parseEnvelope(stdout); + return parseD1Rows(stdout); }; // sqlite_version() is blocked by workerd's local D1 sandbox, so we fall back @@ -107,7 +107,8 @@ export async function introspectD1(opts: IntrospectD1Options): Promise[] { +/** The result rows of one `wrangler d1 execute --json` envelope; throws on a failed or unreadable one. */ +export function parseD1Rows(stdout: string): Record[] { let parsed: unknown; try { parsed = JSON.parse(stdout); From 14b5857b198a3d465c3b89be989c3c10da8c6cd9 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 20:09:25 -0500 Subject: [PATCH 2/7] no-mistakes(review): Scan JSON VO uuids; fix dialect and false greens --- CHANGELOG.md | 13 +- docs/features/migrations-and-drift.md | 16 +- .../packages/cli/src/commands/verify.ts | 23 +- .../packages/cli/src/lib/uuid-values-check.ts | 252 +++++++++++++++--- .../cli/test/verify-uuid-values.test.ts | 203 +++++++++++++- 5 files changed, 443 insertions(+), 64 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d5aa3ba54..b9c80f69a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,10 +13,15 @@ here.** - **`meta verify --uuid-values` lists the stored uuids that 1.3.0's write check refuses.** It is a read-only check to run before upgrading. With `--db ` (SQLite, libSQL or Postgres), or with `--dialect d1 [--d1 ] [--remote]`, it reads every `field.uuid` column (keys, foreign keys - and each element of an `isArray` list) in the tables `meta migrate` governs. For each column - holding values that are not canonical 8-4-4-4-12 uuids, such as `"mbr1"` on SQLite or D1, it gives - the count and up to five samples, and it exits 1 when it finds any. A native Postgres `uuid` - column is reported as guaranteed and is not read. The check never writes. With `--uuid-values`, + and each element of an `isArray` list, where a JSON `null` element counts as not canonical) in the + tables `meta migrate` governs. It also reads each `field.uuid` member of a value object stored as + JSON, including nested value objects and lists of value objects, and names the member by its path + (`claims.meta $.memberId`). For each column or member holding values that are not canonical + 8-4-4-4-12 uuids, such as `"mbr1"` on SQLite or D1, it gives the count and up to five samples, and + it exits 1 when it finds any. A native Postgres `uuid` column is reported as guaranteed and is not + read. A database that holds none of the columns fails the check as a probable wrong database, and + a column missing from the database is named and counted as not scanned. The check never writes. + A `--db` file inside wrangler's local D1 state gets the same warning as the schema gate. With `--uuid-values`, `--db` is used for this check only, not for the schema gate, and `--format json` carries the findings in `uuidValues[]`. It is in the Node CLI only, like the other checks that read a live database. See `docs/features/migrations-and-drift.md`, "`meta verify --uuid-values`". diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index aff63daafe..0f89668017 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -809,11 +809,25 @@ string, so a database may already hold ids such as `"mbr1"`: those rows still re client can write the value again. Run this check before upgrading. It reads every `field.uuid` column (keys, foreign keys and `isArray` lists, each element checked) of the tables `meta migrate` governs, and lists each column holding values that are not canonical, with the count and up to -five of them. It exits 1 when it finds any and never writes. A native Postgres `uuid` (or `uuid[]`) +five of them. A JSON `null` element of a list counts as not canonical, because the write check +refuses it. It exits 1 when it finds any and never writes. A native Postgres `uuid` (or `uuid[]`) column is reported as guaranteed and not read, because the database cannot store anything else. A `field.string` is not read, even one declared `@dbColumnType: uuid`, because no write check applies to it. +The write check also validates the members of a value object, so the check reads each +`field.uuid` member of a value object stored as JSON (any `field.object` that is not +`@storage: flattened`). That includes nested value objects and lists of value objects. Each +member is reported with its JSON path, for example `claims.meta $.memberId` or +`claims.history $[*].tagIds[*]`. An absent or `null` member is not counted. A flattened value +object's `field.uuid` members are their own columns and are read as columns. + +A column that is not in the database is named and not read, and the verdict says how many columns +were not scanned. When the database holds none of the columns, the check fails with "wrong +database?" instead of passing, because it read nothing. A `--db` file inside wrangler's local D1 +state (`.wrangler/state/**/d1/**`) is the local database, so the check warns and points to +`--uuid-values --dialect d1 --remote` for the deployed one. + Fix what it lists in one of two ways. Either rewrite each value to a canonical uuid, along with every foreign key that points at it, or declare the field `field.string` if it never held uuids. With `--uuid-values`, the `--db` connection is used for this check only. Run `meta verify --db ` diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index e6753b85f7..55979adbfe 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -157,7 +157,7 @@ import { import { describeLoadError, reportLoadError } from "../lib/load-error.js"; import { describeError } from "../lib/error-text.js"; import { - scanUuidColumns, uuidColumnsOf, UUID_SAMPLE_LIMIT, uuidValuesReport, type UuidColumn, type UuidColumnResult, + scanUuidColumns, uuidColumnsOf, UUID_SAMPLE_LIMIT, uuidValuesReport, type UuidColumn, type UuidColumnResult, type UuidScanDialect, } from "../lib/uuid-values-check.js"; import { sql } from "kysely"; @@ -1708,20 +1708,23 @@ export async function verifyCommand( return 2; } let columns: UuidColumn[]; + let scanDialect: UuidScanDialect; try { - columns = uuidColumnsOf(root, schema, schemaScope); + scanDialect = flags.dialect !== "d1" && (flags.dialect ?? inferDialect(flags.db as string)) === "postgres" ? "postgres" : "sqlite"; + columns = uuidColumnsOf(root, schema, scanDialect, schemaScope); } catch (err) { if (isEnumLengthRefusal(err)) return refuseEnumLength(err); + if (isInvalidCheckNameError(err)) { log.error(`verify: ${err.message}`); return 1; } log.error(`verify: ${describeError(err)}`); return 1; } - let report: { lines: string[]; failed: boolean }; + let report: ReturnType; if (flags.dialect === "d1") { const d1 = await openD1(); if (typeof d1 === "number") return d1; try { - uuidValueResults = await scanUuidColumns(columns, "sqlite", async (q) => parseD1Rows(await d1.runner(q))); + uuidValueResults = await scanUuidColumns(columns, scanDialect, async (q) => parseD1Rows(await d1.runner(q))); } catch (err) { uuidValuesRunError = `failed to read ${d1.displayUrl}: ${describeError(err)}`; log.error(`verify: ${uuidValuesRunError}`); @@ -1729,6 +1732,15 @@ export async function verifyCommand( } report = uuidValuesReport(uuidValueResults, d1.displayUrl); } else { + // #225, as the schema gate warns: a file inside wrangler's local D1 state is the LOCAL + // database, so a clean scan of it says nothing about the deployed one. + if (isWranglerLocalD1StatePath(flags.db as string)) { + log.warn( + `verify: --db '${flags.db}' points inside a wrangler local D1 state directory — this ` + + `reads the LOCAL database, not the deployed one. Use 'verify --uuid-values --dialect d1 --d1 --remote' ` + + `to read the deployed D1 database.`, + ); + } let kysely; try { kysely = await buildKyselyFromUrl(flags.db as string, flags.dialect as Dialect | undefined); @@ -1741,7 +1753,7 @@ export async function verifyCommand( const db = kysely.db; const query = async (q: string): Promise[]> => (await sql.raw>(q).execute(db)).rows; - uuidValueResults = await scanUuidColumns(columns, kysely.dialect === "postgres" ? "postgres" : "sqlite", query); + uuidValueResults = await scanUuidColumns(columns, scanDialect, query); report = uuidValuesReport(uuidValueResults, kysely.displayUrl); } catch (err) { uuidValuesRunError = `failed to read ${kysely.displayUrl}: ${describeError(err)}`; @@ -1759,6 +1771,7 @@ export async function verifyCommand( if (report.failed) log.error(line); else say(line); } + if (report.error !== undefined) uuidValuesRunError = report.error; return report.failed ? 1 : 0; } diff --git a/server/typescript/packages/cli/src/lib/uuid-values-check.ts b/server/typescript/packages/cli/src/lib/uuid-values-check.ts index f88216411c..90f01ee77b 100644 --- a/server/typescript/packages/cli/src/lib/uuid-values-check.ts +++ b/server/typescript/packages/cli/src/lib/uuid-values-check.ts @@ -12,7 +12,8 @@ // The columns come from the schema builder `meta migrate` and `verify --db` use, so a // table and column are named exactly as the database names them; the fields come from the // loaded metadata, so only a `field.uuid` is checked (a `field.string @dbColumnType: uuid` -// has no write check to fall foul of). +// has no write check to fall foul of). A `field.uuid` member of a value object stored as JSON +// is read inside its column, because the write check validates the value object's members too. import { FIELD_ATTR_OBJECT_REF, @@ -37,14 +38,28 @@ export const CANONICAL_UUID_PATTERN = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F /** How many distinct offending values a finding quotes. */ export const UUID_SAMPLE_LIMIT = 5; +/** One step into a JSON-stored value object: the member's key, and whether it holds a list. */ +export interface UuidJsonStep { + key: string; + isArray: boolean; +} + /** One physical column that holds a `field.uuid` (a key, a foreign key or any other uuid field). */ export interface UuidColumn { schema?: string; table: string; column: string; - /** `field.uuid @isArray`: the column holds a list, each element checked. */ + /** + * The column's stored value is a list: of uuids (`field.uuid @isArray`, each element checked), + * or of value objects when `members` is not empty. + */ isArray: boolean; - /** Every field stored in this column, as `Object.field` (a TPH table can fold several). */ + /** + * The path to a `field.uuid` member inside a value object stored as JSON in this column, outermost + * first; empty when the column stores the uuid itself. + */ + members: UuidJsonStep[]; + /** Every field stored at this place, as `Object.field` (a TPH table can fold several). */ fields: string[]; } @@ -52,6 +67,8 @@ export interface UuidColumn { export interface UuidColumnResult { table: string; column: string; + /** Where inside the column's JSON the uuid member is read, such as `$[*].memberId`. */ + jsonPath?: string; fields: string[]; /** `native`: the database column type guarantees canonical values, so it was not read. */ status: "scanned" | "native" | "missing"; @@ -68,15 +85,16 @@ export type UuidScanDialect = "postgres" | "sqlite"; /** * Every governed table column that stores a `field.uuid`. `inScope` is the `migrate.scope` * predicate `verify --db` honours, so the scan reads the tables `meta migrate` owns and no - * others. The schema is built for Postgres only to name things: table and column names do - * not depend on the dialect, and the Postgres build refuses nothing SQLite accepts here. + * others. The schema is built for the dialect the scan reads, because the build refuses some + * models on Postgres only (a CHECK name over 63 bytes, two CHECKs sharing one name). */ export function uuidColumnsOf( root: MetaData, settings: SchemaBuildSettings, + dialect: UuidScanDialect, inScope?: (fqn: string) => boolean, ): UuidColumn[] { - const built = buildExpectedSchemaWithProvenance(root, { ...settings, dialect: "postgres" }); + const built = buildExpectedSchemaWithProvenance(root, { ...settings, dialect }); const strategy = physicalNamingOf(root).columns; // The table each table-owning object writes, keyed by its resolution key. @@ -98,11 +116,12 @@ export function uuidColumnsOf( column: string, isArray: boolean, label: string, + members: UuidJsonStep[], ): void => { // A column the schema builder does not emit (a derived field, a name this walk got // wrong) is not read: only what `meta migrate` creates is scanned. if (!target.columns.has(column)) return; - const key = `${target.schema ?? ""}\u0000${target.table}\u0000${column}`; + const key = `${target.schema ?? ""}\u0000${target.table}\u0000${column}\u0000${jsonPathOf(isArray, members) ?? ""}`; const existing = found.get(key); if (existing !== undefined) { if (!existing.fields.includes(label)) existing.fields.push(label); @@ -113,10 +132,37 @@ export function uuidColumnsOf( table: target.table, column, isArray, + members, fields: [label], }); }; + // A value object stored as JSON: each `field.uuid` member, and the members of a nested value + // object, which the JSON holds inline. `seen` stops a value object that contains itself. + const addJsonMembers = ( + target: { schema?: string; table: string; columns: Set }, + column: string, + isArray: boolean, + vo: MetaData, + steps: UuidJsonStep[], + label: string, + seen: ReadonlySet, + ): void => { + if (!isMetaObject(vo)) return; + for (const member of vo.fields()) { + if (member.isDerived()) continue; + const path = [...steps, { key: member.name, isArray: member.resolvedIsArray() }]; + const memberLabel = `${label}.${member.name}`; + if (member.subType === FIELD_SUBTYPE_UUID) { + add(target, column, isArray, memberLabel, path); + } else if (member.subType === FIELD_SUBTYPE_OBJECT) { + const inner = refTarget(member, FIELD_ATTR_OBJECT_REF); + if (inner === undefined || seen.has(inner)) continue; + addJsonMembers(target, column, isArray, inner, path, memberLabel, new Set([...seen, inner])); + } + } + }; + // ADR-0039: effective children of the root and effective fields of each object, so a // field inherited through `extends` is found where its table stores it. for (const obj of root.children()) { @@ -127,23 +173,47 @@ export function uuidColumnsOf( if (field.isDerived()) continue; const label = `${obj.name}.${field.name}`; if (field.subType === FIELD_SUBTYPE_UUID) { - add(target, resolveColumnName(field, strategy), field.resolvedIsArray(), label); - } else if ( - field.subType === FIELD_SUBTYPE_OBJECT && - // ADR-0039: resolving — @storage may be inherited via extends. - field.attr(FIELD_ATTR_STORAGE) === STORAGE_FLATTENED - ) { + add(target, resolveColumnName(field, strategy), field.resolvedIsArray(), label, []); + } else if (field.subType === FIELD_SUBTYPE_OBJECT) { const vo = refTarget(field, FIELD_ATTR_OBJECT_REF); if (vo === undefined || !isMetaObject(vo)) continue; - for (const member of vo.fields()) { - if (member.subType !== FIELD_SUBTYPE_UUID) continue; - add(target, resolveFlattenedColumnName(field, member, strategy), member.resolvedIsArray(), `${label}.${member.name}`); + // ADR-0039: resolving — @storage may be inherited via extends. + if (field.attr(FIELD_ATTR_STORAGE) === STORAGE_FLATTENED) { + for (const member of vo.fields()) { + if (member.subType !== FIELD_SUBTYPE_UUID) continue; + add(target, resolveFlattenedColumnName(field, member, strategy), member.resolvedIsArray(), `${label}.${member.name}`, []); + } + } else { + // Any other storage keeps the whole value object in one JSON column. + addJsonMembers(target, resolveColumnName(field, strategy), field.resolvedIsArray(), vo, [], label, new Set([vo])); } } } } - return [...found.values()].sort((a, b) => - `${a.schema ?? ""}.${a.table}.${a.column}`.localeCompare(`${b.schema ?? ""}.${b.table}.${b.column}`)); + const sortKey = (c: UuidColumn): string => `${c.schema ?? ""}.${c.table}.${c.column}${jsonPathOf(c.isArray, c.members) ?? ""}`; + return [...found.values()].sort((a, b) => sortKey(a).localeCompare(sortKey(b))); +} + +/** A member path as a JSON path (`$[*].memberId`), or undefined for a column storing the uuid itself. */ +function jsonPathOf(isArray: boolean, members: readonly UuidJsonStep[]): string | undefined { + if (members.length === 0) return undefined; + return `$${isArray ? "[*]" : ""}${members.map((m) => `.${m.key}${m.isArray ? "[*]" : ""}`).join("")}`; +} + +/** + * The walk from a column to the uuid values a member path names: each `each` opens a list, + * each `key` reads a member. The last step's list, if any, is left to the caller, which also + * reports a value that should be a list and is not. + */ +type JsonOp = { op: "each" } | { op: "key"; key: string }; + +function jsonOps(col: UuidColumn): { ops: JsonOp[]; leafIsArray: boolean } { + const ops: JsonOp[] = col.isArray ? [{ op: "each" }] : []; + col.members.forEach((m, i) => { + ops.push({ op: "key", key: m.key }); + if (m.isArray && i < col.members.length - 1) ops.push({ op: "each" }); + }); + return { ops, leafIsArray: col.members.at(-1)?.isArray ?? false }; } /** The resolution key of the TPH discriminator base whose table `obj`'s rows live in. */ @@ -176,30 +246,80 @@ export async function scanUuidColumns( return results; } +function resultBase(col: UuidColumn): Pick { + const jsonPath = jsonPathOf(col.isArray, col.members); + return { table: col.table, column: col.column, ...(jsonPath !== undefined ? { jsonPath } : {}), fields: col.fields }; +} + async function scanSqlite(col: UuidColumn, query: RowQuery): Promise { const table = ident(col.table); const column = `${table}.${ident(col.column)}`; - const base = { table: col.table, column: col.column, fields: col.fields }; + const base = resultBase(col); const exists = await query(`SELECT 1 AS ok FROM pragma_table_info(${literal(col.table)}) WHERE name = ${literal(col.column)}`); if (exists.length === 0) return { ...base, status: "missing", nonCanonical: 0, samples: [] }; const notCanonical = (v: string, type: string): string => `(${type} <> 'text' OR ${v} NOT GLOB ${literal(SQLITE_UUID_GLOB)})`; - // A scalar column: each non-null value. An array column holds JSON text: each element - // of a well-formed array, and the whole stored value when it is not a JSON array at all. - const offenders = col.isArray - ? [ - `SELECT CAST(j.value AS TEXT) AS v FROM ${table}, json_each(${column}) AS j ` + - `WHERE json_valid(${column}) AND json_type(${column}) = 'array' AND j.value IS NOT NULL AND ${notCanonical("j.value", "j.type")}`, - `SELECT CAST(${column} AS TEXT) AS v FROM ${table} ` + - `WHERE ${column} IS NOT NULL AND (NOT json_valid(${column}) OR json_type(${column}) <> 'array')`, - ].join(" UNION ALL ") - : `SELECT CAST(${column} AS TEXT) AS v FROM ${table} WHERE ${column} IS NOT NULL AND ${notCanonical(column, `typeof(${column})`)}`; + let offenders: string; + if (col.members.length > 0) { + offenders = sqliteMemberOffenders(col, table, column, notCanonical); + } else if (col.isArray) { + // An array column holds JSON text: each element of a well-formed array (a JSON null + // element included, which the write check refuses), and the whole stored value when it + // is not a JSON array at all. + offenders = [ + `SELECT COALESCE(CAST(j.value AS TEXT), 'null') AS v FROM ${table}, json_each(${column}) AS j ` + + `WHERE json_valid(${column}) AND json_type(${column}) = 'array' AND ${notCanonical("j.value", "j.type")}`, + `SELECT CAST(${column} AS TEXT) AS v FROM ${table} ` + + `WHERE ${column} IS NOT NULL AND (NOT json_valid(${column}) OR json_type(${column}) <> 'array')`, + ].join(" UNION ALL "); + } else { + offenders = `SELECT CAST(${column} AS TEXT) AS v FROM ${table} WHERE ${column} IS NOT NULL AND ${notCanonical(column, `typeof(${column})`)}`; + } return { ...base, status: "scanned", ...(await countAndSample(offenders, query)) }; } +/** + * The uuid member a path names inside a JSON-stored value object, on SQLite. A stored value + * that is not valid JSON, or not shaped as the path expects on the way down, holds no member to + * read; an absent or null member is not a value the write check sees as a uuid. + */ +function sqliteMemberOffenders( + col: UuidColumn, + table: string, + column: string, + notCanonical: (v: string, type: string) => string, +): string { + const from = [table]; + let v = `(CASE WHEN json_valid(${column}) THEN ${column} END)`; + let t = `json_type(${v})`; + const each = (): void => { + const alias = `j${from.length}`; + from.push(`json_each(CASE WHEN ${t} = 'array' THEN ${v} ELSE '[]' END) AS ${alias}`); + v = `${alias}.value`; + t = `${alias}.type`; + }; + const { ops, leafIsArray } = jsonOps(col); + for (const step of ops) { + if (step.op === "each") { + each(); + } else { + const obj = `(CASE WHEN ${t} = 'object' THEN ${v} END)`; + const path = literal(`$.${JSON.stringify(step.key)}`); + v = `json_extract(${obj}, ${path})`; + t = `json_type(${obj}, ${path})`; + } + } + if (!leafIsArray) { + return `SELECT CAST(${v} AS TEXT) AS v FROM ${from.join(", ")} WHERE ${t} <> 'null' AND ${notCanonical(v, t)}`; + } + const notAList = `SELECT CAST(${v} AS TEXT) AS v FROM ${from.join(", ")} WHERE ${t} NOT IN ('array', 'null')`; + each(); + return `SELECT COALESCE(CAST(${v} AS TEXT), 'null') AS v FROM ${from.join(", ")} WHERE ${notCanonical(v, t)} UNION ALL ${notAList}`; +} + async function scanPostgres(col: UuidColumn, query: RowQuery): Promise { - const base = { table: col.table, column: col.column, fields: col.fields }; + const base = resultBase(col); const schema = col.schema !== undefined ? literal(col.schema) : "current_schema()"; const typeRows = await query( `SELECT udt_name FROM information_schema.columns WHERE table_schema = ${schema} ` + @@ -208,23 +328,54 @@ async function scanPostgres(col: UuidColumn, query: RowQuery): Promise 0 || (col.isArray && (udt === "jsonb" || udt === "json"))) { + offenders = postgresJsonOffenders(col, `${table} AS t`, `${column}::jsonb`, pattern); + } else if (col.isArray && udt.startsWith("_")) { + // A null element counts: the write check refuses it. + offenders = `SELECT COALESCE(e.v::text, 'null') AS v FROM ${table} AS t, unnest(${column}) AS e(v) WHERE e.v IS NULL OR e.v::text !~ ${pattern}`; } else { offenders = `SELECT ${column}::text AS v FROM ${table} AS t WHERE ${column} IS NOT NULL AND ${column}::text !~ ${pattern}`; } return { ...base, status: "scanned", ...(await countAndSample(offenders, query)) }; } +/** + * The uuid values a JSON column holds, on Postgres: a list column's elements, or the member a + * path names inside a value object. A JSON null element of a uuid list counts (the write check + * refuses it), and so does a stored value that should be a list and is not; an absent or null + * member does not. + */ +function postgresJsonOffenders(col: UuidColumn, from: string, start: string, pattern: string): string { + const joins: string[] = []; + let v = start; + const each = (): void => { + const alias = `e${joins.length}`; + joins.push(`CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(${v}) = 'array' THEN ${v} ELSE '[]'::jsonb END) AS ${alias}(v)`); + v = `${alias}.v`; + }; + const { ops, leafIsArray } = col.members.length === 0 ? { ops: [], leafIsArray: true } : jsonOps(col); + for (const step of ops) { + if (step.op === "each") each(); + else v = `(${v} -> ${literal(step.key)})`; + } + const source = (): string => [from, ...joins].join(" "); + const offending = (x: string): string => `(jsonb_typeof(${x}) <> 'string' OR ${x} #>> '{}' !~ ${pattern})`; + if (!leafIsArray) { + return `SELECT ${v} #>> '{}' AS v FROM ${source()} WHERE jsonb_typeof(${v}) <> 'null' AND ${offending(v)}`; + } + const notAList = `SELECT ${v}::text AS v FROM ${source()} WHERE jsonb_typeof(${v}) NOT IN ('array', 'null')`; + each(); + return `SELECT COALESCE(${v} #>> '{}', 'null') AS v FROM ${source()} WHERE ${offending(v)} UNION ALL ${notAList}`; +} + async function countAndSample( offenders: string, query: RowQuery, @@ -242,8 +393,15 @@ export function quoteSample(value: string): string { return JSON.stringify(value.length > max ? `${value.slice(0, max)}…` : value); } -/** The printed report: one line per column, then the verdict. Exported for its test. */ -export function uuidValuesReport(results: readonly UuidColumnResult[], displayUrl: string): { lines: string[]; failed: boolean } { +/** + * The printed report: one line per column, then the verdict. Exported for its test. `error` is + * set when the database holds none of the columns, so nothing was read: most likely the wrong + * database, and never a pass. + */ +export function uuidValuesReport( + results: readonly UuidColumnResult[], + displayUrl: string, +): { lines: string[]; failed: boolean; error?: string } { const lines: string[] = []; if (results.length === 0) { lines.push(`meta verify --uuid-values — no field.uuid column in ${displayUrl}'s governed tables; nothing to scan.`); @@ -253,7 +411,7 @@ export function uuidValuesReport(results: readonly UuidColumnResult[], displayUr let offending = 0; let total = 0; for (const r of results) { - const where = ` ${r.table}.${r.column} (${r.fields.join(", ")})`; + const where = ` ${r.table}.${r.column}${r.jsonPath !== undefined ? ` ${r.jsonPath}` : ""} (${r.fields.join(", ")})`; if (r.status === "native") { lines.push(`${where}: native uuid column — the database only stores canonical uuids, not scanned`); } else if (r.status === "missing") { @@ -266,14 +424,26 @@ export function uuidValuesReport(results: readonly UuidColumnResult[], displayUr lines.push(`${where}: ${r.nonCanonical} value(s) not a canonical uuid, e.g. ${r.samples.map(quoteSample).join(", ")}`); } } + const missing = results.filter((r) => r.status === "missing").length; + if (missing === results.length) { + const error = `no field.uuid column found in ${displayUrl} — wrong database? None of the ${missing} column(s) exists there, so no value was read`; + lines.push(`meta verify --uuid-values — ${error}.`); + return { lines, failed: true, error }; + } + const notScanned = missing > 0 ? ` ${missing} column(s) not in the database were not scanned.` : ""; if (offending === 0) { - lines.push("meta verify --uuid-values — every stored field.uuid value is canonical; the 1.3 uuid write check refuses none of them."); + lines.push( + missing > 0 + ? `meta verify --uuid-values — every stored field.uuid value in the ${results.length - missing} column(s) present is canonical; the 1.3 uuid write check refuses none of them.${notScanned}` + : "meta verify --uuid-values — every stored field.uuid value is canonical; the 1.3 uuid write check refuses none of them.", + ); return { lines, failed: false }; } lines.push( `meta verify --uuid-values — ${total} stored value(s) in ${offending} column(s) are not canonical 8-4-4-4-12 uuids. ` + "The rows still read, but since 1.3.0 a create or update carrying such a value is refused (400 validation). " + - "Rewrite each value to a canonical uuid (and every foreign key that points at it), or declare the field field.string if it never held uuids.", + "Rewrite each value to a canonical uuid (and every foreign key that points at it), or declare the field field.string if it never held uuids." + + notScanned, ); return { lines, failed: true }; } diff --git a/server/typescript/packages/cli/test/verify-uuid-values.test.ts b/server/typescript/packages/cli/test/verify-uuid-values.test.ts index fc83f7017b..eccede381a 100644 --- a/server/typescript/packages/cli/test/verify-uuid-values.test.ts +++ b/server/typescript/packages/cli/test/verify-uuid-values.test.ts @@ -24,6 +24,38 @@ const CANONICAL_A = "3f2b8c1e-9d4a-4b7e-8c21-5a6f0e9d1b23"; const CANONICAL_B = "00000000-0000-0000-0000-000000000001"; /** Member (uuid key), Claim (uuid key, uuid FK, uuid list, a string column the scan must ignore). */ +/** Claim keeps a value object `meta` and a list of them, `history`, in JSON columns. */ +const VO_MODEL = { "metadata.root": { package: "acme", children: [ + { "object.value": { name: "Owner", children: [ + { "field.uuid": { name: "ownerId" } }, + ] } }, + { "object.value": { name: "ClaimMeta", children: [ + { "field.uuid": { name: "memberId" } }, + { "field.uuid": { name: "tagIds", isArray: true } }, + { "field.string": { name: "note" } }, + { "field.object": { name: "owner", "@objectRef": "Owner" } }, + ] } }, + { "object.entity": { name: "Claim", children: [ + { "source.rdb": { "@table": "claims" } }, + { "field.uuid": { name: "id" } }, + { "field.object": { name: "meta", "@objectRef": "ClaimMeta" } }, + { "field.object": { name: "history", "@objectRef": "ClaimMeta", "@storage": "jsonb", isArray: true } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, +] } }; + +/** Two comparison CHECKs that share the default name `windows_a_cmp_chk`. */ +const SAME_NAMED_CHECKS_MODEL = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Window", children: [ + { "source.rdb": { "@table": "windows" } }, + { "field.uuid": { name: "id" } }, + { "field.int": { name: "a" } }, { "field.int": { name: "b" } }, { "field.int": { name: "c" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + { "validator.comparison": { name: "ab", "@left": "a", "@op": "lt", "@right": "b" } }, + { "validator.comparison": { name: "ac", "@left": "a", "@op": "lt", "@right": "c" } }, + ] } }, +] } }; + const MODEL = { "metadata.root": { package: "acme", children: [ { "object.entity": { name: "Member", children: [ { "source.rdb": { "@table": "members" } }, @@ -85,7 +117,7 @@ describe("meta verify --uuid-values — which columns it reads", () => { test("every field.uuid column: keys, foreign keys and lists; never a field.string, even one stored as uuid", async () => { const root = await project(); const loaded = await loadMemory(root); - const cols = uuidColumnsOf(loaded, {}); + const cols = uuidColumnsOf(loaded, {}, "sqlite"); expect(cols.map((c) => `${c.table}.${c.column}${c.isArray ? "[]" : ""} ${c.fields.join(",")}`)).toEqual([ "claims.id Claim.id", "claims.member_id Claim.memberId", @@ -109,13 +141,46 @@ describe("meta verify --uuid-values — which columns it reads", () => { ] } }, ] } }); const loaded = await loadMemory(root); - const cols = uuidColumnsOf(loaded, {}); + const cols = uuidColumnsOf(loaded, {}, "sqlite"); expect(cols.map((c) => `${c.table}.${c.column} ${c.fields.join(",")}`)).toEqual([ "parties.household_id Person.householdId", "parties.id Party.id,Person.id", ]); }); + test("a field.uuid member of a value object stored as JSON is read inside its column, nested and in lists", async () => { + const root = await project(VO_MODEL); + const loaded = await loadMemory(root); + const cols = uuidColumnsOf(loaded, {}, "sqlite"); + expect(cols.map((c) => `${c.table}.${c.column} ${c.members.length > 0 ? `${c.isArray ? "[*]" : ""}${c.members.map((m) => `.${m.key}${m.isArray ? "[*]" : ""}`).join("")} ` : ""}${c.fields.join(",")}`)).toEqual([ + "claims.history [*].memberId Claim.history.memberId", + "claims.history [*].owner.ownerId Claim.history.owner.ownerId", + "claims.history [*].tagIds[*] Claim.history.tagIds", + "claims.id Claim.id", + "claims.meta .memberId Claim.meta.memberId", + "claims.meta .owner.ownerId Claim.meta.owner.ownerId", + "claims.meta .tagIds[*] Claim.meta.tagIds", + ]); + }); + + test("the schema is built for the dialect it reads: a model Postgres refuses still scans on SQLite", async () => { + // Two CHECKs under one default name: SQLite and D1 keep both, Postgres refuses the model. + const root = await project(SAME_NAMED_CHECKS_MODEL); + const loaded = await loadMemory(root); + expect(() => uuidColumnsOf(loaded, {}, "postgres")).toThrow(/Postgres requires/); + expect(uuidColumnsOf(loaded, {}, "sqlite").map((c) => `${c.table}.${c.column}`)).toEqual(["windows.id"]); + + const file = join(root, "windows.db"); + const db = new Database(file); + db.run("CREATE TABLE windows (id TEXT PRIMARY KEY, a INTEGER, b INTEGER, c INTEGER)"); + db.run("INSERT INTO windows VALUES ('win1', 1, 2, 3)"); + db.close(); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); + expect(code).toBe(1); + expect(out).toContain(`windows.id (Window.id): 1 value(s) not a canonical uuid, e.g. "win1"`); + expect(out).not.toContain("Postgres requires"); + }); + test("--uuid-values without a database is refused at parse time", () => { expect(() => parseVerifyArgs(["--uuid-values"])).toThrow(/--uuid-values reads a database/); expect(parseVerifyArgs(["--uuid-values", "--dialect", "d1"]).uuidValues).toBe(true); @@ -195,6 +260,71 @@ describe("meta verify --uuid-values — SQLite", () => { const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); expect(code).toBe(0); expect(out).toContain("claims.member_id (Claim.memberId): column not in the database"); + // The verdict does not claim every stored value: three columns were never read. + expect(out).toContain("in the 1 column(s) present is canonical"); + expect(out).toContain("3 column(s) not in the database were not scanned"); + }); + + test("a database holding none of the columns fails as a wrong database, not a pass", async () => { + const root = await project(); + const file = join(root, "app.dbb"); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); + expect(code).toBe(1); + expect(out).toContain(`no field.uuid column found in file:${file} — wrong database?`); + expect(out).not.toContain("every stored field.uuid value"); + + const json = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root, undefined, "json")); + expect(json.code).toBe(1); + const payload = JSON.parse(json.stdout) as { errors: { gate: string; error: string }[] }; + expect(payload.errors).toContainEqual(expect.objectContaining({ gate: "uuid-values", error: expect.stringContaining("wrong database?") })); + }); + + test("a JSON null element of a uuid list is counted: the write check refuses it", async () => { + const root = await project(); + const file = join(root, "nulls.db"); + sqliteDb(file, [CANONICAL_A], [[CANONICAL_B, CANONICAL_A, JSON.stringify([CANONICAL_A, null]), null]]); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); + expect(code).toBe(1); + expect(out).toContain(`claims.witness_ids (Claim.witnessIds): 1 value(s) not a canonical uuid, e.g. "null"`); + }); + + test("a file inside wrangler's local D1 state warns that it is the LOCAL database", async () => { + const root = await project(); + const dir = join(root, ".wrangler", "state", "v3", "d1", "miniflare-D1DatabaseObject"); + await mkdir(dir, { recursive: true }); + const file = join(dir, "local.sqlite"); + sqliteDb(file, [CANONICAL_A], []); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); + expect(code).toBe(0); + expect(out).toContain("reads the LOCAL database, not the deployed one"); + expect(out).toContain("--uuid-values --dialect d1 --d1 --remote"); + }); + + test("value-object members stored as JSON are read: scalar, list, nested, and inside a list of value objects", async () => { + const root = await project(VO_MODEL); + const file = join(root, "vo.db"); + const db = new Database(file); + db.run("CREATE TABLE claims (id TEXT PRIMARY KEY, meta TEXT, history TEXT)"); + const insert = (id: string, meta: unknown, history: unknown): void => { + db.run("INSERT INTO claims (id, meta, history) VALUES (?, ?, ?)", [id, meta === undefined ? null : JSON.stringify(meta), history === undefined ? null : JSON.stringify(history)]); + }; + // Clean: canonical members, an absent member, a null member and an empty list. + insert(CANONICAL_A, { memberId: CANONICAL_B, tagIds: [CANONICAL_A], note: "mbr-note", owner: { ownerId: CANONICAL_A } }, [{ memberId: null, tagIds: [] }, {}]); + // Offending: one per member path. + insert(CANONICAL_B, { memberId: "mbr1", tagIds: [CANONICAL_A, "tag-2", null], owner: { ownerId: "own1" } }, [{ memberId: CANONICAL_A }, { memberId: "mbr9", tagIds: "not-a-list", owner: { ownerId: 7 } }]); + insert("00000000-0000-0000-0000-000000000002", undefined, undefined); + db.close(); + + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); + expect(code).toBe(1); + expect(out).toContain(`claims.meta $.memberId (Claim.meta.memberId): 1 value(s) not a canonical uuid, e.g. "mbr1"`); + expect(out).toContain(`claims.meta $.tagIds[*] (Claim.meta.tagIds): 2 value(s) not a canonical uuid, e.g. "null", "tag-2"`); + expect(out).toContain(`claims.meta $.owner.ownerId (Claim.meta.owner.ownerId): 1 value(s) not a canonical uuid, e.g. "own1"`); + expect(out).toContain(`claims.history $[*].memberId (Claim.history.memberId): 1 value(s) not a canonical uuid, e.g. "mbr9"`); + expect(out).toContain(`claims.history $[*].tagIds[*] (Claim.history.tagIds): 1 value(s) not a canonical uuid, e.g. "not-a-list"`); + expect(out).toContain(`claims.history $[*].owner.ownerId (Claim.history.owner.ownerId): 1 value(s) not a canonical uuid, e.g. "7"`); + expect(out).toContain("claims.id (Claim.id): every stored value is a canonical uuid"); + expect(out).toContain("7 stored value(s) in 6 column(s) are not canonical"); }); }); @@ -232,7 +362,8 @@ describe("meta verify --uuid-values — D1", () => { }); describe("meta verify --uuid-values — Postgres (env-gated: MIGRATE_TS_PG_URL)", () => { - test("a native uuid column is guaranteed and not read; a text column is scanned", async () => { + /** A fresh database, set up by `statements`, its URL passed to `run`; dropped afterwards. */ + async function withPgDatabase(statements: string[], run: (url: string) => Promise): Promise { const pgUrl = process.env.MIGRATE_TS_PG_URL; if (pgUrl === undefined || pgUrl.length === 0) return; const admin = new pg.Client({ connectionString: pgUrl }); @@ -245,23 +376,69 @@ describe("meta verify --uuid-values — Postgres (env-gated: MIGRATE_TS_PG_URL)" const c = new pg.Client({ connectionString: url.toString() }); await c.connect(); try { - // members.id native uuid; claims stored as text, as an older hand-made schema might. - await c.query("CREATE TABLE members (id uuid PRIMARY KEY, name text)"); - await c.query("CREATE TABLE claims (id uuid PRIMARY KEY, member_id text, witness_ids uuid[], legacy_ref uuid)"); - await c.query(`INSERT INTO members VALUES ('${CANONICAL_A}', 'x')`); - await c.query(`INSERT INTO claims VALUES ('${CANONICAL_B}', 'mbr1', ARRAY['${CANONICAL_A}']::uuid[], NULL)`); + for (const q of statements) await c.query(q); } finally { await c.end(); } + await run(url.toString()); + } finally { + await admin.query(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); + await admin.end(); + } + } + + test("a native uuid column is guaranteed and not read; a text column is scanned", async () => { + await withPgDatabase([ + // members.id native uuid; claims stored as text, as an older hand-made schema might. + "CREATE TABLE members (id uuid PRIMARY KEY, name text)", + "CREATE TABLE claims (id uuid PRIMARY KEY, member_id text, witness_ids uuid[], legacy_ref uuid)", + `INSERT INTO members VALUES ('${CANONICAL_A}', 'x')`, + `INSERT INTO claims VALUES ('${CANONICAL_B}', 'mbr1', ARRAY['${CANONICAL_A}']::uuid[], NULL)`, + ], async (url) => { const root = await project(); - const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", url.toString()], root)); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", url], root)); expect(code).toBe(1); expect(out).toContain("members.id (Member.id): native uuid column"); expect(out).toContain("claims.witness_ids (Claim.witnessIds): native uuid column"); expect(out).toContain(`claims.member_id (Claim.memberId): 1 value(s) not a canonical uuid, e.g. "mbr1"`); - } finally { - await admin.query(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); - await admin.end(); - } + }); + }); + + test("a jsonb uuid list counts a null element and a stored value that is not a list", async () => { + await withPgDatabase([ + "CREATE TABLE members (id uuid PRIMARY KEY, name text)", + "CREATE TABLE claims (id uuid PRIMARY KEY, member_id uuid, witness_ids jsonb, legacy_ref uuid)", + `INSERT INTO claims VALUES ('${CANONICAL_A}', NULL, '["${CANONICAL_B}", null, "w-1"]', NULL)`, + `INSERT INTO claims VALUES ('${CANONICAL_B}', NULL, '"solo"', NULL)`, + ], async (url) => { + const root = await project(); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", url], root)); + expect(code).toBe(1); + const line = out.split("\n").find((l) => l.includes("claims.witness_ids (Claim.witnessIds)")) ?? ""; + expect(line).toContain("3 value(s) not a canonical uuid"); + // The sample order follows the database's collation. + for (const sample of [`"null"`, `"w-1"`, `"\\"solo\\""`]) expect(line).toContain(sample); + }); + }); + + test("value-object members stored as jsonb are read: scalar, list, nested, and inside a list of value objects", async () => { + const meta = (v: unknown): string => `'${JSON.stringify(v)}'::jsonb`; + await withPgDatabase([ + "CREATE TABLE claims (id uuid PRIMARY KEY, meta jsonb, history jsonb)", + `INSERT INTO claims VALUES ('${CANONICAL_A}', ${meta({ memberId: CANONICAL_B, tagIds: [CANONICAL_A], owner: { ownerId: CANONICAL_A } })}, ${meta([{ memberId: null, tagIds: [] }, {}])})`, + `INSERT INTO claims VALUES ('${CANONICAL_B}', ${meta({ memberId: "mbr1", tagIds: [CANONICAL_A, "tag-2", null], owner: { ownerId: "own1" } })}, ${meta([{ memberId: CANONICAL_A }, { memberId: "mbr9", tagIds: "not-a-list", owner: { ownerId: 7 } }])})`, + `INSERT INTO claims VALUES ('00000000-0000-0000-0000-000000000002', NULL, NULL)`, + ], async (url) => { + const root = await project(VO_MODEL); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", url], root)); + expect(code).toBe(1); + expect(out).toContain(`claims.meta $.memberId (Claim.meta.memberId): 1 value(s) not a canonical uuid, e.g. "mbr1"`); + expect(out).toContain(`claims.meta $.tagIds[*] (Claim.meta.tagIds): 2 value(s) not a canonical uuid, e.g. "null", "tag-2"`); + expect(out).toContain(`claims.meta $.owner.ownerId (Claim.meta.owner.ownerId): 1 value(s) not a canonical uuid, e.g. "own1"`); + expect(out).toContain(`claims.history $[*].memberId (Claim.history.memberId): 1 value(s) not a canonical uuid, e.g. "mbr9"`); + expect(out).toContain(`claims.history $[*].tagIds[*] (Claim.history.tagIds): 1 value(s) not a canonical uuid, e.g. "\\"not-a-list\\""`); + expect(out).toContain(`claims.history $[*].owner.ownerId (Claim.history.owner.ownerId): 1 value(s) not a canonical uuid, e.g. "7"`); + expect(out).toContain("claims.id (Claim.id): native uuid column"); + }); }); }); From 2956dc2881561e0b36db0789061131aa672954d4 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 20:45:09 -0500 Subject: [PATCH 3/7] no-mistakes(review): Scan every uuid place from migrate's layout --- CHANGELOG.md | 36 +- docs/features/cli.md | 2 +- docs/features/migrations-and-drift.md | 64 +- .../packages/cli/src/commands/verify.ts | 35 +- server/typescript/packages/cli/src/index.ts | 22 +- .../packages/cli/src/lib/uuid-values-check.ts | 658 +++++++++--------- .../cli/test/__snapshots__/cli.test.ts.snap | 11 +- .../cli/test/verify-uuid-values.test.ts | 426 ++++++++++-- .../test/uuid-values-scan.test.ts | 233 +++++++ .../metadata/src/loader/validation-passes.ts | 2 +- .../migrate-ts/src/expected-schema.ts | 297 +++++--- .../packages/migrate-ts/src/index.ts | 2 +- 12 files changed, 1200 insertions(+), 588 deletions(-) create mode 100644 server/typescript/packages/integration-tests/test/uuid-values-scan.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index b9c80f69a1..e469fd03f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,19 +12,29 @@ here.** - **`meta verify --uuid-values` lists the stored uuids that 1.3.0's write check refuses.** It is a read-only check to run before upgrading. With `--db ` (SQLite, libSQL or Postgres), or with - `--dialect d1 [--d1 ] [--remote]`, it reads every `field.uuid` column (keys, foreign keys - and each element of an `isArray` list, where a JSON `null` element counts as not canonical) in the - tables `meta migrate` governs. It also reads each `field.uuid` member of a value object stored as - JSON, including nested value objects and lists of value objects, and names the member by its path - (`claims.meta $.memberId`). For each column or member holding values that are not canonical - 8-4-4-4-12 uuids, such as `"mbr1"` on SQLite or D1, it gives the count and up to five samples, and - it exits 1 when it finds any. A native Postgres `uuid` column is reported as guaranteed and is not - read. A database that holds none of the columns fails the check as a probable wrong database, and - a column missing from the database is named and counted as not scanned. The check never writes. - A `--db` file inside wrangler's local D1 state gets the same warning as the schema gate. With `--uuid-values`, - `--db` is used for this check only, not for the schema gate, and `--format json` carries the - findings in `uuidValues[]`. It is in the Node CLI only, like the other checks that read a live - database. See `docs/features/migrations-and-drift.md`, "`meta verify --uuid-values`". + `--dialect d1 [--d1 ] [--remote]`, it reads every place the model types `field.uuid`, in + every table the model stores rows in, `@unmanaged` tables and tables outside `migrate.scope` + included: keys, foreign keys, each element of an `isArray` list (a JSON `null` element counts as + not canonical), and inside a value object stored as JSON each `field.uuid` member, through nested + value objects, lists of value objects and the values of a `field.map` of value objects. A + flattened value object's members are read in their own columns, and a member that is itself an + object or a map is read inside its JSON column. Which column holds which field comes from the same + code `meta migrate` lays out its columns with, so a TPH subtype's flattened value object is read in + the one JSON column migrate gives it. Each place is named by its column and JSON path + (`claims.meta $.memberId`); for each one holding values that are not canonical 8-4-4-4-12 uuids, + such as `"mbr1"` on SQLite or D1, it gives the count and up to five samples, and it exits 1 when it + finds any. A native Postgres `uuid` or `uuid[]` column is reported as guaranteed and not read. + Every place ends as scanned, native, missing (the table or column is not in this database) or + unreadable (the read failed, the column type cannot hold the value, the stored text is not JSON, + or a value object contains itself), and the check passes only when every place was read: any + missing or unreadable place makes the run incomplete, names the place and its reason, and exits 1. + It does not read a `field.map @valueType: uuid` or an object with no `@objectRef` (the write check + does not check either as a uuid), or views. The SQLite and D1 queries stay inside D1's limits + (a GLOB pattern of 50 bytes, one JSON path per run of member keys). The check never writes. A + `--db` file inside wrangler's local D1 state gets the same warning as the schema gate. With + `--uuid-values`, `--db` is used for this check only, not for the schema gate, and `--format json` + carries one row per place in `uuidValues[]`. It is in the Node CLI only, like the other checks that + read a live database. See `docs/features/migrations-and-drift.md`, "`meta verify --uuid-values`". - **C# and Rust render dotted names, a list's `length` and `0` as TypeScript does.** C# resolves a dotted name whole against each context, innermost outward, so a context holding only the first segment no longer hides an outer match (`render-shadowed-dotted-prefix`). The Rust diff --git a/docs/features/cli.md b/docs/features/cli.md index a7aa5b852a..8258c73afc 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -56,7 +56,7 @@ vocabulary everywhere, each port implementing the modes it supports. | Subverb | What it checks | Touches a DB? | |---|---|---| | `verify --db` | **Schema drift** — does the live database (or snapshot) match the metadata? (migrate engine, ADR-0015) | yes | -| `verify --uuid-values` | **Stored uuid values** (since 1.3.1). This is a read-only check to run before upgrading. With `--db ` or `--dialect d1`, it reads every `field.uuid` column and lists the values that are not canonical 8-4-4-4-12 uuids, which the 1.3 write check refuses. It exits 1 when it finds any. With this flag, `--db` is used for this check only. **Node `meta` only.** See [`migrations-and-drift.md`](migrations-and-drift.md#meta-verify---uuid-values--stored-values-the-uuid-write-check-refuses). | yes (read-only) | +| `verify --uuid-values` | **Stored uuid values** (since 1.3.1). This is a read-only check to run before upgrading. With `--db ` or `--dialect d1`, it reads every place the model types `field.uuid` (columns, list elements, value-object members stored as JSON, map values and flattened members) in every table the model stores rows in, `@unmanaged` and out-of-scope tables included, and lists the values that are not canonical 8-4-4-4-12 uuids, which the 1.3 write check refuses. It exits 1 when it finds any, and also when any place could not be read (a missing table or column, a failed read): it passes only when every place was read. With this flag, `--db` is used for this check only. **Node `meta` only.** See [`migrations-and-drift.md`](migrations-and-drift.md#meta-verify---uuid-values--stored-values-the-uuid-write-check-refuses). | yes (read-only) | | `verify --codegen` | **Codegen drift** — regenerate from metadata in memory and fail if it differs from the committed generated output. Catches "metadata changed but `meta gen` wasn't re-run". **A hand-edited generated file** (Node `meta`): `meta gen` three-way-merges hand edits, so the gate compares the *generated contribution* against the committed `.gen-state/.hashes/` and reports each edited file separately, by path, with how to see the edit and how to drop it. What that report does to the exit code is the `verify.handEdits` key in `.metaobjects/config.json`: `"fail"` exits 1, `"notice"` (and a project without the key, as before 1.3) prints it and exits 0. `meta init` writes `"fail"` for a new project. `--allow-hand-edits` relaxes `fail` to a notice for one run; `--forbid-hand-edits` makes a hand edit fail for one run whatever the key says. The other ports compare the generated files byte for byte, so any edit is drift and fails: `dotnet meta verify --codegen`, `mvn metaobjects:verify` (Java and Kotlin) and `metaobjects verify --codegen` each exit non-zero and name the file. | no | | `verify --templates` | **Template/prompt drift** — `Renderer.verify` checks each `template.*` node's `{{field}}` references against its payload VO (FR-004). A Jinja body (Python and TypeScript, ADR-0061) is checked the same way. | no | | `verify --docs` | **Removed in 1.1.0** (ADR-0034 Amendment 9). It prints where the check went and exits 2: documentation is written by entries in `generators`, so `verify --codegen` checks it with the rest of the declared output. | — | diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index 0f89668017..e2cd6ec4b6 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -806,33 +806,53 @@ meta verify --uuid-values --dialect d1 [--d1 DB] [--remote] Since 1.3.0 the generated create and update models refuse a `field.uuid` value that is not the 8-4-4-4-12 hex shape, on every dialect. SQLite and D1 store a uuid as text and accepted any string, so a database may already hold ids such as `"mbr1"`: those rows still read, but no -client can write the value again. Run this check before upgrading. It reads every `field.uuid` -column (keys, foreign keys and `isArray` lists, each element checked) of the tables `meta migrate` -governs, and lists each column holding values that are not canonical, with the count and up to -five of them. A JSON `null` element of a list counts as not canonical, because the write check -refuses it. It exits 1 when it finds any and never writes. A native Postgres `uuid` (or `uuid[]`) -column is reported as guaranteed and not read, because the database cannot store anything else. -A `field.string` is not read, even one declared `@dbColumnType: uuid`, because no write check -applies to it. - -The write check also validates the members of a value object, so the check reads each -`field.uuid` member of a value object stored as JSON (any `field.object` that is not -`@storage: flattened`). That includes nested value objects and lists of value objects. Each -member is reported with its JSON path, for example `claims.meta $.memberId` or -`claims.history $[*].tagIds[*]`. An absent or `null` member is not counted. A flattened value -object's `field.uuid` members are their own columns and are read as columns. - -A column that is not in the database is named and not read, and the verdict says how many columns -were not scanned. When the database holds none of the columns, the check fails with "wrong -database?" instead of passing, because it read nothing. A `--db` file inside wrangler's local D1 -state (`.wrangler/state/**/d1/**`) is the local database, so the check warns and points to -`--uuid-values --dialect d1 --remote` for the deployed one. +client can write the value again. Run this check before upgrading. It never writes. + +It reads every place the model types `field.uuid`, in every table the model stores rows in. +That includes `@unmanaged` tables, tables outside `migrate.scope` and tables from an imported +package, because the write check applies to them and reading changes nothing. Which column holds +which field comes from the same code `meta migrate` lays out its columns with. Inside a column the +check follows the nesting the write check validates: + +- a `field.uuid` column (keys, foreign keys and every other uuid field); +- each element of an `isArray` list of uuids. A JSON `null` element counts as not canonical, and so + does a stored value that is not a list, because the write check refuses both; +- each `field.uuid` member of a value object stored as JSON (any `field.object` that is not + `@storage: flattened`), through nested value objects and lists of value objects; +- each value of a `field.map` of value objects; +- a flattened value object's members: a uuid member is its own column, and a member that is itself + an object or a map is read inside its JSON column. A flattened value object declared on a TPH + subtype is one JSON column, as migrate stores it. + +Each place is reported with its column and JSON path, for example `claims.meta $.memberId`, +`claims.history $[*].tagIds[*]` or `claims.by_region $.*.regionId`, with the count of values that +are not canonical and up to five of them. An absent or `null` member is not counted. A container of +the wrong type on the way down (a string where an object should be) holds no uuid and is not +counted. Not read: a `field.string`, even one declared `@dbColumnType: uuid`, a +`field.map @valueType: uuid` and a `field.object` with no `@objectRef` (the write check does not +check any of them as a uuid), and views (their rows live in a table already read). + +Every place ends in one status: + +| Status | Meaning | Counts as read | +|---|---|---| +| scanned | every stored value was read | yes | +| native | a Postgres `uuid` or `uuid[]` column: the database stores nothing else | yes | +| missing | the table or the column is not in this database | no | +| unreadable | the read failed, the column type cannot hold what the model says (a value object in a Postgres column that is not `json`/`jsonb`), the stored SQLite text is not JSON, or a value object contains itself | no | + +The check exits 1 when it finds a value that is not canonical. It passes only when every place was +read: a missing or unreadable place makes the run incomplete, exits 1 and is listed with its reason +(under `--format json`, in `errors[]`). A model whose tables live in more than one database is +therefore incomplete against each one, and says which tables it did not find. A `--db` file inside +wrangler's local D1 state (`.wrangler/state/**/d1/**`) is the local database, so the check warns and +points to `--uuid-values --dialect d1 --remote` for the deployed one. Fix what it lists in one of two ways. Either rewrite each value to a canonical uuid, along with every foreign key that points at it, or declare the field `field.string` if it never held uuids. With `--uuid-values`, the `--db` connection is used for this check only. Run `meta verify --db ` separately for schema drift. Under `--format json` the findings are in `uuidValues[]`, one row per -column. Only the Node CLI has this check, as it has the other checks that read a live database. +place, with its status and the reason for each place not read. Only the Node CLI has this check, as it has the other checks that read a live database. ## Generated-vs-runtime: Kotlin startup validator diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index 55979adbfe..19653360d7 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -157,7 +157,7 @@ import { import { describeLoadError, reportLoadError } from "../lib/load-error.js"; import { describeError } from "../lib/error-text.js"; import { - scanUuidColumns, uuidColumnsOf, UUID_SAMPLE_LIMIT, uuidValuesReport, type UuidColumn, type UuidColumnResult, type UuidScanDialect, + scanUuidPlaces, uuidPlacesOf, UUID_SAMPLE_LIMIT, uuidValuesReport, type UuidColumnResult, type UuidScanDialect, } from "../lib/uuid-values-check.js"; import { sql } from "kysely"; @@ -1700,31 +1700,29 @@ export async function verifyCommand( } // -- uuid values (pre-upgrade data check) ------------------------------------ - // Reads every `field.uuid` column of the --db / --dialect d1 database and reports the - // stored values the 1.3 write check refuses. Read-only; see lib/uuid-values-check.ts. + // Reads every place the model types `field.uuid` in the --db / --dialect d1 database and + // reports the stored values the 1.3 write check refuses. Read-only; see lib/uuid-values-check.ts. async function runUuidValuesVerify(): Promise { if (flags.dialect === "d1" && flags.db !== undefined) { log.error(`verify: --db is not used for dialect 'd1' — wrangler.toml owns the connection; pass --d1 instead`); return 2; } - let columns: UuidColumn[]; - let scanDialect: UuidScanDialect; - try { - scanDialect = flags.dialect !== "d1" && (flags.dialect ?? inferDialect(flags.db as string)) === "postgres" ? "postgres" : "sqlite"; - columns = uuidColumnsOf(root, schema, scanDialect, schemaScope); - } catch (err) { - if (isEnumLengthRefusal(err)) return refuseEnumLength(err); - if (isInvalidCheckNameError(err)) { log.error(`verify: ${err.message}`); return 1; } - log.error(`verify: ${describeError(err)}`); - return 1; - } + const scanDialect: UuidScanDialect = + flags.dialect !== "d1" && (flags.dialect ?? inferDialect(flags.db as string)) === "postgres" ? "postgres" : "sqlite"; + // Every table the model stores rows in: the write check applies to `@unmanaged` tables and + // tables outside migrate.scope too, and reading them changes nothing. + const places = uuidPlacesOf(root); let report: ReturnType; if (flags.dialect === "d1") { const d1 = await openD1(); if (typeof d1 === "number") return d1; + const query = async (q: string): Promise[]> => parseD1Rows(await d1.runner(q)); try { - uuidValueResults = await scanUuidColumns(columns, scanDialect, async (q) => parseD1Rows(await d1.runner(q))); + // A database that cannot be reached at all is a run error; anything later is recorded + // on the place it belongs to. + await query("SELECT 1 AS ok"); + uuidValueResults = await scanUuidPlaces(places, scanDialect, query); } catch (err) { uuidValuesRunError = `failed to read ${d1.displayUrl}: ${describeError(err)}`; log.error(`verify: ${uuidValuesRunError}`); @@ -1753,7 +1751,8 @@ export async function verifyCommand( const db = kysely.db; const query = async (q: string): Promise[]> => (await sql.raw>(q).execute(db)).rows; - uuidValueResults = await scanUuidColumns(columns, scanDialect, query); + await query("SELECT 1 AS ok"); + uuidValueResults = await scanUuidPlaces(places, scanDialect, query); report = uuidValuesReport(uuidValueResults, kysely.displayUrl); } catch (err) { uuidValuesRunError = `failed to read ${kysely.displayUrl}: ${describeError(err)}`; @@ -2482,7 +2481,7 @@ function buildVerifyPayload(input: { rulesCounts?: RulesSummary; /** What the schema gate found, when it compared anything. */ schemaDrift?: SchemaDriftSection; - /** What the uuid-values scan found, one row per field.uuid column, when it ran. */ + /** What the uuid-values scan found, one row per field.uuid place, when it ran. */ uuidValues?: readonly UuidColumnResult[]; /** Gates that could not run at all (an unreachable database) — failures, not drift. */ errors?: readonly { gate: string; error: string }[]; @@ -2535,7 +2534,7 @@ function buildVerifyPayload(input: { } if (drifted.some((g) => g.gate === "uuid-values") && input.uuidValues !== undefined) { help.push( - `the uuid-values scan's findings are in uuidValues[] — one row per field.uuid column, with the count of stored values that are not canonical uuids and up to ${UUID_SAMPLE_LIMIT} of them; rewrite them to canonical uuids or declare the field field.string`, + `the uuid-values scan's findings are in uuidValues[] — one row per field.uuid place, with its status, a reason for each place not read, the count of stored values that are not canonical uuids and up to ${UUID_SAMPLE_LIMIT} of them; rewrite them to canonical uuids or declare the field field.string`, ); } if (drifted.some((g) => g.gate !== "schema" && g.gate !== "uuid-values")) { diff --git a/server/typescript/packages/cli/src/index.ts b/server/typescript/packages/cli/src/index.ts index 46dc4b93d2..3a6e7ca7c0 100644 --- a/server/typescript/packages/cli/src/index.ts +++ b/server/typescript/packages/cli/src/index.ts @@ -128,11 +128,12 @@ VERIFY FLAGS (ADR-0021 D2 — explicit subverbs; combine any; exit 1 on ANY drif temp-object probe on the target. Also SHADOW_DATABASE_URL or migrate.shadowDatabaseUrl in .metaobjects/config.json. --uuid-values Pre-upgrade data check, read-only: with --db (or --dialect d1), - read every field.uuid column and list each one whose stored values - are not canonical 8-4-4-4-12 uuids, with a count and samples. Since - 1.3.0 a create or update carrying such a value is refused. Exits 1 - when any is found. A native Postgres uuid column is not read (the - type already guarantees it). With this flag --db serves the scan + read every place the model types field.uuid (in every table, value + objects stored as JSON included) and list each one whose stored + values are not canonical 8-4-4-4-12 uuids, with a count and samples. + Since 1.3.0 a create or update carrying such a value is refused. + Exits 1 when any is found, or when a place could not be read. A + native Postgres uuid column is not read (the type guarantees it). With this flag --db serves the scan only; run 'meta verify --db ' for schema drift. --prompts Directory of provider-resolved template text (default: prompts) --dialect sqlite|postgres|d1 Optional override (auto-detected from --db URL scheme) @@ -394,11 +395,12 @@ FLAGS: project adopted with 'migrate baseline --from-db' (its chain does not build the schema); use --replay there. --uuid-values Pre-upgrade data check, read-only: with --db (or --dialect d1), - read every field.uuid column and list each one whose stored values - are not canonical 8-4-4-4-12 uuids, with a count and samples. Since - 1.3.0 a create or update carrying such a value is refused. Exits 1 - when any is found. A native Postgres uuid column is not read (the - type already guarantees it). With this flag --db serves the scan + read every place the model types field.uuid (in every table, value + objects stored as JSON included) and list each one whose stored + values are not canonical 8-4-4-4-12 uuids, with a count and samples. + Since 1.3.0 a create or update carrying such a value is refused. + Exits 1 when any is found, or when a place could not be read. A + native Postgres uuid column is not read (the type guarantees it). With this flag --db serves the scan only; run 'meta verify --db ' for schema drift. --prompts Directory of provider-resolved template text (default: prompts) --dialect sqlite|postgres|d1 Optional override (auto-detected from --db URL scheme) diff --git a/server/typescript/packages/cli/src/lib/uuid-values-check.ts b/server/typescript/packages/cli/src/lib/uuid-values-check.ts index 90f01ee77b..068d356e6d 100644 --- a/server/typescript/packages/cli/src/lib/uuid-values-check.ts +++ b/server/typescript/packages/cli/src/lib/uuid-values-check.ts @@ -1,36 +1,33 @@ -// `meta verify --uuid-values` — a read-only scan of the values already stored in every -// `field.uuid` column. +// `meta verify --uuid-values` — a read-only scan of the values already stored wherever the model +// types a value `field.uuid`. // -// 1.3.0 made the generated create and update schemas refuse a `field.uuid` value that is -// not the 8-4-4-4-12 hex shape, on every dialect. Postgres stores a uuid in a native -// `uuid` column, which could never hold anything else; SQLite and D1 store it as text and -// accepted any string. A project whose rows carry ids such as `"mbr1"` still reads them -// after the upgrade, but no client can write those values again. This scan finds them -// BEFORE the upgrade: per column, how many stored values are not canonical and a few of -// them. It never writes. +// 1.3.0 made the generated create and update schemas refuse a `field.uuid` value that is not the +// 8-4-4-4-12 hex shape, on every dialect. Postgres stores a uuid in a native `uuid` column, which +// could never hold anything else; SQLite and D1 store it as text and accepted any string. A +// project whose rows carry ids such as `"mbr1"` still reads them after the upgrade, but no client +// can write those values again. This scan finds them BEFORE the upgrade: per place, how many +// stored values are not canonical and a few of them. It never writes. // -// The columns come from the schema builder `meta migrate` and `verify --db` use, so a -// table and column are named exactly as the database names them; the fields come from the -// loaded metadata, so only a `field.uuid` is checked (a `field.string @dbColumnType: uuid` -// has no write check to fall foul of). A `field.uuid` member of a value object stored as JSON -// is read inside its column, because the write check validates the value object's members too. +// What to read is one enumeration. The tables and columns come from `storedTablesOf`, the layout +// `meta migrate` builds its columns from, so the scan and the schema cannot disagree about which +// column holds a field. Every table the model stores rows in is read: `@unmanaged` tables and +// tables outside `migrate.scope` included, because the write check applies to them and reading +// changes nothing. Inside a column, the walk follows the nesting the write schema validates: a +// uuid, a list of uuids, a value object's members, a list of value objects, a map of value objects. +// +// Every place ends in one status, and the run claims all-clear only when every place was read. import { FIELD_ATTR_OBJECT_REF, - FIELD_ATTR_STORAGE, + FIELD_SUBTYPE_MAP, FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_UUID, - OBJECT_ATTR_DISCRIMINATOR, - STORAGE_FLATTENED, - TYPE_OBJECT, isMetaObject, - physicalNamingOf, refTarget, - resolveColumnName, - resolveFlattenedColumnName, type MetaData, + type MetaField, } from "@metaobjectsdev/metadata"; -import { buildExpectedSchemaWithProvenance, qualifiedDbName, type SchemaBuildSettings } from "@metaobjectsdev/migrate-ts"; +import { storedTablesOf } from "@metaobjectsdev/migrate-ts"; /** The canonical shape the 1.3 write check accepts: 8-4-4-4-12 hex digits, either case. */ export const CANONICAL_UUID_PATTERN = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"; @@ -38,40 +35,44 @@ export const CANONICAL_UUID_PATTERN = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F /** How many distinct offending values a finding quotes. */ export const UUID_SAMPLE_LIMIT = 5; -/** One step into a JSON-stored value object: the member's key, and whether it holds a list. */ -export interface UuidJsonStep { - key: string; - isArray: boolean; -} +/** One step from a column's stored value down to a uuid inside it. */ +export type UuidStep = + | { kind: "member"; key: string } // a value object's member + | { kind: "elements" } // each element of a JSON list + | { kind: "values" }; // each value of a JSON map (field.map) -/** One physical column that holds a `field.uuid` (a key, a foreign key or any other uuid field). */ -export interface UuidColumn { +/** A position in stored data that the model types as `field.uuid`. */ +export interface UuidPlace { schema?: string; table: string; column: string; - /** - * The column's stored value is a list: of uuids (`field.uuid @isArray`, each element checked), - * or of value objects when `members` is not empty. - */ - isArray: boolean; - /** - * The path to a `field.uuid` member inside a value object stored as JSON in this column, outermost - * first; empty when the column stores the uuid itself. - */ - members: UuidJsonStep[]; - /** Every field stored at this place, as `Object.field` (a TPH table can fold several). */ - fields: string[]; + /** Empty: the column stores the uuid itself. Otherwise the walk into the column's JSON. */ + steps: UuidStep[]; + /** `Object.field[.member…]`, as the model names it. */ + label: string; + /** The table's source is `@unmanaged`: reported, never a reason to skip. */ + unmanaged: boolean; + /** Set when the walk stopped early: a value object that contains itself. */ + truncated?: string; } -/** What the scan found in one column. */ +/** What the scan found at one place. */ export interface UuidColumnResult { table: string; column: string; - /** Where inside the column's JSON the uuid member is read, such as `$[*].memberId`. */ + /** Where inside the column's JSON the uuid is read, such as `$[*].memberId`. */ jsonPath?: string; + /** The field stored at this place, as `Object.field[.member…]`. */ fields: string[]; - /** `native`: the database column type guarantees canonical values, so it was not read. */ - status: "scanned" | "native" | "missing"; + unmanaged: boolean; + /** + * `scanned`: every stored value was read. `native`: a Postgres `uuid` / `uuid[]` column, whose + * type guarantees the shape. `missing`: the table or column is not in this database. + * `unreadable`: the read failed, or the value cannot be reached. Only the first two count as read. + */ + status: "scanned" | "native" | "missing" | "unreadable"; + /** Why, for `missing` and `unreadable`. */ + reason?: string; nonCanonical: number; samples: string[]; } @@ -82,309 +83,291 @@ export type RowQuery = (sql: string) => Promise[]>; /** The SQL family the scan speaks: Postgres, or SQLite (which D1 is). */ export type UuidScanDialect = "postgres" | "sqlite"; -/** - * Every governed table column that stores a `field.uuid`. `inScope` is the `migrate.scope` - * predicate `verify --db` honours, so the scan reads the tables `meta migrate` owns and no - * others. The schema is built for the dialect the scan reads, because the build refuses some - * models on Postgres only (a CHECK name over 63 bytes, two CHECKs sharing one name). - */ -export function uuidColumnsOf( - root: MetaData, - settings: SchemaBuildSettings, - dialect: UuidScanDialect, - inScope?: (fqn: string) => boolean, -): UuidColumn[] { - const built = buildExpectedSchemaWithProvenance(root, { ...settings, dialect }); - const strategy = physicalNamingOf(root).columns; - - // The table each table-owning object writes, keyed by its resolution key. - const tableOf = new Map }>(); - for (const t of built.snapshot.tables) { - const owner = built.provenance.get(qualifiedDbName(t)); - if (owner === undefined) continue; - if (inScope !== undefined && !inScope(owner)) continue; - tableOf.set(owner, { - ...(t.schema !== undefined ? { schema: t.schema } : {}), - table: t.name, - columns: new Set(t.columns.map((c) => c.name)), - }); - } - - const found = new Map(); - const add = ( - target: { schema?: string; table: string; columns: Set }, - column: string, - isArray: boolean, - label: string, - members: UuidJsonStep[], - ): void => { - // A column the schema builder does not emit (a derived field, a name this walk got - // wrong) is not read: only what `meta migrate` creates is scanned. - if (!target.columns.has(column)) return; - const key = `${target.schema ?? ""}\u0000${target.table}\u0000${column}\u0000${jsonPathOf(isArray, members) ?? ""}`; - const existing = found.get(key); - if (existing !== undefined) { - if (!existing.fields.includes(label)) existing.fields.push(label); - return; - } - found.set(key, { - ...(target.schema !== undefined ? { schema: target.schema } : {}), - table: target.table, - column, - isArray, - members, - fields: [label], - }); - }; - - // A value object stored as JSON: each `field.uuid` member, and the members of a nested value - // object, which the JSON holds inline. `seen` stops a value object that contains itself. - const addJsonMembers = ( - target: { schema?: string; table: string; columns: Set }, - column: string, - isArray: boolean, - vo: MetaData, - steps: UuidJsonStep[], - label: string, - seen: ReadonlySet, - ): void => { - if (!isMetaObject(vo)) return; - for (const member of vo.fields()) { - if (member.isDerived()) continue; - const path = [...steps, { key: member.name, isArray: member.resolvedIsArray() }]; - const memberLabel = `${label}.${member.name}`; - if (member.subType === FIELD_SUBTYPE_UUID) { - add(target, column, isArray, memberLabel, path); - } else if (member.subType === FIELD_SUBTYPE_OBJECT) { - const inner = refTarget(member, FIELD_ATTR_OBJECT_REF); - if (inner === undefined || seen.has(inner)) continue; - addJsonMembers(target, column, isArray, inner, path, memberLabel, new Set([...seen, inner])); - } - } - }; - - // ADR-0039: effective children of the root and effective fields of each object, so a - // field inherited through `extends` is found where its table stores it. - for (const obj of root.children()) { - if (obj.type !== TYPE_OBJECT || !isMetaObject(obj) || obj.isAbstract) continue; - const target = tableOf.get(obj.resolutionKey()) ?? tableOf.get(tphBaseKey(obj) ?? ""); - if (target === undefined) continue; - for (const field of obj.fields()) { - if (field.isDerived()) continue; - const label = `${obj.name}.${field.name}`; +/** Every place the model types as `field.uuid`, in every table the model stores rows in. */ +export function uuidPlacesOf(root: MetaData): UuidPlace[] { + const places: UuidPlace[] = []; + for (const t of storedTablesOf(root)) { + const at = (column: string, steps: UuidStep[], label: string, truncated?: string): void => { + places.push({ + ...(t.schema !== undefined ? { schema: t.schema } : {}), + table: t.table, + column, + steps, + label, + unmanaged: t.unmanaged, + ...(truncated !== undefined ? { truncated } : {}), + }); + }; + const visit = (field: MetaField, column: string, steps: UuidStep[], label: string, seen: ReadonlySet): void => { + const list: UuidStep[] = field.resolvedIsArray() ? [{ kind: "elements" }] : []; if (field.subType === FIELD_SUBTYPE_UUID) { - add(target, resolveColumnName(field, strategy), field.resolvedIsArray(), label, []); - } else if (field.subType === FIELD_SUBTYPE_OBJECT) { - const vo = refTarget(field, FIELD_ATTR_OBJECT_REF); - if (vo === undefined || !isMetaObject(vo)) continue; - // ADR-0039: resolving — @storage may be inherited via extends. - if (field.attr(FIELD_ATTR_STORAGE) === STORAGE_FLATTENED) { - for (const member of vo.fields()) { - if (member.subType !== FIELD_SUBTYPE_UUID) continue; - add(target, resolveFlattenedColumnName(field, member, strategy), member.resolvedIsArray(), `${label}.${member.name}`, []); - } - } else { - // Any other storage keeps the whole value object in one JSON column. - addJsonMembers(target, resolveColumnName(field, strategy), field.resolvedIsArray(), vo, [], label, new Set([vo])); - } + at(column, [...steps, ...list], label); + return; } - } + const isObject = field.subType === FIELD_SUBTYPE_OBJECT; + if (!isObject && field.subType !== FIELD_SUBTYPE_MAP) return; + // ADR-0039: resolving — @objectRef may be inherited via extends. + const vo = refTarget(field, FIELD_ATTR_OBJECT_REF); + // No value object: an open JSON bag or a map of scalars holds no position typed field.uuid. + if (vo === undefined || !isMetaObject(vo)) return; + const inner: UuidStep[] = isObject ? [...steps, ...list] : [...steps, { kind: "values" }]; + if (seen.has(vo)) { + at(column, inner, label, `value object ${vo.name} contains itself; read to this depth only`); + return; + } + const deeper = new Set([...seen, vo]); + for (const member of vo.fields()) { + visit(member, column, [...inner, { kind: "member", key: member.name }], `${label}.${member.name}`, deeper); + } + }; + for (const f of t.fields) visit(f.field, f.column, [], f.label, new Set()); } - const sortKey = (c: UuidColumn): string => `${c.schema ?? ""}.${c.table}.${c.column}${jsonPathOf(c.isArray, c.members) ?? ""}`; - return [...found.values()].sort((a, b) => sortKey(a).localeCompare(sortKey(b))); -} - -/** A member path as a JSON path (`$[*].memberId`), or undefined for a column storing the uuid itself. */ -function jsonPathOf(isArray: boolean, members: readonly UuidJsonStep[]): string | undefined { - if (members.length === 0) return undefined; - return `$${isArray ? "[*]" : ""}${members.map((m) => `.${m.key}${m.isArray ? "[*]" : ""}`).join("")}`; -} - -/** - * The walk from a column to the uuid values a member path names: each `each` opens a list, - * each `key` reads a member. The last step's list, if any, is left to the caller, which also - * reports a value that should be a list and is not. - */ -type JsonOp = { op: "each" } | { op: "key"; key: string }; - -function jsonOps(col: UuidColumn): { ops: JsonOp[]; leafIsArray: boolean } { - const ops: JsonOp[] = col.isArray ? [{ op: "each" }] : []; - col.members.forEach((m, i) => { - ops.push({ op: "key", key: m.key }); - if (m.isArray && i < col.members.length - 1) ops.push({ op: "each" }); - }); - return { ops, leafIsArray: col.members.at(-1)?.isArray ?? false }; + return places; } -/** The resolution key of the TPH discriminator base whose table `obj`'s rows live in. */ -function tphBaseKey(obj: MetaData): string | undefined { - let a = obj.superResolved; - while (a !== undefined) { - // ADR-0039 category 3: a super-resolution walk reads each ancestor's OWN @discriminator. - if (a.ownAttr(OBJECT_ATTR_DISCRIMINATOR) !== undefined) return a.resolutionKey(); - a = a.superResolved; - } - return undefined; +/** `$.meta[*].ownerId` — how a finding names a position inside a JSON column. */ +function jsonPathOf(steps: readonly UuidStep[]): string | undefined { + if (steps.length === 0) return undefined; + return `$${steps.map((s) => (s.kind === "member" ? `.${s.key}` : s.kind === "elements" ? "[*]" : ".*")).join("")}`; } const ident = (name: string): string => `"${name.replaceAll(`"`, `""`)}"`; const literal = (value: string): string => `'${value.replaceAll("'", "''")}'`; -/** SQLite has no regular expressions by default; GLOB with one class per digit is exact. */ -const SQLITE_UUID_GLOB = [8, 4, 4, 4, 12].map((n) => "[0-9a-fA-F]".repeat(n)).join("-"); - -/** Scan every column; reads only, and never more than a count and a few samples per column. */ -export async function scanUuidColumns( - columns: readonly UuidColumn[], - dialect: UuidScanDialect, - query: RowQuery, -): Promise { - const results: UuidColumnResult[] = []; - for (const col of columns) { - results.push(dialect === "postgres" ? await scanPostgres(col, query) : await scanSqlite(col, query)); - } - return results; -} - -function resultBase(col: UuidColumn): Pick { - const jsonPath = jsonPathOf(col.isArray, col.members); - return { table: col.table, column: col.column, ...(jsonPath !== undefined ? { jsonPath } : {}), fields: col.fields }; +/** + * The canonical shape on SQLite, which has no regular expressions. D1 refuses a LIKE/GLOB pattern + * over 50 bytes, so the shape is spelled out: 36 bytes, dashes at 9/14/19/24 and nowhere else, + * every other byte a hex digit. The one pattern is 18 bytes. + */ +function sqliteIsCanonical(v: string, type: string): string { + return `(${type} = 'text' AND length(CAST(${v} AS BLOB)) = 36 AND substr(${v}, 9, 1) = '-' AND substr(${v}, 14, 1) = '-' ` + + `AND substr(${v}, 19, 1) = '-' AND substr(${v}, 24, 1) = '-' AND length(replace(${v}, '-', '')) = 32 ` + + `AND ${v} NOT GLOB '*[^0-9a-fA-F-]*')`; } -async function scanSqlite(col: UuidColumn, query: RowQuery): Promise { - const table = ident(col.table); - const column = `${table}.${ident(col.column)}`; - const base = resultBase(col); - const exists = await query(`SELECT 1 AS ok FROM pragma_table_info(${literal(col.table)}) WHERE name = ${literal(col.column)}`); - if (exists.length === 0) return { ...base, status: "missing", nonCanonical: 0, samples: [] }; - - const notCanonical = (v: string, type: string): string => - `(${type} <> 'text' OR ${v} NOT GLOB ${literal(SQLITE_UUID_GLOB)})`; - let offenders: string; - if (col.members.length > 0) { - offenders = sqliteMemberOffenders(col, table, column, notCanonical); - } else if (col.isArray) { - // An array column holds JSON text: each element of a well-formed array (a JSON null - // element included, which the write check refuses), and the whole stored value when it - // is not a JSON array at all. - offenders = [ - `SELECT COALESCE(CAST(j.value AS TEXT), 'null') AS v FROM ${table}, json_each(${column}) AS j ` + - `WHERE json_valid(${column}) AND json_type(${column}) = 'array' AND ${notCanonical("j.value", "j.type")}`, - `SELECT CAST(${column} AS TEXT) AS v FROM ${table} ` + - `WHERE ${column} IS NOT NULL AND (NOT json_valid(${column}) OR json_type(${column}) <> 'array')`, - ].join(" UNION ALL "); - } else { - offenders = `SELECT CAST(${column} AS TEXT) AS v FROM ${table} WHERE ${column} IS NOT NULL AND ${notCanonical(column, `typeof(${column})`)}`; +/** One row per stored value at the place that is not a canonical uuid, on SQLite or D1. */ +function sqliteOffenders(place: UuidPlace): string { + const table = ident(place.table); + const column = `${table}.${ident(place.column)}`; + if (place.steps.length === 0) { + return `SELECT CAST(${column} AS TEXT) AS v FROM ${table} WHERE ${column} IS NOT NULL AND NOT ${sqliteIsCanonical(column, `typeof(${column})`)}`; } - return { ...base, status: "scanned", ...(await countAndSample(offenders, query)) }; -} - -/** - * The uuid member a path names inside a JSON-stored value object, on SQLite. A stored value - * that is not valid JSON, or not shaped as the path expects on the way down, holds no member to - * read; an absent or null member is not a value the write check sees as a uuid. - */ -function sqliteMemberOffenders( - col: UuidColumn, - table: string, - column: string, - notCanonical: (v: string, type: string) => string, -): string { + // The column holds JSON text. `doc` is the JSON value the walk stands in (NULL when there is + // none to read), `path` the run of member keys not yet applied to it: one json_* call per run, + // so the SQL grows linearly with depth (D1 refuses a statement over 100 KB). const from = [table]; - let v = `(CASE WHEN json_valid(${column}) THEN ${column} END)`; - let t = `json_type(${v})`; - const each = (): void => { + let doc = `CASE WHEN json_valid(${column}) THEN ${column} END`; + let path = "$"; + const each = (want: "array" | "object"): string => { const alias = `j${from.length}`; - from.push(`json_each(CASE WHEN ${t} = 'array' THEN ${v} ELSE '[]' END) AS ${alias}`); - v = `${alias}.value`; - t = `${alias}.type`; + from.push(`json_each(CASE WHEN json_type(${doc}, ${literal(path)}) = '${want}' THEN ${doc} END, ${literal(path)}) AS ${alias}`); + doc = `CASE WHEN ${alias}.type IN ('object', 'array') THEN ${alias}.value END`; + path = "$"; + return alias; }; - const { ops, leafIsArray } = jsonOps(col); - for (const step of ops) { - if (step.op === "each") { - each(); - } else { - const obj = `(CASE WHEN ${t} = 'object' THEN ${v} END)`; - const path = literal(`$.${JSON.stringify(step.key)}`); - v = `json_extract(${obj}, ${path})`; - t = `json_type(${obj}, ${path})`; - } + const steps = [...place.steps]; + const leafList = steps.at(-1)?.kind === "elements"; + if (leafList) steps.pop(); + for (const s of steps) { + if (s.kind === "member") path += `.${JSON.stringify(s.key)}`; + else each(s.kind === "elements" ? "array" : "object"); } - if (!leafIsArray) { - return `SELECT CAST(${v} AS TEXT) AS v FROM ${from.join(", ")} WHERE ${t} <> 'null' AND ${notCanonical(v, t)}`; + if (!leafList) { + // A uuid member: absent or JSON null is not a value; anything else must be canonical. + const v = `json_extract(${doc}, ${literal(path)})`; + const t = `json_type(${doc}, ${literal(path)})`; + return `SELECT CAST(${v} AS TEXT) AS v FROM ${from.join(", ")} WHERE ${t} <> 'null' AND NOT ${sqliteIsCanonical(v, t)}`; } - const notAList = `SELECT CAST(${v} AS TEXT) AS v FROM ${from.join(", ")} WHERE ${t} NOT IN ('array', 'null')`; - each(); - return `SELECT COALESCE(CAST(${v} AS TEXT), 'null') AS v FROM ${from.join(", ")} WHERE ${notCanonical(v, t)} UNION ALL ${notAList}`; + // A uuid list: a stored value that is not a list at all, then each element (a JSON null too). + const atRoot = from.length === 1 && path === "$"; + const notAList = atRoot + ? `SELECT CAST(${column} AS TEXT) AS v FROM ${table} WHERE ${column} IS NOT NULL AND CASE WHEN json_valid(${column}) THEN json_type(${column}) NOT IN ('array', 'null') ELSE 1 END` + : `SELECT CAST(json_extract(${doc}, ${literal(path)}) AS TEXT) AS v FROM ${from.join(", ")} WHERE json_type(${doc}, ${literal(path)}) NOT IN ('array', 'null')`; + const e = each("array"); + return `SELECT COALESCE(CAST(${e}.value AS TEXT), 'null') AS v FROM ${from.join(", ")} WHERE NOT ${sqliteIsCanonical(`${e}.value`, `${e}.type`)} UNION ALL ${notAList}`; } -async function scanPostgres(col: UuidColumn, query: RowQuery): Promise { - const base = resultBase(col); - const schema = col.schema !== undefined ? literal(col.schema) : "current_schema()"; - const typeRows = await query( - `SELECT udt_name FROM information_schema.columns WHERE table_schema = ${schema} ` + - `AND table_name = ${literal(col.table)} AND column_name = ${literal(col.column)}`, - ); - if (typeRows.length === 0) return { ...base, status: "missing", nonCanonical: 0, samples: [] }; - const udt = String(typeRows[0]?.udt_name ?? ""); - // A native uuid (or uuid[]) column holds nothing else: the database already guarantees it. - if (col.members.length === 0 && (udt === "uuid" || udt === "_uuid")) { - return { ...base, status: "native", nonCanonical: 0, samples: [] }; - } +/** Rows whose stored text is not JSON at all: the uuids inside could not be read. */ +function sqliteUnparsable(table: string, column: string): string { + const t = ident(table); + const c = `${t}.${ident(column)}`; + return `SELECT CAST(${c} AS TEXT) AS v FROM ${t} WHERE ${c} IS NOT NULL AND NOT json_valid(${c})`; +} - const table = col.schema !== undefined ? `${ident(col.schema)}.${ident(col.table)}` : ident(col.table); - const column = `t.${ident(col.column)}`; +/** How Postgres stores the place: decided from the column's real type, never from the model. */ +type PgPlan = { native: true } | { sql: string } | { unreadable: string }; + +function postgresPlan(place: UuidPlace, typname: string): PgPlan { + const table = place.schema !== undefined ? `${ident(place.schema)}.${ident(place.table)}` : ident(place.table); + const column = `t.${ident(place.column)}`; const pattern = literal(CANONICAL_UUID_PATTERN); - let offenders: string; - if (col.members.length > 0 || (col.isArray && (udt === "jsonb" || udt === "json"))) { - offenders = postgresJsonOffenders(col, `${table} AS t`, `${column}::jsonb`, pattern); - } else if (col.isArray && udt.startsWith("_")) { + if (place.steps.length === 0) { + // A native uuid column holds nothing else. + if (typname === "uuid") return { native: true }; + return { sql: `SELECT ${column}::text AS v FROM ${table} AS t WHERE ${column} IS NOT NULL AND ${column}::text !~ ${pattern}` }; + } + const rootList = place.steps.length === 1 && place.steps[0]?.kind === "elements"; + if (rootList && typname === "_uuid") return { native: true }; + if (rootList && typname.startsWith("_")) { // A null element counts: the write check refuses it. - offenders = `SELECT COALESCE(e.v::text, 'null') AS v FROM ${table} AS t, unnest(${column}) AS e(v) WHERE e.v IS NULL OR e.v::text !~ ${pattern}`; - } else { - offenders = `SELECT ${column}::text AS v FROM ${table} AS t WHERE ${column} IS NOT NULL AND ${column}::text !~ ${pattern}`; + return { sql: `SELECT COALESCE(e.v::text, 'null') AS v FROM ${table} AS t CROSS JOIN LATERAL unnest(${column}) AS e(v) WHERE e.v IS NULL OR e.v::text !~ ${pattern}` }; + } + if (typname !== "jsonb" && typname !== "json") { + return { unreadable: `column type ${typname} is not json or jsonb: the value inside it cannot be read` }; } - return { ...base, status: "scanned", ...(await countAndSample(offenders, query)) }; -} - -/** - * The uuid values a JSON column holds, on Postgres: a list column's elements, or the member a - * path names inside a value object. A JSON null element of a uuid list counts (the write check - * refuses it), and so does a stored value that should be a list and is not; an absent or null - * member does not. - */ -function postgresJsonOffenders(col: UuidColumn, from: string, start: string, pattern: string): string { const joins: string[] = []; - let v = start; - const each = (): void => { + let v = `${column}::jsonb`; + const each = (want: "array" | "object"): void => { const alias = `e${joins.length}`; - joins.push(`CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(${v}) = 'array' THEN ${v} ELSE '[]'::jsonb END) AS ${alias}(v)`); + joins.push(want === "array" + ? `CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(${v}) = 'array' THEN ${v} ELSE '[]'::jsonb END) AS ${alias}(v)` + : `CROSS JOIN LATERAL jsonb_each(CASE WHEN jsonb_typeof(${v}) = 'object' THEN ${v} ELSE '{}'::jsonb END) AS ${alias}(k, v)`); v = `${alias}.v`; }; - const { ops, leafIsArray } = col.members.length === 0 ? { ops: [], leafIsArray: true } : jsonOps(col); - for (const step of ops) { - if (step.op === "each") each(); - else v = `(${v} -> ${literal(step.key)})`; + const steps = [...place.steps]; + const leafList = steps.at(-1)?.kind === "elements"; + if (leafList) steps.pop(); + for (const s of steps) { + if (s.kind === "member") v = `(${v} -> ${literal(s.key)})`; + else each(s.kind === "elements" ? "array" : "object"); } - const source = (): string => [from, ...joins].join(" "); + const source = (): string => [`${table} AS t`, ...joins].join(" "); const offending = (x: string): string => `(jsonb_typeof(${x}) <> 'string' OR ${x} #>> '{}' !~ ${pattern})`; - if (!leafIsArray) { - return `SELECT ${v} #>> '{}' AS v FROM ${source()} WHERE jsonb_typeof(${v}) <> 'null' AND ${offending(v)}`; + if (!leafList) { + return { sql: `SELECT ${v} #>> '{}' AS v FROM ${source()} WHERE jsonb_typeof(${v}) <> 'null' AND ${offending(v)}` }; } const notAList = `SELECT ${v}::text AS v FROM ${source()} WHERE jsonb_typeof(${v}) NOT IN ('array', 'null')`; - each(); - return `SELECT COALESCE(${v} #>> '{}', 'null') AS v FROM ${source()} WHERE ${offending(v)} UNION ALL ${notAList}`; + each("array"); + return { sql: `SELECT COALESCE(${v} #>> '{}', 'null') AS v FROM ${source()} WHERE ${offending(v)} UNION ALL ${notAList}` }; } -async function countAndSample( - offenders: string, +const message = (err: unknown): string => (err instanceof Error ? err.message : String(err)); + +/** + * Scan every place; reads only, and never more than a count and a few samples per place. A + * failure is recorded on the place it belongs to, never thrown. + */ +export async function scanUuidPlaces( + places: readonly UuidPlace[], + dialect: UuidScanDialect, query: RowQuery, -): Promise<{ nonCanonical: number; samples: string[] }> { - const countRows = await query(`SELECT COUNT(*) AS n FROM (${offenders}) AS o`); - const nonCanonical = Number(countRows[0]?.n ?? 0); - if (nonCanonical === 0) return { nonCanonical, samples: [] }; - const sampleRows = await query(`SELECT DISTINCT o.v AS v FROM (${offenders}) AS o ORDER BY o.v LIMIT ${UUID_SAMPLE_LIMIT}`); - return { nonCanonical, samples: sampleRows.map((r) => String(r.v)) }; +): Promise { + // One catalog read per table: which columns exist, and their types. + const catalogs = new Map | { error: string }>(); + const catalogOf = async (p: UuidPlace): Promise | { error: string }> => { + const key = `${p.schema ?? ""}\u0000${p.table}`; + let cat = catalogs.get(key); + if (cat === undefined) { + try { + const rows = dialect === "sqlite" + ? await query(`SELECT name AS column_name, type AS type_name FROM pragma_table_info(${literal(p.table)})`) + // pg_catalog, not information_schema: the latter hides a table the role cannot read, + // which would report a permission problem as a missing table. + : await query( + `SELECT a.attname AS column_name, ty.typname AS type_name FROM pg_catalog.pg_attribute a ` + + `JOIN pg_catalog.pg_class c ON c.oid = a.attrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace ` + + `JOIN pg_catalog.pg_type ty ON ty.oid = a.atttypid ` + + `WHERE n.nspname = ${p.schema !== undefined ? literal(p.schema) : "current_schema()"} AND c.relname = ${literal(p.table)} ` + + `AND a.attnum > 0 AND NOT a.attisdropped`, + ); + cat = new Map(rows.map((r) => [String(r.column_name), String(r.type_name)])); + } catch (err) { + cat = { error: message(err) }; + } + catalogs.set(key, cat); + } + return cat; + }; + const countAndSample = async (offenders: string): Promise<{ nonCanonical: number; samples: string[] }> => { + const nonCanonical = Number((await query(`SELECT COUNT(*) AS n FROM (${offenders}) AS o`))[0]?.n ?? 0); + if (nonCanonical === 0) return { nonCanonical, samples: [] }; + const rows = await query(`SELECT DISTINCT o.v AS v FROM (${offenders}) AS o ORDER BY o.v LIMIT ${UUID_SAMPLE_LIMIT}`); + return { nonCanonical, samples: rows.map((r) => String(r.v)) }; + }; + + const results: UuidColumnResult[] = []; + // SQLite: a JSON column is checked once for text that is not JSON, whatever it holds. + const parsedColumns = new Set(); + for (const p of places) { + const jsonPath = jsonPathOf(p.steps); + const base = { + table: p.table, + column: p.column, + ...(jsonPath !== undefined ? { jsonPath } : {}), + fields: [p.label], + unmanaged: p.unmanaged, + }; + const none = { nonCanonical: 0, samples: [] as string[] }; + const cat = await catalogOf(p); + if (!(cat instanceof Map)) { + results.push({ ...base, status: "unreadable", reason: cat.error, ...none }); + continue; + } + if (cat.size === 0) { + results.push({ ...base, status: "missing", reason: "table not in this database", ...none }); + continue; + } + const type = cat.get(p.column); + if (type === undefined) { + results.push({ ...base, status: "missing", reason: "column not in this database", ...none }); + continue; + } + if (p.truncated !== undefined) { + results.push({ ...base, status: "unreadable", reason: p.truncated, ...none }); + continue; + } + try { + let sql: string; + if (dialect === "postgres") { + const plan = postgresPlan(p, type); + if ("native" in plan) { + results.push({ ...base, status: "native", ...none }); + continue; + } + if ("unreadable" in plan) { + results.push({ ...base, status: "unreadable", reason: plan.unreadable, ...none }); + continue; + } + sql = plan.sql; + } else { + sql = sqliteOffenders(p); + // A root uuid list reports text that is not JSON as a finding; anything deeper cannot read it. + const rootList = p.steps.length === 1 && p.steps[0]?.kind === "elements"; + const colKey = `${p.table}\u0000${p.column}`; + if (p.steps.length > 0 && !rootList && !parsedColumns.has(colKey)) { + parsedColumns.add(colKey); + const bad = await countAndSample(sqliteUnparsable(p.table, p.column)); + if (bad.nonCanonical > 0) { + const names = p.label.split("."); + const memberSteps = p.steps.filter((s) => s.kind === "member").length; + results.push({ + table: p.table, + column: p.column, + fields: [names.slice(0, names.length - memberSteps).join(".")], + unmanaged: p.unmanaged, + status: "unreadable", + reason: "stored text is not JSON: the uuids inside could not be read", + ...bad, + }); + } + } + } + results.push({ ...base, status: "scanned", ...(await countAndSample(sql)) }); + } catch (err) { + results.push({ ...base, status: "unreadable", reason: message(err), ...none }); + } + } + return results; +} + +/** The run's verdict: all-clear only when every place was read. */ +export type UuidVerdict = "clear" | "found" | "incomplete" | "nothing-declared"; + +export function uuidVerdict(results: readonly UuidColumnResult[]): UuidVerdict { + if (results.length === 0) return "nothing-declared"; + if (results.some((r) => r.status === "scanned" && r.nonCanonical > 0)) return "found"; + if (results.some((r) => r.status === "missing" || r.status === "unreadable")) return "incomplete"; + return "clear"; } /** A stored value as a finding quotes it: JSON-quoted, and cut short when it is long. */ @@ -394,28 +377,32 @@ export function quoteSample(value: string): string { } /** - * The printed report: one line per column, then the verdict. Exported for its test. `error` is - * set when the database holds none of the columns, so nothing was read: most likely the wrong - * database, and never a pass. + * The printed report: one line per place, then the verdict. Exported for its test. `error` is set + * when a place was not read and nothing was found: the run is incomplete, never a pass. */ export function uuidValuesReport( results: readonly UuidColumnResult[], displayUrl: string, ): { lines: string[]; failed: boolean; error?: string } { const lines: string[] = []; - if (results.length === 0) { - lines.push(`meta verify --uuid-values — no field.uuid column in ${displayUrl}'s governed tables; nothing to scan.`); + const verdict = uuidVerdict(results); + if (verdict === "nothing-declared") { + lines.push("meta verify --uuid-values — this model declares no stored field.uuid; nothing to scan."); return { lines, failed: false }; } - lines.push(`meta verify --uuid-values — ${results.length} field.uuid column(s) in ${displayUrl}:`); + lines.push(`meta verify --uuid-values — ${results.length} field.uuid place(s) in ${displayUrl}:`); let offending = 0; let total = 0; + const unread: string[] = []; for (const r of results) { - const where = ` ${r.table}.${r.column}${r.jsonPath !== undefined ? ` ${r.jsonPath}` : ""} (${r.fields.join(", ")})`; + const place = `${r.table}.${r.column}${r.jsonPath !== undefined ? ` ${r.jsonPath}` : ""}`; + const where = ` ${place} (${r.fields.join(", ")}${r.unmanaged ? ", @unmanaged" : ""})`; if (r.status === "native") { - lines.push(`${where}: native uuid column — the database only stores canonical uuids, not scanned`); - } else if (r.status === "missing") { - lines.push(`${where}: column not in the database — not scanned (meta verify --db reports schema drift)`); + lines.push(`${where}: native uuid column — the database only stores canonical uuids, not read`); + } else if (r.status === "missing" || r.status === "unreadable") { + unread.push(place); + const quoted = r.nonCanonical > 0 ? `; ${r.nonCanonical} value(s), e.g. ${r.samples.map(quoteSample).join(", ")}` : ""; + lines.push(`${where}: NOT READ — ${r.reason ?? r.status}${quoted}`); } else if (r.nonCanonical === 0) { lines.push(`${where}: every stored value is a canonical uuid`); } else { @@ -424,26 +411,21 @@ export function uuidValuesReport( lines.push(`${where}: ${r.nonCanonical} value(s) not a canonical uuid, e.g. ${r.samples.map(quoteSample).join(", ")}`); } } - const missing = results.filter((r) => r.status === "missing").length; - if (missing === results.length) { - const error = `no field.uuid column found in ${displayUrl} — wrong database? None of the ${missing} column(s) exists there, so no value was read`; - lines.push(`meta verify --uuid-values — ${error}.`); - return { lines, failed: true, error }; - } - const notScanned = missing > 0 ? ` ${missing} column(s) not in the database were not scanned.` : ""; - if (offending === 0) { - lines.push( - missing > 0 - ? `meta verify --uuid-values — every stored field.uuid value in the ${results.length - missing} column(s) present is canonical; the 1.3 uuid write check refuses none of them.${notScanned}` - : "meta verify --uuid-values — every stored field.uuid value is canonical; the 1.3 uuid write check refuses none of them.", - ); + const notRead = unread.length > 0 ? ` ${unread.length} place(s) were not read (listed above): ${unread.join(", ")}.` : ""; + if (verdict === "clear") { + lines.push("meta verify --uuid-values — every stored field.uuid value is canonical; the 1.3 uuid write check refuses none of them."); return { lines, failed: false }; } + if (verdict === "incomplete") { + const error = `incomplete — ${unread.length} of ${results.length} field.uuid place(s) in ${displayUrl} were not read, so the check cannot say every stored value is canonical: ${unread.join(", ")}`; + lines.push(`meta verify --uuid-values — ${error}. Point --db at the database the model describes, or fix what each line names.`); + return { lines, failed: true, error }; + } lines.push( - `meta verify --uuid-values — ${total} stored value(s) in ${offending} column(s) are not canonical 8-4-4-4-12 uuids. ` + + `meta verify --uuid-values — ${total} stored value(s) in ${offending} place(s) are not canonical 8-4-4-4-12 uuids. ` + "The rows still read, but since 1.3.0 a create or update carrying such a value is refused (400 validation). " + "Rewrite each value to a canonical uuid (and every foreign key that points at it), or declare the field field.string if it never held uuids." + - notScanned, + notRead, ); return { lines, failed: true }; } diff --git a/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap b/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap index 916fdce725..463fb16029 100644 --- a/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap +++ b/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap @@ -106,11 +106,12 @@ VERIFY FLAGS (ADR-0021 D2 — explicit subverbs; combine any; exit 1 on ANY drif temp-object probe on the target. Also SHADOW_DATABASE_URL or migrate.shadowDatabaseUrl in .metaobjects/config.json. --uuid-values Pre-upgrade data check, read-only: with --db (or --dialect d1), - read every field.uuid column and list each one whose stored values - are not canonical 8-4-4-4-12 uuids, with a count and samples. Since - 1.3.0 a create or update carrying such a value is refused. Exits 1 - when any is found. A native Postgres uuid column is not read (the - type already guarantees it). With this flag --db serves the scan + read every place the model types field.uuid (in every table, value + objects stored as JSON included) and list each one whose stored + values are not canonical 8-4-4-4-12 uuids, with a count and samples. + Since 1.3.0 a create or update carrying such a value is refused. + Exits 1 when any is found, or when a place could not be read. A + native Postgres uuid column is not read (the type guarantees it). With this flag --db serves the scan only; run 'meta verify --db ' for schema drift. --prompts Directory of provider-resolved template text (default: prompts) --dialect sqlite|postgres|d1 Optional override (auto-detected from --db URL scheme) diff --git a/server/typescript/packages/cli/test/verify-uuid-values.test.ts b/server/typescript/packages/cli/test/verify-uuid-values.test.ts index eccede381a..93aebbdc65 100644 --- a/server/typescript/packages/cli/test/verify-uuid-values.test.ts +++ b/server/typescript/packages/cli/test/verify-uuid-values.test.ts @@ -8,12 +8,16 @@ */ import { describe, test, expect, afterAll } from "bun:test"; import { Database } from "bun:sqlite"; -import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises"; +import { mkdtemp, mkdir, writeFile, rm, readdir } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { pathToFileURL } from "node:url"; import pg from "pg"; +import { runGen } from "@metaobjectsdev/codegen-ts"; +import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; import { verifyCommand } from "../src/commands/verify.js"; -import { uuidColumnsOf, uuidValuesReport } from "../src/lib/uuid-values-check.js"; +import { defineConfig } from "../src/index.js"; +import { scanUuidPlaces, uuidPlacesOf, uuidValuesReport, uuidVerdict, type UuidPlace } from "../src/lib/uuid-values-check.js"; import { parseVerifyArgs } from "../src/lib/args.js"; import { loadMemory } from "@metaobjectsdev/sdk"; @@ -23,7 +27,6 @@ afterAll(async () => { for (const d of dirs) await rm(d, { recursive: true, forc const CANONICAL_A = "3f2b8c1e-9d4a-4b7e-8c21-5a6f0e9d1b23"; const CANONICAL_B = "00000000-0000-0000-0000-000000000001"; -/** Member (uuid key), Claim (uuid key, uuid FK, uuid list, a string column the scan must ignore). */ /** Claim keeps a value object `meta` and a list of them, `history`, in JSON columns. */ const VO_MODEL = { "metadata.root": { package: "acme", children: [ { "object.value": { name: "Owner", children: [ @@ -44,18 +47,7 @@ const VO_MODEL = { "metadata.root": { package: "acme", children: [ ] } }, ] } }; -/** Two comparison CHECKs that share the default name `windows_a_cmp_chk`. */ -const SAME_NAMED_CHECKS_MODEL = { "metadata.root": { package: "acme", children: [ - { "object.entity": { name: "Window", children: [ - { "source.rdb": { "@table": "windows" } }, - { "field.uuid": { name: "id" } }, - { "field.int": { name: "a" } }, { "field.int": { name: "b" } }, { "field.int": { name: "c" } }, - { "identity.primary": { name: "pk", "@fields": ["id"] } }, - { "validator.comparison": { name: "ab", "@left": "a", "@op": "lt", "@right": "b" } }, - { "validator.comparison": { name: "ac", "@left": "a", "@op": "lt", "@right": "c" } }, - ] } }, -] } }; - +/** Member (uuid key), Claim (uuid key, uuid FK, uuid list, a string column the scan must ignore). */ const MODEL = { "metadata.root": { package: "acme", children: [ { "object.entity": { name: "Member", children: [ { "source.rdb": { "@table": "members" } }, @@ -74,13 +66,13 @@ const MODEL = { "metadata.root": { package: "acme", children: [ ] } }, ] } }; -async function project(model: unknown = MODEL): Promise { +async function project(model: unknown = MODEL, config: unknown = { schema_version: 1 }): Promise { const root = await mkdtemp(join(tmpdir(), "verify-uuid-values-")); dirs.push(root); await mkdir(join(root, "metaobjects"), { recursive: true }); await writeFile(join(root, "metaobjects", "meta.acme.json"), JSON.stringify(model), "utf8"); await mkdir(join(root, ".metaobjects"), { recursive: true }); - await writeFile(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1 }), "utf8"); + await writeFile(join(root, ".metaobjects", "config.json"), JSON.stringify(config), "utf8"); return root; } @@ -113,15 +105,77 @@ async function capture(fn: () => Promise): Promise<{ code: number; out: } } -describe("meta verify --uuid-values — which columns it reads", () => { +/** + * Every place a uuid can sit: map values, flattened members (scalar, object, map), a flattened + * value object on a TPH subtype (stored as one JSON column), a map of uuids (no check), an + * `@unmanaged` table. + */ +const KITCHEN = { "metadata.root": { package: "acme", children: [ + { "object.value": { name: "Geo", children: [{ "field.uuid": { name: "regionId" } }, { "field.string": { name: "label" } }] } }, + { "object.value": { name: "Tag", children: [{ "field.uuid": { name: "tagId" } }, { "field.uuid": { name: "aliasIds", isArray: true } }] } }, + { "object.value": { name: "Address", children: [ + { "field.uuid": { name: "placeId" } }, + { "field.uuid": { name: "altIds", isArray: true } }, + { "field.object": { name: "geo", "@objectRef": "Geo" } }, + { "field.map": { name: "tags", "@objectRef": "Tag" } }, + ] } }, + { "object.value": { name: "ClaimMeta", children: [ + { "field.uuid": { name: "memberId" } }, + { "field.uuid": { name: "tagIds", isArray: true } }, + { "field.string": { name: "note" } }, + { "field.object": { name: "geo", "@objectRef": "Geo" } }, + { "field.object": { name: "stops", "@objectRef": "Geo", isArray: true } }, + { "field.map": { name: "byKey", "@objectRef": "Tag" } }, + ] } }, + { "object.entity": { name: "Member", children: [ + { "source.rdb": { "@table": "members" } }, + { "field.uuid": { name: "id" } }, + { "field.string": { name: "name" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + { "object.entity": { name: "Claim", children: [ + { "source.rdb": { "@table": "claims" } }, + { "field.uuid": { name: "id" } }, + { "field.uuid": { name: "memberId" } }, + { "field.uuid": { name: "witnessIds", isArray: true } }, + { "field.string": { name: "legacyRef", "@dbColumnType": "uuid" } }, + { "field.object": { name: "meta", "@objectRef": "ClaimMeta" } }, + { "field.object": { name: "history", "@objectRef": "ClaimMeta", "@storage": "jsonb", isArray: true } }, + { "field.map": { name: "byRegion", "@objectRef": "Geo" } }, + { "field.map": { name: "plainMap", "@valueType": "uuid" } }, + { "field.object": { name: "home", "@objectRef": "Address", "@storage": "flattened" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + { "identity.reference": { name: "ref_member", "@fields": ["memberId"], "@references": "Member" } }, + ] } }, + { "object.entity": { name: "Party", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "parties" } }, + { "field.uuid": { name: "id" } }, + { "field.string": { name: "kind" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + { "object.entity": { name: "Person", extends: "Party", "@discriminatorValue": "person", children: [ + { "field.uuid": { name: "householdId" } }, + { "field.object": { name: "work", "@objectRef": "Address", "@storage": "flattened" } }, + ] } }, + { "object.entity": { name: "Legacy", children: [ + { "source.rdb": { "@table": "legacy_things", "@unmanaged": true } }, + { "field.uuid": { name: "id" } }, + { "field.uuid": { name: "ownerId" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, +] } }; + +/** A place as `table.column $path Label`, for comparing enumerations. */ +const placeKey = (p: UuidPlace): string => + `${p.table}.${p.column}${p.steps.length > 0 ? ` $${p.steps.map((s) => (s.kind === "member" ? `.${s.key}` : s.kind === "elements" ? "[*]" : ".*")).join("")}` : ""} ${p.label}${p.unmanaged ? " @unmanaged" : ""}`; + +describe("meta verify --uuid-values — which places it reads", () => { test("every field.uuid column: keys, foreign keys and lists; never a field.string, even one stored as uuid", async () => { - const root = await project(); - const loaded = await loadMemory(root); - const cols = uuidColumnsOf(loaded, {}, "sqlite"); - expect(cols.map((c) => `${c.table}.${c.column}${c.isArray ? "[]" : ""} ${c.fields.join(",")}`)).toEqual([ + const loaded = await loadMemory(await project()); + expect(uuidPlacesOf(loaded).map(placeKey).sort()).toEqual([ "claims.id Claim.id", "claims.member_id Claim.memberId", - "claims.witness_ids[] Claim.witnessIds", + "claims.witness_ids $[*] Claim.witnessIds", "members.id Member.id", ]); }); @@ -140,45 +194,132 @@ describe("meta verify --uuid-values — which columns it reads", () => { { "field.uuid": { name: "householdId" } }, ] } }, ] } }); - const loaded = await loadMemory(root); - const cols = uuidColumnsOf(loaded, {}, "sqlite"); - expect(cols.map((c) => `${c.table}.${c.column} ${c.fields.join(",")}`)).toEqual([ + expect(uuidPlacesOf(await loadMemory(root)).map(placeKey).sort()).toEqual([ "parties.household_id Person.householdId", - "parties.id Party.id,Person.id", + "parties.id Party.id", ]); }); test("a field.uuid member of a value object stored as JSON is read inside its column, nested and in lists", async () => { - const root = await project(VO_MODEL); - const loaded = await loadMemory(root); - const cols = uuidColumnsOf(loaded, {}, "sqlite"); - expect(cols.map((c) => `${c.table}.${c.column} ${c.members.length > 0 ? `${c.isArray ? "[*]" : ""}${c.members.map((m) => `.${m.key}${m.isArray ? "[*]" : ""}`).join("")} ` : ""}${c.fields.join(",")}`)).toEqual([ - "claims.history [*].memberId Claim.history.memberId", - "claims.history [*].owner.ownerId Claim.history.owner.ownerId", - "claims.history [*].tagIds[*] Claim.history.tagIds", + const loaded = await loadMemory(await project(VO_MODEL)); + expect(uuidPlacesOf(loaded).map(placeKey).sort()).toEqual([ + "claims.history $[*].memberId Claim.history.memberId", + "claims.history $[*].owner.ownerId Claim.history.owner.ownerId", + "claims.history $[*].tagIds[*] Claim.history.tagIds", "claims.id Claim.id", - "claims.meta .memberId Claim.meta.memberId", - "claims.meta .owner.ownerId Claim.meta.owner.ownerId", - "claims.meta .tagIds[*] Claim.meta.tagIds", + "claims.meta $.memberId Claim.meta.memberId", + "claims.meta $.owner.ownerId Claim.meta.owner.ownerId", + "claims.meta $.tagIds[*] Claim.meta.tagIds", ]); }); - test("the schema is built for the dialect it reads: a model Postgres refuses still scans on SQLite", async () => { - // Two CHECKs under one default name: SQLite and D1 keep both, Postgres refuses the model. - const root = await project(SAME_NAMED_CHECKS_MODEL); - const loaded = await loadMemory(root); - expect(() => uuidColumnsOf(loaded, {}, "postgres")).toThrow(/Postgres requires/); - expect(uuidColumnsOf(loaded, {}, "sqlite").map((c) => `${c.table}.${c.column}`)).toEqual(["windows.id"]); + test("map values, flattened members that hold JSON, a TPH subtype's flattened value object, and an @unmanaged table", async () => { + const places = uuidPlacesOf(await loadMemory(await project(KITCHEN))).map(placeKey); + expect(places).toEqual(expect.arrayContaining([ + // field.map of value objects: each value's members. + "claims.by_region $.*.regionId Claim.byRegion.regionId", + // A flattened value object: a uuid member is its own column, an object or map member a JSON column. + "claims.home_place_id Claim.home.placeId", + "claims.home_alt_ids $[*] Claim.home.altIds", + "claims.home_geo $.regionId Claim.home.geo.regionId", + "claims.home_tags $.*.tagId Claim.home.tags.tagId", + "claims.home_tags $.*.aliasIds[*] Claim.home.tags.aliasIds", + // migrate stores a TPH subtype's flattened value object as ONE JSON column. + "parties.work $.placeId Person.work.placeId", + "parties.work $.geo.regionId Person.work.geo.regionId", + "parties.work $.tags.*.tagId Person.work.tags.tagId", + // An @unmanaged table holds rows the write check applies to. + "legacy_things.id Legacy.id @unmanaged", + "legacy_things.owner_id Legacy.ownerId @unmanaged", + ])); + // A map of uuids is a plain string map in the write schema: not checked, so not read. + expect(places.some((p) => p.includes("plain_map"))).toBe(false); + }); + + test("the places equal the positions the generated insert schemas check for the uuid shape", async () => { + // Oracle: the real entity module the reference generator writes, imported and walked as live + // Zod schemas. A nesting the write schema checks and the scan does not read fails here. + const loaded = await loadMemory(await project(KITCHEN)); + const dir = await mkdtemp(join(import.meta.dir, "tmp-uuid-write-schema-")); + dirs.push(dir); + await runGen({ + config: defineConfig({ outDir: join(dir, "out"), outputLayout: "flat", extStyle: "none", dbImport: "../db", dialect: "sqlite", generators: [entityFile()] }), + metadata: loaded, + projectRoot: dir, + sourceFiles: [], + }); + const mods: Record = {}; + for (const f of (await readdir(join(dir, "out"), { recursive: true })).filter((x) => x.endsWith(".ts"))) { + Object.assign(mods, await import(pathToFileURL(join(dir, "out", f)).href)); + } + type Schema = { _def?: Record; def?: Record; safeParse(v: unknown): { success: boolean } }; + const checksUuid = (s: Schema): boolean => + s.safeParse(CANONICAL_B).success && s.safeParse(CANONICAL_A.toUpperCase()).success && !s.safeParse("mbr1").success; + const checked = new Set(); + const visit = (s: Schema | undefined, path: string): void => { + const def = (s?._def ?? s?.def) as Record | undefined; + if (s === undefined || def === undefined) return; + const t = String(def.typeName ?? def.type ?? "").toLowerCase().replace(/^zod/, ""); + if (t === "object") { + const shape = (typeof def.shape === "function" ? (def.shape as () => unknown)() : def.shape) as Record; + for (const [k, v] of Object.entries(shape)) visit(v, `${path}.${k}`); + } else if (t === "array") visit((def.element ?? def.type) as Schema, `${path}[*]`); + else if (t === "record") visit(def.valueType as Schema, `${path}.*`); + else if (["optional", "nullable", "default", "readonly", "nonoptional"].includes(t)) visit(def.innerType as Schema, path); + else if (["effects", "pipe", "pipeline"].includes(t)) visit((def.schema ?? def.in) as Schema, path); + else if (t === "string" && checksUuid(s)) checked.add(path); + }; + for (const e of ["Member", "Claim", "Party", "Person", "Legacy"]) { + const schema = mods[`${e}InsertSchema`] as Schema | undefined; + expect(schema).toBeDefined(); + visit(schema, e); + } + // A subtype's schema repeats its base's fields, which are the base's places. + const written = [...checked].filter((p) => !(p.startsWith("Person.") && checked.has(`Party.${p.slice("Person.".length)}`))); + // The same notation for a place: a flattened member is a row key (home.placeId is homePlaceId). + const scanned = uuidPlacesOf(loaded).map((p) => { + const names = p.label.split("."); + const flat = names.length - 2 - p.steps.filter((s) => s.kind === "member").length; + let out = `${names[0]}.${names.slice(1, 2 + flat).map((n, k) => (k === 0 ? n : `${n[0]!.toUpperCase()}${n.slice(1)}`)).join("")}`; + let i = 2 + flat; + for (const s of p.steps) out += s.kind === "member" ? `.${names[i++]}` : s.kind === "elements" ? "[*]" : ".*"; + return out; + }); + expect(written.length).toBeGreaterThan(20); + expect(scanned.sort()).toEqual(written.sort()); + }); + + test("a value object that contains itself is one place marked as not read past that depth", async () => { + const root = await project({ "metadata.root": { package: "acme", children: [ + { "object.value": { name: "Node", children: [ + { "field.uuid": { name: "nodeId" } }, + { "field.object": { name: "kids", "@objectRef": "Node", isArray: true } }, + ] } }, + { "object.entity": { name: "Tree", children: [ + { "source.rdb": { "@table": "trees" } }, + { "field.uuid": { name: "id" } }, + { "field.object": { name: "top", "@objectRef": "Node" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + ] } }); + const places = uuidPlacesOf(await loadMemory(root)); + expect(places.map(placeKey).sort()).toEqual([ + "trees.id Tree.id", + "trees.top $.kids[*] Tree.top.kids", + "trees.top $.nodeId Tree.top.nodeId", + ]); + expect(places.find((p) => p.label === "Tree.top.kids")?.truncated).toContain("contains itself"); - const file = join(root, "windows.db"); + const file = join(root, "trees.db"); const db = new Database(file); - db.run("CREATE TABLE windows (id TEXT PRIMARY KEY, a INTEGER, b INTEGER, c INTEGER)"); - db.run("INSERT INTO windows VALUES ('win1', 1, 2, 3)"); + db.run("CREATE TABLE trees (id TEXT PRIMARY KEY, top TEXT)"); + db.run("INSERT INTO trees VALUES (?, ?)", [CANONICAL_A, JSON.stringify({ nodeId: CANONICAL_B, kids: [{ nodeId: "deep-bad" }] })]); db.close(); const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); expect(code).toBe(1); - expect(out).toContain(`windows.id (Window.id): 1 value(s) not a canonical uuid, e.g. "win1"`); - expect(out).not.toContain("Postgres requires"); + expect(out).toContain("trees.top $.kids[*] (Tree.top.kids): NOT READ — value object Node contains itself"); + expect(out).toContain("incomplete"); + expect(out).not.toContain("every stored field.uuid value is canonical"); }); test("--uuid-values without a database is refused at parse time", () => { @@ -186,13 +327,34 @@ describe("meta verify --uuid-values — which columns it reads", () => { expect(parseVerifyArgs(["--uuid-values", "--dialect", "d1"]).uuidValues).toBe(true); }); - test("the report: nothing to scan, all canonical, and findings", () => { + test("the verdict: nothing declared, clear, found, and incomplete when any place was not read", () => { + const row = { table: "t", column: "id", fields: ["T.id"], unmanaged: false, nonCanonical: 0, samples: [] as string[] }; expect(uuidValuesReport([], "file:x").failed).toBe(false); - const clean = uuidValuesReport([{ table: "t", column: "id", fields: ["T.id"], status: "scanned", nonCanonical: 0, samples: [] }], "file:x"); + expect(uuidValuesReport([], "file:x").lines.join("\n")).toContain("declares no stored field.uuid"); + + const clean = uuidValuesReport([{ ...row, status: "scanned" }, { ...row, column: "n", status: "native" }], "file:x"); expect(clean.failed).toBe(false); - const bad = uuidValuesReport([{ table: "t", column: "id", fields: ["T.id"], status: "scanned", nonCanonical: 2, samples: ["a", "b"] }], "file:x"); + expect(clean.lines.join("\n")).toContain("every stored field.uuid value is canonical"); + + const bad = uuidValuesReport([{ ...row, status: "scanned", nonCanonical: 2, samples: ["a", "b"] }], "file:x"); expect(bad.failed).toBe(true); + expect(bad.error).toBeUndefined(); expect(bad.lines.join("\n")).toContain(`t.id (T.id): 2 value(s) not a canonical uuid, e.g. "a", "b"`); + + const missing = [{ ...row, status: "scanned" as const }, { ...row, table: "u", status: "missing" as const, reason: "table not in this database" }]; + expect(uuidVerdict(missing)).toBe("incomplete"); + const incomplete = uuidValuesReport(missing, "file:x"); + expect(incomplete.failed).toBe(true); + expect(incomplete.error).toContain("1 of 2 field.uuid place(s)"); + expect(incomplete.lines.join("\n")).toContain("u.id (T.id): NOT READ — table not in this database"); + expect(incomplete.lines.join("\n")).not.toContain("every stored field.uuid value is canonical"); + + // Findings and an unread place: both are named. + const both = uuidValuesReport([{ ...row, status: "scanned", nonCanonical: 1, samples: ["a"] }, { ...row, table: "u", status: "unreadable", reason: "boom" }], "file:x"); + expect(uuidVerdict([{ ...row, status: "scanned", nonCanonical: 1, samples: ["a"] }, { ...row, table: "u", status: "unreadable", reason: "boom" }])).toBe("found"); + expect(both.failed).toBe(true); + expect(both.lines.join("\n")).toContain("u.id (T.id): NOT READ — boom"); + expect(both.lines.at(-1)).toContain("1 place(s) were not read (listed above): u.id"); }); }); @@ -212,9 +374,9 @@ describe("meta verify --uuid-values — SQLite", () => { expect(out).toContain(`claims.member_id (Claim.memberId): 1 value(s) not a canonical uuid, e.g. "mbr1"`); expect(out).toContain(`claims.id (Claim.id): 1 value(s) not a canonical uuid, e.g. "clm2"`); // One bad element of a well-formed list, and one stored value that is not a JSON list at all. - expect(out).toContain(`claims.witness_ids (Claim.witnessIds): 2 value(s) not a canonical uuid, e.g. "not json", "w-1"`); + expect(out).toContain(`claims.witness_ids $[*] (Claim.witnessIds): 2 value(s) not a canonical uuid, e.g. "not json", "w-1"`); expect(out).not.toContain("legacy_ref"); - expect(out).toContain("5 stored value(s) in 4 column(s) are not canonical"); + expect(out).toContain("5 stored value(s) in 4 place(s) are not canonical"); // `--db` served the scan alone: the hand-made tables differ from the expected schema, // and the schema gate was not run to say so. expect(out).not.toContain("schema drift"); @@ -251,32 +413,135 @@ describe("meta verify --uuid-values — SQLite", () => { expect(payload.help.some((h) => h.includes("uuidValues[]"))).toBe(true); }); - test("a column missing from the database is named, not read, and does not fail the scan", async () => { + test("a table missing from the database is named, not read, and makes the run incomplete: exit 1", async () => { const root = await project(); const file = join(root, "partial.db"); const db = new Database(file); db.run("CREATE TABLE members (id TEXT PRIMARY KEY, name TEXT)"); db.close(); const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); - expect(code).toBe(0); - expect(out).toContain("claims.member_id (Claim.memberId): column not in the database"); - // The verdict does not claim every stored value: three columns were never read. - expect(out).toContain("in the 1 column(s) present is canonical"); - expect(out).toContain("3 column(s) not in the database were not scanned"); + expect(code).toBe(1); + expect(out).toContain("members.id (Member.id): every stored value is a canonical uuid"); + expect(out).toContain("claims.member_id (Claim.memberId): NOT READ — table not in this database"); + expect(out).toContain("incomplete — 3 of 4 field.uuid place(s)"); + expect(out).not.toContain("every stored field.uuid value is canonical"); }); - test("a database holding none of the columns fails as a wrong database, not a pass", async () => { + test("a column missing from a table that exists is named as such", async () => { + const root = await project(); + const file = join(root, "nocol.db"); + const db = new Database(file); + db.run("CREATE TABLE members (id TEXT PRIMARY KEY, name TEXT)"); + db.run("CREATE TABLE claims (id TEXT PRIMARY KEY, member_id TEXT, legacy_ref TEXT)"); + db.close(); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); + expect(code).toBe(1); + expect(out).toContain("claims.witness_ids $[*] (Claim.witnessIds): NOT READ — column not in this database"); + expect(out).toContain("incomplete — 1 of 4 field.uuid place(s)"); + }); + + test("a database holding none of the tables is incomplete, not a pass", async () => { const root = await project(); const file = join(root, "app.dbb"); const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); expect(code).toBe(1); - expect(out).toContain(`no field.uuid column found in file:${file} — wrong database?`); + expect(out).toContain(`incomplete — 4 of 4 field.uuid place(s) in file:${file} were not read`); expect(out).not.toContain("every stored field.uuid value"); const json = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root, undefined, "json")); expect(json.code).toBe(1); - const payload = JSON.parse(json.stdout) as { errors: { gate: string; error: string }[] }; - expect(payload.errors).toContainEqual(expect.objectContaining({ gate: "uuid-values", error: expect.stringContaining("wrong database?") })); + const payload = JSON.parse(json.stdout) as { verify: { gate: string; ok: boolean }[]; errors: { gate: string; error: string }[] }; + expect(payload.verify).toContainEqual(expect.objectContaining({ gate: "uuid-values", ok: false })); + expect(payload.errors).toContainEqual(expect.objectContaining({ gate: "uuid-values", error: expect.stringContaining("were not read") })); + }); + + test("one place's failing query is recorded on that place; the others are still read", async () => { + const root = await project(); + const db = new Database(":memory:"); + db.run("CREATE TABLE members (id TEXT PRIMARY KEY, name TEXT)"); + db.run("CREATE TABLE claims (id TEXT PRIMARY KEY, member_id TEXT, witness_ids TEXT, legacy_ref TEXT)"); + db.run("INSERT INTO members VALUES ('mbr1', 'x')"); + const results = await scanUuidPlaces(uuidPlacesOf(await loadMemory(root)), "sqlite", async (q) => { + if (q.includes(`"member_id"`) && !q.includes("pragma_table_info")) throw new Error("simulated transport failure"); + return db.query(q).all() as Record[]; + }); + db.close(); + expect(results.find((r) => r.column === "member_id")).toMatchObject({ status: "unreadable", reason: "simulated transport failure" }); + expect(results.find((r) => r.table === "members")).toMatchObject({ status: "scanned", nonCanonical: 1, samples: ["mbr1"] }); + expect(results.find((r) => r.table === "claims" && r.column === "id")).toMatchObject({ status: "scanned", nonCanonical: 0 }); + expect(uuidVerdict(results)).toBe("found"); + }); + + test("text that is not JSON in a value-object column is unreadable, never clear", async () => { + const root = await project(VO_MODEL); + const file = join(root, "notjson.db"); + const db = new Database(file); + db.run("CREATE TABLE claims (id TEXT PRIMARY KEY, meta TEXT, history TEXT)"); + db.run("INSERT INTO claims VALUES (?, ?, NULL)", [CANONICAL_A, "memberId=mbr1"]); + db.close(); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); + expect(code).toBe(1); + expect(out).toContain(`claims.meta (Claim.meta): NOT READ — stored text is not JSON: the uuids inside could not be read; 1 value(s), e.g. "memberId=mbr1"`); + expect(out).toContain("incomplete"); + }); + + test("an @unmanaged table and a table outside migrate.scope are read like any other", async () => { + const model = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Member", children: [ + { "source.rdb": { "@table": "members" } }, + { "field.uuid": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + { "object.entity": { name: "Legacy", children: [ + { "source.rdb": { "@table": "legacy_things", "@unmanaged": true } }, + { "field.uuid": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + ] } }; + // migrate.scope matches nothing: meta migrate governs no table here, and the scan reads both. + const root = await project(model, { schema_version: 1, migrate: { scope: ["other::**"] } }); + const file = join(root, "scoped.db"); + const db = new Database(file); + db.run("CREATE TABLE members (id TEXT PRIMARY KEY)"); + db.run("CREATE TABLE legacy_things (id TEXT PRIMARY KEY)"); + db.run("INSERT INTO members VALUES ('mbr1')"); + db.run("INSERT INTO legacy_things VALUES ('leg1')"); + db.close(); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); + expect(code).toBe(1); + expect(out).toContain(`members.id (Member.id): 1 value(s) not a canonical uuid, e.g. "mbr1"`); + expect(out).toContain(`legacy_things.id (Legacy.id, @unmanaged): 1 value(s) not a canonical uuid, e.g. "leg1"`); + }); + + test("map values, flattened members holding JSON and a TPH subtype's flattened value object are read", async () => { + const root = await project(KITCHEN); + const file = join(root, "kitchen.db"); + const db = new Database(file); + db.run("CREATE TABLE claims (id TEXT, member_id TEXT, witness_ids TEXT, meta TEXT, history TEXT, by_region TEXT, home_place_id TEXT, home_alt_ids TEXT, home_geo TEXT, home_tags TEXT)"); + db.run("CREATE TABLE parties (id TEXT, kind TEXT, household_id TEXT, work TEXT)"); + db.run("INSERT INTO claims (id, by_region, home_geo, home_tags) VALUES (?, ?, ?, ?)", [ + CANONICAL_A, + JSON.stringify({ east: { regionId: "reg1" }, west: { regionId: CANONICAL_B } }), + JSON.stringify({ regionId: "geo1" }), + JSON.stringify({ a: { tagId: "tag1", aliasIds: [CANONICAL_A, "alias1"] } }), + ]); + db.run("INSERT INTO parties (id, kind, work) VALUES (?, 'person', ?)", [ + CANONICAL_B, + JSON.stringify({ placeId: "plc1", geo: { regionId: CANONICAL_A }, tags: { x: { tagId: "wtag1" } } }), + ]); + db.close(); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); + expect(code).toBe(1); + expect(out).toContain(`claims.by_region $.*.regionId (Claim.byRegion.regionId): 1 value(s) not a canonical uuid, e.g. "reg1"`); + expect(out).toContain(`claims.home_geo $.regionId (Claim.home.geo.regionId): 1 value(s) not a canonical uuid, e.g. "geo1"`); + expect(out).toContain(`claims.home_tags $.*.tagId (Claim.home.tags.tagId): 1 value(s) not a canonical uuid, e.g. "tag1"`); + expect(out).toContain(`claims.home_tags $.*.aliasIds[*] (Claim.home.tags.aliasIds): 1 value(s) not a canonical uuid, e.g. "alias1"`); + expect(out).toContain(`parties.work $.placeId (Person.work.placeId): 1 value(s) not a canonical uuid, e.g. "plc1"`); + expect(out).toContain(`parties.work $.tags.*.tagId (Person.work.tags.tagId): 1 value(s) not a canonical uuid, e.g. "wtag1"`); + expect(out).toContain("parties.work $.geo.regionId (Person.work.geo.regionId): every stored value is a canonical uuid"); + // members and legacy_things are not in this database: named, never silently skipped. + expect(out).toContain("members.id (Member.id): NOT READ — table not in this database"); + expect(out).toContain("legacy_things.id (Legacy.id, @unmanaged): NOT READ — table not in this database"); }); test("a JSON null element of a uuid list is counted: the write check refuses it", async () => { @@ -285,7 +550,7 @@ describe("meta verify --uuid-values — SQLite", () => { sqliteDb(file, [CANONICAL_A], [[CANONICAL_B, CANONICAL_A, JSON.stringify([CANONICAL_A, null]), null]]); const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); expect(code).toBe(1); - expect(out).toContain(`claims.witness_ids (Claim.witnessIds): 1 value(s) not a canonical uuid, e.g. "null"`); + expect(out).toContain(`claims.witness_ids $[*] (Claim.witnessIds): 1 value(s) not a canonical uuid, e.g. "null"`); }); test("a file inside wrangler's local D1 state warns that it is the LOCAL database", async () => { @@ -324,7 +589,7 @@ describe("meta verify --uuid-values — SQLite", () => { expect(out).toContain(`claims.history $[*].tagIds[*] (Claim.history.tagIds): 1 value(s) not a canonical uuid, e.g. "not-a-list"`); expect(out).toContain(`claims.history $[*].owner.ownerId (Claim.history.owner.ownerId): 1 value(s) not a canonical uuid, e.g. "7"`); expect(out).toContain("claims.id (Claim.id): every stored value is a canonical uuid"); - expect(out).toContain("7 stored value(s) in 6 column(s) are not canonical"); + expect(out).toContain("7 stored value(s) in 6 place(s) are not canonical"); }); }); @@ -345,7 +610,8 @@ describe("meta verify --uuid-values — D1", () => { const q = args[args.indexOf("--command") + 1] ?? ""; seen.push(q); const results = - q.includes("pragma_table_info") ? [{ ok: 1 }] + q.includes("pragma_table_info") ? [{ column_name: "id" }, { column_name: "member_id" }, { column_name: "witness_ids" }] + : q === "SELECT 1 AS ok" ? [{ ok: 1 }] : q.startsWith("SELECT COUNT(*)") ? [{ n: q.includes(`"members"`) ? 2 : 0 }] : q.startsWith("SELECT DISTINCT") ? [{ v: "mbr1" }, { v: "mbr2" }] : []; @@ -399,7 +665,7 @@ describe("meta verify --uuid-values — Postgres (env-gated: MIGRATE_TS_PG_URL)" const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", url], root)); expect(code).toBe(1); expect(out).toContain("members.id (Member.id): native uuid column"); - expect(out).toContain("claims.witness_ids (Claim.witnessIds): native uuid column"); + expect(out).toContain("claims.witness_ids $[*] (Claim.witnessIds): native uuid column"); expect(out).toContain(`claims.member_id (Claim.memberId): 1 value(s) not a canonical uuid, e.g. "mbr1"`); }); }); @@ -414,13 +680,37 @@ describe("meta verify --uuid-values — Postgres (env-gated: MIGRATE_TS_PG_URL)" const root = await project(); const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", url], root)); expect(code).toBe(1); - const line = out.split("\n").find((l) => l.includes("claims.witness_ids (Claim.witnessIds)")) ?? ""; + const line = out.split("\n").find((l) => l.includes("claims.witness_ids $[*] (Claim.witnessIds)")) ?? ""; expect(line).toContain("3 value(s) not a canonical uuid"); // The sample order follows the database's collation. for (const sample of [`"null"`, `"w-1"`, `"\\"solo\\""`]) expect(line).toContain(sample); }); }); + test("a value object in a column that is not json is unreadable; a table in another schema is read", async () => { + await withPgDatabase([ + "CREATE SCHEMA crm", + "CREATE TABLE claims (id uuid PRIMARY KEY, meta text, history jsonb)", + `INSERT INTO claims VALUES ('${CANONICAL_A}', '{"memberId":"mbr1"}', NULL)`, + "CREATE TABLE crm.members (id text PRIMARY KEY)", + "INSERT INTO crm.members VALUES ('mbr2')", + ], async (url) => { + const root = await project({ "metadata.root": { package: "acme", children: [ + ...VO_MODEL["metadata.root"].children, + { "object.entity": { name: "Member", children: [ + { "source.rdb": { "@table": "members", "@schema": "crm" } }, + { "field.uuid": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + ] } }); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", url], root)); + expect(code).toBe(1); + expect(out).toContain("claims.meta $.memberId (Claim.meta.memberId): NOT READ — column type text is not json or jsonb"); + expect(out).toContain(`members.id (Member.id): 1 value(s) not a canonical uuid, e.g. "mbr2"`); + expect(out).toContain("3 place(s) were not read (listed above): claims.meta $.memberId"); + }); + }); + test("value-object members stored as jsonb are read: scalar, list, nested, and inside a list of value objects", async () => { const meta = (v: unknown): string => `'${JSON.stringify(v)}'::jsonb`; await withPgDatabase([ diff --git a/server/typescript/packages/integration-tests/test/uuid-values-scan.test.ts b/server/typescript/packages/integration-tests/test/uuid-values-scan.test.ts new file mode 100644 index 0000000000..b5c3ee3a97 --- /dev/null +++ b/server/typescript/packages/integration-tests/test/uuid-values-scan.test.ts @@ -0,0 +1,233 @@ +// bun:test entry — `meta verify --uuid-values`'s SQL on a real engine: bun:sqlite and Cloudflare +// D1's local runtime (Miniflare runs the real workerd D1 binding, with D1's own limits: a LIKE/GLOB +// pattern over 50 bytes, a statement over 100 KB, a compound SELECT over five terms are refused). +// +// Oracle: an independent walk, in JavaScript, of the very values planted in each column, using the +// canonical 8-4-4-4-12 pattern the 1.3 write check applies. Each place's count from the SQL must +// equal the walk's count. A builder that a D1 limit refuses fails as `unreadable` here. + +import { Database } from "bun:sqlite"; +import { describe, expect, test } from "bun:test"; +import { loadString, type MetaData } from "@metaobjectsdev/metadata"; +import { + CANONICAL_UUID_PATTERN, + scanUuidPlaces, + uuidPlacesOf, + uuidVerdict, + type RowQuery, + type UuidColumnResult, + type UuidPlace, + type UuidStep, +} from "../../cli/src/lib/uuid-values-check.ts"; +import { startLocalD1 } from "../src/query-scenario-d1.ts"; + +const MODEL = { "metadata.root": { package: "acme", children: [ + { "object.value": { name: "Geo", children: [{ "field.uuid": { name: "regionId" } }, { "field.string": { name: "label" } }] } }, + { "object.value": { name: "Tag", children: [{ "field.uuid": { name: "tagId" } }, { "field.uuid": { name: "aliasIds", isArray: true } }] } }, + { "object.value": { name: "Address", children: [ + { "field.uuid": { name: "placeId" } }, + { "field.uuid": { name: "altIds", isArray: true } }, + { "field.object": { name: "geo", "@objectRef": "Geo" } }, + { "field.map": { name: "tags", "@objectRef": "Tag" } }, + ] } }, + { "object.value": { name: "ClaimMeta", children: [ + { "field.uuid": { name: "memberId" } }, + { "field.uuid": { name: "tagIds", isArray: true } }, + { "field.object": { name: "geo", "@objectRef": "Geo" } }, + { "field.object": { name: "stops", "@objectRef": "Geo", isArray: true } }, + { "field.map": { name: "byKey", "@objectRef": "Tag" } }, + ] } }, + { "object.entity": { name: "Claim", children: [ + { "source.rdb": { "@table": "claims" } }, + { "field.uuid": { name: "id" } }, + { "field.uuid": { name: "witnessIds", isArray: true } }, + { "field.object": { name: "meta", "@objectRef": "ClaimMeta" } }, + { "field.object": { name: "history", "@objectRef": "ClaimMeta", "@storage": "jsonb", isArray: true } }, + { "field.map": { name: "byRegion", "@objectRef": "Geo" } }, + { "field.object": { name: "home", "@objectRef": "Address", "@storage": "flattened" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + { "object.entity": { name: "Party", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "parties" } }, + { "field.uuid": { name: "id" } }, + { "field.string": { name: "kind" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + { "object.entity": { name: "Person", extends: "Party", "@discriminatorValue": "person", children: [ + { "field.object": { name: "work", "@objectRef": "Address", "@storage": "flattened" } }, + ] } }, +] } }; + +const RE = new RegExp(CANONICAL_UUID_PATTERN); + +/** A seeded generator, so a failure reproduces. */ +function rng(seed: number): { rnd: () => number; pick: (xs: readonly T[]) => T } { + let s = seed; + const rnd = (): number => { + s = (s * 1103515245 + 12345) & 0x7fffffff; + return s / 0x7fffffff; + }; + return { rnd, pick: (xs) => xs[Math.floor(rnd() * xs.length)]! }; +} + +/** Strings near the canonical shape, and a few far from it; a full-width digit; LIKE/GLOB metacharacters. */ +const BAD_STRINGS = [ + "mbr1", "", "null", "00000000-0000-0000-0000-00000000000G", "00000000-0000-0000-0000-0000000000001", + "00000000-0000-0000-0000-00000000000", "------------------------------------", "00000000_0000_0000_0000_000000000001", + "{00000000-0000-0000-0000-000000000001}", "00000000-0000-0000-0000-000000000001\n", "0000000-00000-0000-0000-000000000001", + "00000000-0000-0000-0000-000000000001", "00000000-0000-0000-00000000-00000001", "it's", "%", "*", +]; + +interface Cell { column: string; stored: string | number | null; parsed: unknown; notJson: boolean } + +function plant(places: readonly UuidPlace[], seed: number, rows: number): Map { + const { rnd, pick } = rng(seed); + const hex = (n: number): string => Array.from({ length: n }, () => pick([..."0123456789abcdefABCDEF"])).join(""); + const good = (): string => `${hex(8)}-${hex(4)}-${hex(4)}-${hex(4)}-${hex(12)}`; + const uuidish = (): unknown => { + const r = rnd(); + if (r < 0.55) return good(); + if (r < 0.85) return pick(BAD_STRINGS); + return pick([null, 7, true, {}, [], ["a"]]); + }; + const gen = (steps: readonly UuidStep[]): unknown => { + if (steps.length === 0) return uuidish(); + const [s, ...rest] = steps as [UuidStep, ...UuidStep[]]; + if (rnd() < 0.12) return pick([null, "mbr1", 3, [], {}, [1, "x", null]]); + if (s.kind === "member") return { [s.key]: gen(rest), other: "x" }; + if (s.kind === "elements") return Array.from({ length: Math.floor(rnd() * 4) }, () => gen(rest)); + return Object.fromEntries(Array.from({ length: Math.floor(rnd() * 3) }, (_, i) => [`k${i}`, gen(rest)])); + }; + const plain = (x: unknown): x is Record => typeof x === "object" && x !== null && !Array.isArray(x); + const merge = (a: unknown, b: unknown): unknown => { + if (plain(a) && plain(b)) { + const o: Record = { ...a }; + for (const [k, v] of Object.entries(b)) o[k] = k in o ? merge(o[k], v) : v; + return o; + } + if (Array.isArray(a) && Array.isArray(b)) return (a.length >= b.length ? a : b).map((_, i) => (i < a.length && i < b.length ? merge(a[i], b[i]) : (a[i] ?? b[i]))); + return a; + }; + const columns = new Map>(); + for (const p of places) { + const cols = columns.get(p.table) ?? new Map(); + cols.set(p.column, [...(cols.get(p.column) ?? []), p]); + columns.set(p.table, cols); + } + const out = new Map(); + for (const [table, cols] of columns) { + const tableRows: Cell[][] = []; + for (let i = 0; i < rows; i++) { + tableRows.push([...cols].map(([column, ps]) => { + if (ps[0]!.steps.length === 0) { + const v = rnd() < 0.1 ? null : rnd() < 0.05 ? 7 : rnd() < 0.7 ? good() : pick(BAD_STRINGS); + return { column, stored: v, parsed: v, notJson: false }; + } + const r = rnd(); + if (r < 0.06) return { column, stored: null, parsed: null, notJson: false }; + if (r < 0.12) return { column, stored: pick(["not json", "mbr1,mbr2", "{bad"]), parsed: undefined, notJson: true }; + let doc: unknown; + for (const p of ps) doc = doc === undefined ? gen(p.steps) : merge(doc, gen(p.steps)); + return { column, stored: JSON.stringify(doc ?? null), parsed: doc ?? null, notJson: false }; + })); + } + out.set(table, tableRows); + } + return out; +} + +/** The oracle: how many values at `steps` inside `value` the write check would refuse. */ +function refused(value: unknown, steps: readonly UuidStep[]): number { + const plain = (x: unknown): x is Record => typeof x === "object" && x !== null && !Array.isArray(x); + const canonical = (x: unknown): boolean => typeof x === "string" && RE.test(x); + if (steps.length === 0) return value === undefined || value === null || canonical(value) ? 0 : 1; + const [s, ...rest] = steps as [UuidStep, ...UuidStep[]]; + if (s.kind === "member") return plain(value) ? refused(value[s.key], rest) : 0; + if (s.kind === "values") return plain(value) ? Object.values(value).reduce((n, v) => n + refused(v, rest), 0) : 0; + if (rest.length === 0) { + // A uuid list: a stored value that is not a list counts once; each non-canonical element counts. + if (value === undefined || value === null) return 0; + if (!Array.isArray(value)) return 1; + return value.filter((e) => !canonical(e)).length; + } + return Array.isArray(value) ? value.reduce((n, v) => n + refused(v, rest), 0) : 0; +} + +const pathOf = (steps: readonly UuidStep[]): string => + steps.length === 0 ? "" : `$${steps.map((s) => (s.kind === "member" ? `.${s.key}` : s.kind === "elements" ? "[*]" : ".*")).join("")}`; + +async function loadModel(): Promise { + const { root, errors } = await loadString(JSON.stringify(MODEL), "json"); + expect(errors).toEqual([]); + return root; +} + +/** Plant rows through `exec`, scan through `query`, and compare every place with the oracle. */ +async function differential( + create: (table: string, columns: string[], rows: (string | number | null)[][]) => Promise, + query: RowQuery, +): Promise { + const places = uuidPlacesOf(await loadModel()); + const planted = plant(places, 42, 120); + for (const [table, rows] of planted) await create(table, rows[0]!.map((c) => c.column), rows.map((r) => r.map((c) => c.stored))); + + const statements: string[] = []; + const results = await scanUuidPlaces(places, "sqlite", async (sql) => { + statements.push(sql); + return query(sql); + }); + // Read-only: every statement the scan sent is a SELECT. + for (const sql of statements) expect(sql.startsWith("SELECT ")).toBe(true); + + for (const p of places) { + const cells = planted.get(p.table)!.map((r) => r.find((c) => c.column === p.column)!); + const rootList = p.steps.length === 1 && p.steps[0]!.kind === "elements"; + const want = cells.reduce((n, c) => n + (c.notJson ? (rootList ? 1 : 0) : refused(c.parsed, p.steps)), 0); + const got = results.find((r) => r.table === p.table && r.column === p.column && (r.jsonPath ?? "") === pathOf(p.steps) && r.fields[0] === p.label); + expect({ place: `${p.table}.${p.column} ${pathOf(p.steps)}`, status: got?.status, reason: got?.reason, n: got?.nonCanonical }) + .toEqual({ place: `${p.table}.${p.column} ${pathOf(p.steps)}`, status: "scanned", reason: undefined, n: want }); + } + // Text that is not JSON in a value-object column: reported once per column as not read. + for (const [table, rows] of planted) { + for (const column of rows[0]!.map((c) => c.column)) { + const ps = places.filter((p) => p.table === table && p.column === column); + if (ps.every((p) => p.steps.length === 0 || (p.steps.length === 1 && p.steps[0]!.kind === "elements"))) continue; + const notJson = rows.filter((r) => r.find((c) => c.column === column)!.notJson).length; + const got = results.filter((r) => r.table === table && r.column === column && r.status === "unreadable"); + expect({ column: `${table}.${column}`, n: got[0]?.nonCanonical ?? 0, rows: got.length }).toEqual({ column: `${table}.${column}`, n: notJson, rows: notJson > 0 ? 1 : 0 }); + } + } + return results; +} + +describe("meta verify --uuid-values — the scan's SQL against an independent walk of planted values", () => { + test("bun:sqlite", async () => { + const db = new Database(":memory:"); + try { + const results = await differential(async (table, columns, rows) => { + db.run(`CREATE TABLE "${table}" (${columns.map((c) => `"${c}" TEXT`).join(", ")})`); + const insert = db.prepare(`INSERT INTO "${table}" VALUES (${columns.map(() => "?").join(", ")})`); + for (const row of rows) insert.run(...row); + }, async (sql) => db.query(sql).all() as Record[]); + expect(uuidVerdict(results)).toBe("found"); + } finally { + db.close(); + } + }); + + test("Cloudflare D1 (local runtime)", async () => { + const local = await startLocalD1(); + try { + const d1 = local.d1 as unknown as { + prepare(sql: string): { bind(...v: unknown[]): { run(): Promise }; all(): Promise<{ results?: Record[] }> }; + }; + const results = await differential(async (table, columns, rows) => { + await local.d1.exec(`CREATE TABLE "${table}" (${columns.map((c) => `"${c}" TEXT`).join(", ")})`); + for (const row of rows) await d1.prepare(`INSERT INTO "${table}" VALUES (${columns.map(() => "?").join(", ")})`).bind(...row).run(); + }, async (sql) => (await d1.prepare(sql).all()).results ?? []); + expect(uuidVerdict(results)).toBe("found"); + } finally { + await local.dispose(); + } + }, { timeout: 120_000 }); +}); diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 4aeca05731..2d6d235d0e 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -3974,7 +3974,7 @@ function physicalColumnsOf(field: MetaData): PhysicalColumn[] { if (field.subType === FIELD_SUBTYPE_OBJECT && field.attr(FIELD_ATTR_STORAGE) === STORAGE_FLATTENED) { const target = refTarget(field, FIELD_ATTR_OBJECT_REF); if (target === undefined || !isMetaObject(target)) return []; - // Every member, as migrate's flattenObjectField expands it. + // Every member, as migrate's storedTablesOf expands it. return target.fields().map((member) => ({ column: resolveFlattenedColumnName(field, member), label: `${field.name}.${member.name}`, diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 772ba8b758..62146a3a53 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -230,41 +230,20 @@ export interface ExpectedSchemaWithProvenance { foreignKeyIndexes?: ReadonlyMap; } -/** - * The expected schema as every existing caller wants it. Thin wrapper over - * {@link buildExpectedSchemaWithProvenance}; byte-identical output. - */ -export function buildExpectedSchema( - root: MetaData, - opts?: BuildExpectedSchemaOptions, -): SchemaSnapshot { - const built = buildExpectedSchemaWithProvenance(root, opts); - // No scope here: every FK whose target is not a unique key is refused. - if (built.fkTargetViolations !== undefined && built.fkTargetsUnenforced === undefined) { - throw new FkTargetNotUniqueError(built.fkTargetViolations); - } - return built.snapshot; -} +/** An object that owns a table: the entity and its resolved table name. */ +interface TableOwner { entity: MetaObject; tableName: string } /** - * The expected schema PLUS the declaring FQN of every table and view in it. - * - * Provenance is threaded out of the passes that already hold the declaring node — - * Pass 2 has each table's entity, Pass 4 each view's input — so there is exactly - * one walk and one set of skip rules. Callers that filter by scope - * (`scopeExpectedSchema`) consume it; callers that don't use the wrapper above. + * Pass 1 of the schema build: which objects own a table, and the table every object's rows + * live in. `entities` are the tables this build emits; `fkTargetOnly` are `@unmanaged` tables + * (no descriptor, still a table in the database); `byKey` maps every object that has rows — + * a table owner, or a TPH member folded into its base — to that table's name. */ -export function buildExpectedSchemaWithProvenance( - root: MetaData, - opts?: BuildExpectedSchemaOptions, -): ExpectedSchemaWithProvenance { - // D1 is SQLite at the SQL level; normalize it so downstream dialect checks - // don't need to handle "d1" separately. - const dialect = opts?.dialect === "d1" ? "sqlite" : opts?.dialect; - // ADR-0058: the project's one column rule, carried by the loaded root — the value codegen - // and every runtime read, so the schema and the code that addresses it cannot disagree. - const strategy: ColumnNamingStrategy = physicalNamingOf(root).columns; - +function collectTableOwners(root: MetaData): { + entities: TableOwner[]; + fkTargetOnly: TableOwner[]; + byKey: Map; +} { // Pass 1: collect entities + their resolved table names. // Skip: // - abstract objects (e.g., BaseEntity) @@ -272,13 +251,13 @@ export function buildExpectedSchemaWithProvenance( // - any object with no declared/inherited WRITABLE source (#248 — covers // value objects, projections, sourceless entities, and any sourceless // custom subtype uniformly; see the rule comment below) - const entities: { entity: MetaObject; tableName: string }[] = []; + const entities: TableOwner[] = []; // #208 §7 — entities whose physical name must still resolve for FK TARGETING even // though we emit NO TableDescriptor for them: an @unmanaged table (Flyway/hand- // migration owns its DDL). An FK from a managed table INTO a Flyway-owned table is // legal and needs the target's physical name; only the table's own create/alter/drop // is suppressed (migration ORDERING vs the external tool is a documented adopter caveat). - const fkTargetOnly: { entity: MetaObject; tableName: string }[] = []; + const fkTargetOnly: TableOwner[] = []; // FR-017 TPH: everything beneath a discriminator base — a concrete subtype, or an // abstract level in between — has no table of its own, but is still an FK TARGET: its // rows are in the base's table. Registered once the bases are known (below); skipping @@ -335,6 +314,157 @@ export function buildExpectedSchemaWithProvenance( for (const e of [...tableOwners, ...subtypeTargets]) { byKey.set(e.entity.resolutionKey(), e.tableName); } + return { entities, fkTargetOnly, byKey }; +} + +/** One stored field of a table: the column that holds it and the field that declares it. */ +export interface StoredField { + column: string; + field: MetaField; + /** The `Object.field` (or `Object.field.member`) path that names it in the model. */ + label: string; + /** Set for a member of a `@storage: flattened` value object: the field that holds the object. */ + flattenedIn?: MetaField; + /** Set for a column a TPH subtype adds to its base's table: the subtype. */ + subtype?: MetaObject; +} + +/** A table that stores an object's rows, whether or not `meta migrate` owns its DDL. */ +export interface StoredTable { + schema?: string; + table: string; + /** Resolution key of the object that owns the table. */ + owner: string; + /** The table's source is `@unmanaged`: `meta migrate` neither creates nor alters it. */ + unmanaged: boolean; + fields: StoredField[]; +} + +/** + * Every table the model stores rows in, with the field behind each column. This is the layout + * {@link buildExpectedSchema} turns into DDL, minus everything DDL needs and a reader does not: + * it takes no dialect, builds no index, check or foreign key, refuses nothing, and it includes + * `@unmanaged` tables. A tool that reads stored values (not one that owns the schema) starts here. + */ +export function storedTablesOf(root: MetaData): StoredTable[] { + const strategy: ColumnNamingStrategy = physicalNamingOf(root).columns; + const { entities, fkTargetOnly } = collectTableOwners(root); + const one = ({ entity, tableName }: TableOwner, unmanaged: boolean): StoredTable => { + const schema = resolveTableSchema(entity); + return { + ...(schema !== undefined ? { schema } : {}), + table: tableName, + owner: entity.resolutionKey(), + unmanaged, + fields: storedFieldsOf(entity, root as MetaRoot, strategy), + }; + }; + return [...entities.map((e) => one(e, false)), ...fkTargetOnly.map((e) => one(e, true))]; +} + +/** + * The fields a table stores, in column order: the owner's effective fields (a flattened value + * object contributes one column per member, and no column of its own), then, for a TPH + * discriminator base, each concrete subtype's further fields. A derived field is never stored. + * The one definition of "which column holds which field": {@link buildTable} builds its + * columns from it. + */ +function storedFieldsOf(entity: MetaObject, root: MetaRoot, strategy: ColumnNamingStrategy): StoredField[] { + const out: StoredField[] = []; + for (const field of entity.fields()) { + // #213 — a derived (origin-bearing) field is read-only and lives only on the + // read (view) side (FR-024 §7 / ADR-0028); it is NOT a physical column on the + // entity's write table. Excluding it here stops the leak that put a joined + // passthrough onto the write table (and collided with a hand-written + // `SELECT o.*, extra` view's alias). + if (field.isDerived()) continue; + const label = `${entity.name}.${field.name}`; + if ( + field.subType === FIELD_SUBTYPE_OBJECT && + // ADR-0039: resolving — @storage may be inherited via extends. + field.attr(FIELD_ATTR_STORAGE) === STORAGE_FLATTENED + ) { + // Flattened storage: expand nested value-object fields as prefixed columns. + // The parent field.object itself does NOT produce its own column. + // ADR-0039: resolving — @objectRef may be inherited via extends. + const targetObject = refTarget(field, FIELD_ATTR_OBJECT_REF); + if (targetObject === undefined || !isMetaObject(targetObject)) continue; + for (const nested of targetObject.fields()) { + out.push({ + column: resolveFlattenedColumnName(field, nested, strategy), + field: nested, + label: `${label}.${nested.name}`, + flattenedIn: field, + }); + } + } else { + out.push({ column: resolveColumnName(field, strategy), field, label }); + } + } + + // FR-017 TPH: if this is a discriminator base, fold each concrete subtype's + // OWN fields into the single table. Dedupe by column name so an + // inherited/overridden base column is not re-emitted. + // ADR-0039: effective attr — @discriminator may be inherited (deep TPH base). + if (entity.attr(OBJECT_ATTR_DISCRIMINATOR) !== undefined) { + const existing = new Set(out.map((c) => c.column)); + const baseFieldNames = new Set(entity.fields().map((f) => f.name)); + for (const sub of tphConcreteSubtypes(entity, root)) { + // ADR-0039: effective fields — a field declared on an ABSTRACT intermediate level + // (Party → abstract Organization → Carrier) is a column of this table too, and + // only the resolving view reaches it. Reading the subtype's own children dropped + // it, while codegen's `collectTphSubtypeFields` folds it: a Drizzle column with no + // DDL behind it. Base fields are already emitted above, so they are skipped. + for (const field of sub.fields()) { + if (baseFieldNames.has(field.name)) continue; + // #213 — a TPH subtype's derived field is read-only too; never a column. + if (field.isDerived()) continue; + const column = resolveColumnName(field, strategy); + if (existing.has(column)) continue; + out.push({ column, field, label: `${sub.name}.${field.name}`, subtype: sub }); + existing.add(column); + } + } + } + return out; +} + +/** + * The expected schema as every existing caller wants it. Thin wrapper over + * {@link buildExpectedSchemaWithProvenance}; byte-identical output. + */ +export function buildExpectedSchema( + root: MetaData, + opts?: BuildExpectedSchemaOptions, +): SchemaSnapshot { + const built = buildExpectedSchemaWithProvenance(root, opts); + // No scope here: every FK whose target is not a unique key is refused. + if (built.fkTargetViolations !== undefined && built.fkTargetsUnenforced === undefined) { + throw new FkTargetNotUniqueError(built.fkTargetViolations); + } + return built.snapshot; +} + +/** + * The expected schema PLUS the declaring FQN of every table and view in it. + * + * Provenance is threaded out of the passes that already hold the declaring node — + * Pass 2 has each table's entity, Pass 4 each view's input — so there is exactly + * one walk and one set of skip rules. Callers that filter by scope + * (`scopeExpectedSchema`) consume it; callers that don't use the wrapper above. + */ +export function buildExpectedSchemaWithProvenance( + root: MetaData, + opts?: BuildExpectedSchemaOptions, +): ExpectedSchemaWithProvenance { + // D1 is SQLite at the SQL level; normalize it so downstream dialect checks + // don't need to handle "d1" separately. + const dialect = opts?.dialect === "d1" ? "sqlite" : opts?.dialect; + // ADR-0058: the project's one column rule, carried by the loaded root — the value codegen + // and every runtime read, so the schema and the code that addresses it cannot disagree. + const strategy: ColumnNamingStrategy = physicalNamingOf(root).columns; + + const { entities, byKey } = collectTableOwners(root); const resolveTargetTable = (target: MetaObject): string | undefined => byKey.get(target.resolutionKey()); // Provenance: qualified physical name → declaring object's FQN. Recorded as the @@ -666,69 +796,35 @@ function buildTable( }); const columns: ColumnDescriptor[] = []; - for (const field of entity.fields()) { - // #213 — a derived (origin-bearing) field is read-only and lives only on the - // read (view) side (FR-024 §7 / ADR-0028); it is NOT a physical column on the - // entity's write table. Excluding it here stops the leak that put a joined - // passthrough onto the write table (and collided with a hand-written - // `SELECT o.*, extra` view's alias). - if (field.isDerived()) continue; - const isPk = pkJsNames.includes(field.name); - if ( - field.subType === FIELD_SUBTYPE_OBJECT && - // ADR-0039: resolving — @storage may be inherited via extends. - field.attr(FIELD_ATTR_STORAGE) === STORAGE_FLATTENED - ) { - // Flattened storage: expand nested value-object fields as prefixed columns. - // The parent field.object itself does NOT produce its own column. - columns.push(...flattenObjectField(field, strategy)); + for (const stored of storedFieldsOf(entity, root, strategy)) { + const { field } = stored; + if (stored.subtype !== undefined) { + const col = buildColumn(field, false, undefined, strategy); + // Subtype-only columns are always nullable in TPH: a row of any OTHER + // subtype stores NULL here. A DB DEFAULT defeats exactly that — a sibling + // subtype's INSERT omits the column and silently takes the default instead + // of NULL — so the default is dropped for the same reason the NOT NULL is. + // This mirrors codegen's `forceNullable` (drizzle-schema.ts), which already + // suppresses both; without it migrate puts a DEFAULT in the database that + // the app's Drizzle schema does not know about, and `verify --db` cannot + // see the disagreement because it shares this expected schema. + col.nullable = true; + // `delete`, not `= undefined`: the descriptor's `default` is an OPTIONAL + // property and this package compiles with exactOptionalPropertyTypes, under + // which assigning undefined is a type error (TS2412). `bun test` transpiles + // per-file without typechecking, so that mistake passes the whole suite. + delete col.default; + columns.push(col); + } else if (stored.flattenedIn !== undefined) { + columns.push({ ...buildColumn(field, /* isPk */ false, /* pkGeneration */ undefined, strategy), name: stored.column }); } else { + const isPk = pkJsNames.includes(field.name); const col = buildColumn(field, isPk, isPk ? pkGeneration : undefined, strategy); if (isPk && pkGeneration === "increment" && pkIdentity !== undefined) applyDeclaredSequence(col, pkIdentity); columns.push(col); } } - // FR-017 TPH: if this is a discriminator base, fold each concrete subtype's - // OWN fields into the single table as NULLABLE columns (a row of any other - // subtype stores NULL there), even when the field is @required. Dedupe by - // column name so an inherited/overridden base column is not re-emitted. - // ADR-0039: effective attr — @discriminator may be inherited (deep TPH base). - if (entity.attr(OBJECT_ATTR_DISCRIMINATOR) !== undefined) { - const existing = new Set(columns.map((c) => c.name)); - const baseFieldNames = new Set(entity.fields().map((f) => f.name)); - for (const sub of tphConcreteSubtypes(entity, root)) { - // ADR-0039: effective fields — a field declared on an ABSTRACT intermediate level - // (Party → abstract Organization → Carrier) is a column of this table too, and - // only the resolving view reaches it. Reading the subtype's own children dropped - // it, while codegen's `collectTphSubtypeFields` folds it: a Drizzle column with no - // DDL behind it. Base fields are already emitted above, so they are skipped. - for (const field of sub.fields()) { - if (baseFieldNames.has(field.name)) continue; - // #213 — a TPH subtype's derived field is read-only too; never a column. - if (field.isDerived()) continue; - const col = buildColumn(field, false, undefined, strategy); - if (existing.has(col.name)) continue; - // Subtype-only columns are always nullable in TPH: a row of any OTHER - // subtype stores NULL here. A DB DEFAULT defeats exactly that — a sibling - // subtype's INSERT omits the column and silently takes the default instead - // of NULL — so the default is dropped for the same reason the NOT NULL is. - // This mirrors codegen's `forceNullable` (drizzle-schema.ts), which already - // suppresses both; without it migrate puts a DEFAULT in the database that - // the app's Drizzle schema does not know about, and `verify --db` cannot - // see the disagreement because it shares this expected schema. - col.nullable = true; - // `delete`, not `= undefined`: the descriptor's `default` is an OPTIONAL - // property and this package compiles with exactOptionalPropertyTypes, under - // which assigning undefined is a type error (TS2412). `bun test` transpiles - // per-file without typechecking, so that mistake passes the whole suite. - delete col.default; - columns.push(col); - existing.add(col.name); - } - } - } - const descriptor: TableDescriptor = { name: tableName, columns, @@ -1694,27 +1790,6 @@ export function uncoveredForeignKeyColumns(t: Pick ({ - ...buildColumn(nested, /* isPk */ false, /* pkGeneration */ undefined, strategy), - name: resolveFlattenedColumnName(field, nested, strategy), - })); -} - /** * `@default: "now"`: the current time. Not a literal, because Postgres converts the literal * `'now'` to a timestamp once, when the column's DEFAULT is created, and every row then gets the diff --git a/server/typescript/packages/migrate-ts/src/index.ts b/server/typescript/packages/migrate-ts/src/index.ts index 1a7f07923b..6f92a4bdfe 100644 --- a/server/typescript/packages/migrate-ts/src/index.ts +++ b/server/typescript/packages/migrate-ts/src/index.ts @@ -8,7 +8,7 @@ // See docs/specs/2026-05-11-v0.2-sp4-migrate-ts-design.md. // Pipeline functions -export { buildExpectedSchema, buildExpectedSchemaWithProvenance, foreignKeyIndexName, uncoveredForeignKeyColumns } from "./expected-schema.js"; +export { buildExpectedSchema, buildExpectedSchemaWithProvenance, foreignKeyIndexName, uncoveredForeignKeyColumns, storedTablesOf, type StoredField, type StoredTable } from "./expected-schema.js"; export { findReferentialActionConflict, describeReferentialActionConflict, From 5e5c0d86b12d0b871ae13a1cf951de7998abb014 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 20:52:43 -0500 Subject: [PATCH 4/7] no-mistakes(review): Read TPH sibling fields; skip uuid-free recursion --- CHANGELOG.md | 9 +- docs/features/migrations-and-drift.md | 7 +- .../packages/cli/src/lib/uuid-values-check.ts | 167 ++++++++++++------ .../cli/test/verify-uuid-values.test.ts | 129 +++++++++++++- .../test/uuid-values-scan.test.ts | 2 +- .../migrate-ts/src/expected-schema.ts | 49 ++++- 6 files changed, 288 insertions(+), 75 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e469fd03f9..a4b93828a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,14 +20,17 @@ here.** flattened value object's members are read in their own columns, and a member that is itself an object or a map is read inside its JSON column. Which column holds which field comes from the same code `meta migrate` lays out its columns with, so a TPH subtype's flattened value object is read in - the one JSON column migrate gives it. Each place is named by its column and JSON path + the one JSON column migrate gives it. TPH sibling subtypes that declare different fields on one + column are each read, in the rows whose discriminator names a subtype declaring that field, so a + `field.string` sibling's values are not reported. Each place is named by its column and JSON path (`claims.meta $.memberId`); for each one holding values that are not canonical 8-4-4-4-12 uuids, such as `"mbr1"` on SQLite or D1, it gives the count and up to five samples, and it exits 1 when it finds any. A native Postgres `uuid` or `uuid[]` column is reported as guaranteed and not read. Every place ends as scanned, native, missing (the table or column is not in this database) or unreadable (the read failed, the column type cannot hold the value, the stored text is not JSON, - or a value object contains itself), and the check passes only when every place was read: any - missing or unreadable place makes the run incomplete, names the place and its reason, and exits 1. + or a value object that holds a `field.uuid` contains itself), and the check passes only when + every place was read: any missing or unreadable place makes the run incomplete, names the place + and its reason, and exits 1. It does not read a `field.map @valueType: uuid` or an object with no `@objectRef` (the write check does not check either as a uuid), or views. The SQLite and D1 queries stay inside D1's limits (a GLOB pattern of 50 bytes, one JSON path per run of member keys). The check never writes. A diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index e2cd6ec4b6..a6d950909a 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -822,7 +822,10 @@ check follows the nesting the write check validates: - each value of a `field.map` of value objects; - a flattened value object's members: a uuid member is its own column, and a member that is itself an object or a map is read inside its JSON column. A flattened value object declared on a TPH - subtype is one JSON column, as migrate stores it. + subtype is one JSON column, as migrate stores it; +- a column that TPH sibling subtypes each declare with a different field: every field is followed, + and where only some siblings put a uuid at a place, only the rows whose discriminator names one of + those subtypes are read, so a sibling's `field.string` values are not reported. Each place is reported with its column and JSON path, for example `claims.meta $.memberId`, `claims.history $[*].tagIds[*]` or `claims.by_region $.*.regionId`, with the count of values that @@ -839,7 +842,7 @@ Every place ends in one status: | scanned | every stored value was read | yes | | native | a Postgres `uuid` or `uuid[]` column: the database stores nothing else | yes | | missing | the table or the column is not in this database | no | -| unreadable | the read failed, the column type cannot hold what the model says (a value object in a Postgres column that is not `json`/`jsonb`), the stored SQLite text is not JSON, or a value object contains itself | no | +| unreadable | the read failed, the column type cannot hold what the model says (a value object in a Postgres column that is not `json`/`jsonb`), the stored SQLite text is not JSON, or a value object that holds a `field.uuid` contains itself (one with no `field.uuid` inside is no place at all) | no | The check exits 1 when it finds a value that is not canonical. It passes only when every place was read: a missing or unreadable place makes the run incomplete, exits 1 and is listed with its reason diff --git a/server/typescript/packages/cli/src/lib/uuid-values-check.ts b/server/typescript/packages/cli/src/lib/uuid-values-check.ts index 068d356e6d..52cc26ab97 100644 --- a/server/typescript/packages/cli/src/lib/uuid-values-check.ts +++ b/server/typescript/packages/cli/src/lib/uuid-values-check.ts @@ -26,8 +26,9 @@ import { refTarget, type MetaData, type MetaField, + type MetaObject, } from "@metaobjectsdev/metadata"; -import { storedTablesOf } from "@metaobjectsdev/migrate-ts"; +import { storedTablesOf, type StoredField } from "@metaobjectsdev/migrate-ts"; /** The canonical shape the 1.3 write check accepts: 8-4-4-4-12 hex digits, either case. */ export const CANONICAL_UUID_PATTERN = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"; @@ -48,10 +49,15 @@ export interface UuidPlace { column: string; /** Empty: the column stores the uuid itself. Otherwise the walk into the column's JSON. */ steps: UuidStep[]; - /** `Object.field[.member…]`, as the model names it. */ - label: string; + /** `Object.field[.member…]` for every field stored at this place, as the model names it. */ + labels: string[]; /** The table's source is `@unmanaged`: reported, never a reason to skip. */ unmanaged: boolean; + /** + * Set when only some rows hold this place: TPH sibling subtypes that declare different fields + * on one column. Only rows whose discriminator column holds one of `values` are read. + */ + rows?: { column: string; values: string[] }; /** Set when the walk stopped early: a value object that contains itself. */ truncated?: string; } @@ -87,44 +93,89 @@ export type UuidScanDialect = "postgres" | "sqlite"; export function uuidPlacesOf(root: MetaData): UuidPlace[] { const places: UuidPlace[] = []; for (const t of storedTablesOf(root)) { - const at = (column: string, steps: UuidStep[], label: string, truncated?: string): void => { - places.push({ - ...(t.schema !== undefined ? { schema: t.schema } : {}), - table: t.table, - column, - steps, - label, - unmanaged: t.unmanaged, - ...(truncated !== undefined ? { truncated } : {}), - }); + // One place per column and path; `values` is undefined when every row holds it, else the + // discriminator values of the subtypes whose field puts it there. + const found = new Map | undefined }>(); + const visitStored = (stored: StoredField): void => { + const at = (steps: UuidStep[], label: string, truncated?: string): void => { + const key = `${stored.column}\u0000${jsonPathOf(steps) ?? ""}`; + const existing = found.get(key); + if (existing === undefined) { + found.set(key, { + place: { + ...(t.schema !== undefined ? { schema: t.schema } : {}), + table: t.table, + column: stored.column, + steps, + labels: [label], + unmanaged: t.unmanaged, + ...(truncated !== undefined ? { truncated } : {}), + }, + values: stored.subtypes === undefined ? undefined : new Set(stored.subtypes.map((s) => s.value)), + }); + return; + } + if (!existing.place.labels.includes(label)) existing.place.labels.push(label); + if (stored.subtypes === undefined) existing.values = undefined; + else for (const s of stored.subtypes) existing.values?.add(s.value); + }; + const visit = (field: MetaField, steps: UuidStep[], label: string, seen: ReadonlySet): void => { + const list: UuidStep[] = field.resolvedIsArray() ? [{ kind: "elements" }] : []; + if (field.subType === FIELD_SUBTYPE_UUID) { + at([...steps, ...list], label); + return; + } + const vo = valueObjectOf(field); + if (vo === undefined) return; + const inner: UuidStep[] = field.subType === FIELD_SUBTYPE_OBJECT ? [...steps, ...list] : [...steps, { kind: "values" }]; + if (seen.has(vo)) { + if (reachesUuid(vo, new Set([vo]))) at(inner, label, `value object ${vo.name} contains itself; read to this depth only`); + return; + } + const deeper = new Set([...seen, vo]); + for (const member of vo.fields()) { + visit(member, [...inner, { kind: "member", key: member.name }], `${label}.${member.name}`, deeper); + } + }; + visit(stored.field, [], stored.label, new Set()); }; - const visit = (field: MetaField, column: string, steps: UuidStep[], label: string, seen: ReadonlySet): void => { - const list: UuidStep[] = field.resolvedIsArray() ? [{ kind: "elements" }] : []; - if (field.subType === FIELD_SUBTYPE_UUID) { - at(column, [...steps, ...list], label); - return; - } - const isObject = field.subType === FIELD_SUBTYPE_OBJECT; - if (!isObject && field.subType !== FIELD_SUBTYPE_MAP) return; - // ADR-0039: resolving — @objectRef may be inherited via extends. - const vo = refTarget(field, FIELD_ATTR_OBJECT_REF); - // No value object: an open JSON bag or a map of scalars holds no position typed field.uuid. - if (vo === undefined || !isMetaObject(vo)) return; - const inner: UuidStep[] = isObject ? [...steps, ...list] : [...steps, { kind: "values" }]; - if (seen.has(vo)) { - at(column, inner, label, `value object ${vo.name} contains itself; read to this depth only`); - return; - } - const deeper = new Set([...seen, vo]); - for (const member of vo.fields()) { - visit(member, column, [...inner, { kind: "member", key: member.name }], `${label}.${member.name}`, deeper); + for (const f of t.fields) visitStored(f); + + // Every discriminator value that stores some field in a column. + const carriers = new Map>(); + for (const f of t.fields) { + for (const s of f.subtypes ?? []) carriers.set(f.column, (carriers.get(f.column) ?? new Set()).add(s.value)); + } + for (const { place, values } of found.values()) { + if (values !== undefined && t.discriminatorColumn !== undefined && values.size < (carriers.get(place.column)?.size ?? 0)) { + place.rows = { column: t.discriminatorColumn, values: [...values].sort() }; } - }; - for (const f of t.fields) visit(f.field, f.column, [], f.label, new Set()); + places.push(place); + } } return places; } +/** The value object a `field.object` or `field.map` holds, or undefined for any other field. */ +function valueObjectOf(field: MetaField): MetaObject | undefined { + if (field.subType !== FIELD_SUBTYPE_OBJECT && field.subType !== FIELD_SUBTYPE_MAP) return undefined; + // ADR-0039: resolving — @objectRef may be inherited via extends. + const vo = refTarget(field, FIELD_ATTR_OBJECT_REF); + // No value object: an open JSON bag or a map of scalars holds no position typed field.uuid. + return vo !== undefined && isMetaObject(vo) ? vo : undefined; +} + +/** Whether a `field.uuid` sits anywhere inside `vo`, at any depth. */ +function reachesUuid(vo: MetaObject, seen: Set): boolean { + return vo.fields().some((member) => { + if (member.subType === FIELD_SUBTYPE_UUID) return true; + const inner = valueObjectOf(member); + if (inner === undefined || seen.has(inner)) return false; + seen.add(inner); + return reachesUuid(inner, seen); + }); +} + /** `$.meta[*].ownerId` — how a finding names a position inside a JSON column. */ function jsonPathOf(steps: readonly UuidStep[]): string | undefined { if (steps.length === 0) return undefined; @@ -145,12 +196,19 @@ function sqliteIsCanonical(v: string, type: string): string { `AND ${v} NOT GLOB '*[^0-9a-fA-F-]*')`; } +/** ` AND IN (…)` when only some rows hold the place; empty when every row does. */ +function rowsOnly(place: UuidPlace, discriminator: (column: string) => string): string { + if (place.rows === undefined) return ""; + return ` AND ${discriminator(ident(place.rows.column))} IN (${place.rows.values.map(literal).join(", ")})`; +} + /** One row per stored value at the place that is not a canonical uuid, on SQLite or D1. */ function sqliteOffenders(place: UuidPlace): string { const table = ident(place.table); const column = `${table}.${ident(place.column)}`; + const only = rowsOnly(place, (c) => `CAST(${table}.${c} AS TEXT)`); if (place.steps.length === 0) { - return `SELECT CAST(${column} AS TEXT) AS v FROM ${table} WHERE ${column} IS NOT NULL AND NOT ${sqliteIsCanonical(column, `typeof(${column})`)}`; + return `SELECT CAST(${column} AS TEXT) AS v FROM ${table} WHERE ${column} IS NOT NULL AND NOT ${sqliteIsCanonical(column, `typeof(${column})`)}${only}`; } // The column holds JSON text. `doc` is the JSON value the walk stands in (NULL when there is // none to read), `path` the run of member keys not yet applied to it: one json_* call per run, @@ -176,22 +234,22 @@ function sqliteOffenders(place: UuidPlace): string { // A uuid member: absent or JSON null is not a value; anything else must be canonical. const v = `json_extract(${doc}, ${literal(path)})`; const t = `json_type(${doc}, ${literal(path)})`; - return `SELECT CAST(${v} AS TEXT) AS v FROM ${from.join(", ")} WHERE ${t} <> 'null' AND NOT ${sqliteIsCanonical(v, t)}`; + return `SELECT CAST(${v} AS TEXT) AS v FROM ${from.join(", ")} WHERE ${t} <> 'null' AND NOT ${sqliteIsCanonical(v, t)}${only}`; } // A uuid list: a stored value that is not a list at all, then each element (a JSON null too). const atRoot = from.length === 1 && path === "$"; const notAList = atRoot - ? `SELECT CAST(${column} AS TEXT) AS v FROM ${table} WHERE ${column} IS NOT NULL AND CASE WHEN json_valid(${column}) THEN json_type(${column}) NOT IN ('array', 'null') ELSE 1 END` - : `SELECT CAST(json_extract(${doc}, ${literal(path)}) AS TEXT) AS v FROM ${from.join(", ")} WHERE json_type(${doc}, ${literal(path)}) NOT IN ('array', 'null')`; + ? `SELECT CAST(${column} AS TEXT) AS v FROM ${table} WHERE ${column} IS NOT NULL AND CASE WHEN json_valid(${column}) THEN json_type(${column}) NOT IN ('array', 'null') ELSE 1 END${only}` + : `SELECT CAST(json_extract(${doc}, ${literal(path)}) AS TEXT) AS v FROM ${from.join(", ")} WHERE json_type(${doc}, ${literal(path)}) NOT IN ('array', 'null')${only}`; const e = each("array"); - return `SELECT COALESCE(CAST(${e}.value AS TEXT), 'null') AS v FROM ${from.join(", ")} WHERE NOT ${sqliteIsCanonical(`${e}.value`, `${e}.type`)} UNION ALL ${notAList}`; + return `SELECT COALESCE(CAST(${e}.value AS TEXT), 'null') AS v FROM ${from.join(", ")} WHERE NOT ${sqliteIsCanonical(`${e}.value`, `${e}.type`)}${only} UNION ALL ${notAList}`; } /** Rows whose stored text is not JSON at all: the uuids inside could not be read. */ -function sqliteUnparsable(table: string, column: string): string { - const t = ident(table); - const c = `${t}.${ident(column)}`; - return `SELECT CAST(${c} AS TEXT) AS v FROM ${t} WHERE ${c} IS NOT NULL AND NOT json_valid(${c})`; +function sqliteUnparsable(place: UuidPlace): string { + const t = ident(place.table); + const c = `${t}.${ident(place.column)}`; + return `SELECT CAST(${c} AS TEXT) AS v FROM ${t} WHERE ${c} IS NOT NULL AND NOT json_valid(${c})${rowsOnly(place, (d) => `CAST(${t}.${d} AS TEXT)`)}`; } /** How Postgres stores the place: decided from the column's real type, never from the model. */ @@ -201,16 +259,17 @@ function postgresPlan(place: UuidPlace, typname: string): PgPlan { const table = place.schema !== undefined ? `${ident(place.schema)}.${ident(place.table)}` : ident(place.table); const column = `t.${ident(place.column)}`; const pattern = literal(CANONICAL_UUID_PATTERN); + const only = rowsOnly(place, (c) => `t.${c}::text`); if (place.steps.length === 0) { // A native uuid column holds nothing else. if (typname === "uuid") return { native: true }; - return { sql: `SELECT ${column}::text AS v FROM ${table} AS t WHERE ${column} IS NOT NULL AND ${column}::text !~ ${pattern}` }; + return { sql: `SELECT ${column}::text AS v FROM ${table} AS t WHERE ${column} IS NOT NULL AND ${column}::text !~ ${pattern}${only}` }; } const rootList = place.steps.length === 1 && place.steps[0]?.kind === "elements"; if (rootList && typname === "_uuid") return { native: true }; if (rootList && typname.startsWith("_")) { // A null element counts: the write check refuses it. - return { sql: `SELECT COALESCE(e.v::text, 'null') AS v FROM ${table} AS t CROSS JOIN LATERAL unnest(${column}) AS e(v) WHERE e.v IS NULL OR e.v::text !~ ${pattern}` }; + return { sql: `SELECT COALESCE(e.v::text, 'null') AS v FROM ${table} AS t CROSS JOIN LATERAL unnest(${column}) AS e(v) WHERE (e.v IS NULL OR e.v::text !~ ${pattern})${only}` }; } if (typname !== "jsonb" && typname !== "json") { return { unreadable: `column type ${typname} is not json or jsonb: the value inside it cannot be read` }; @@ -234,11 +293,11 @@ function postgresPlan(place: UuidPlace, typname: string): PgPlan { const source = (): string => [`${table} AS t`, ...joins].join(" "); const offending = (x: string): string => `(jsonb_typeof(${x}) <> 'string' OR ${x} #>> '{}' !~ ${pattern})`; if (!leafList) { - return { sql: `SELECT ${v} #>> '{}' AS v FROM ${source()} WHERE jsonb_typeof(${v}) <> 'null' AND ${offending(v)}` }; + return { sql: `SELECT ${v} #>> '{}' AS v FROM ${source()} WHERE jsonb_typeof(${v}) <> 'null' AND ${offending(v)}${only}` }; } - const notAList = `SELECT ${v}::text AS v FROM ${source()} WHERE jsonb_typeof(${v}) NOT IN ('array', 'null')`; + const notAList = `SELECT ${v}::text AS v FROM ${source()} WHERE jsonb_typeof(${v}) NOT IN ('array', 'null')${only}`; each("array"); - return { sql: `SELECT COALESCE(${v} #>> '{}', 'null') AS v FROM ${source()} WHERE ${offending(v)} UNION ALL ${notAList}` }; + return { sql: `SELECT COALESCE(${v} #>> '{}', 'null') AS v FROM ${source()} WHERE ${offending(v)}${only} UNION ALL ${notAList}` }; } const message = (err: unknown): string => (err instanceof Error ? err.message : String(err)); @@ -294,7 +353,7 @@ export async function scanUuidPlaces( table: p.table, column: p.column, ...(jsonPath !== undefined ? { jsonPath } : {}), - fields: [p.label], + fields: p.labels, unmanaged: p.unmanaged, }; const none = { nonCanonical: 0, samples: [] as string[] }; @@ -333,17 +392,17 @@ export async function scanUuidPlaces( sql = sqliteOffenders(p); // A root uuid list reports text that is not JSON as a finding; anything deeper cannot read it. const rootList = p.steps.length === 1 && p.steps[0]?.kind === "elements"; - const colKey = `${p.table}\u0000${p.column}`; + const colKey = `${p.table}\u0000${p.column}\u0000${p.rows?.values.join("\u0000") ?? ""}`; if (p.steps.length > 0 && !rootList && !parsedColumns.has(colKey)) { parsedColumns.add(colKey); - const bad = await countAndSample(sqliteUnparsable(p.table, p.column)); + const bad = await countAndSample(sqliteUnparsable(p)); if (bad.nonCanonical > 0) { - const names = p.label.split("."); const memberSteps = p.steps.filter((s) => s.kind === "member").length; + const fieldOf = (label: string): string => label.split(".").slice(0, label.split(".").length - memberSteps).join("."); results.push({ table: p.table, column: p.column, - fields: [names.slice(0, names.length - memberSteps).join(".")], + fields: [...new Set(p.labels.map(fieldOf))], unmanaged: p.unmanaged, status: "unreadable", reason: "stored text is not JSON: the uuids inside could not be read", diff --git a/server/typescript/packages/cli/test/verify-uuid-values.test.ts b/server/typescript/packages/cli/test/verify-uuid-values.test.ts index 93aebbdc65..716da3591c 100644 --- a/server/typescript/packages/cli/test/verify-uuid-values.test.ts +++ b/server/typescript/packages/cli/test/verify-uuid-values.test.ts @@ -20,6 +20,7 @@ import { defineConfig } from "../src/index.js"; import { scanUuidPlaces, uuidPlacesOf, uuidValuesReport, uuidVerdict, type UuidPlace } from "../src/lib/uuid-values-check.js"; import { parseVerifyArgs } from "../src/lib/args.js"; import { loadMemory } from "@metaobjectsdev/sdk"; +import { buildExpectedSchema } from "@metaobjectsdev/migrate-ts"; const dirs: string[] = []; afterAll(async () => { for (const d of dirs) await rm(d, { recursive: true, force: true }); }); @@ -165,9 +166,10 @@ const KITCHEN = { "metadata.root": { package: "acme", children: [ ] } }, ] } }; -/** A place as `table.column $path Label`, for comparing enumerations. */ +/** A place as `table.column $path Labels`, for comparing enumerations. */ const placeKey = (p: UuidPlace): string => - `${p.table}.${p.column}${p.steps.length > 0 ? ` $${p.steps.map((s) => (s.kind === "member" ? `.${s.key}` : s.kind === "elements" ? "[*]" : ".*")).join("")}` : ""} ${p.label}${p.unmanaged ? " @unmanaged" : ""}`; + `${p.table}.${p.column}${p.steps.length > 0 ? ` $${p.steps.map((s) => (s.kind === "member" ? `.${s.key}` : s.kind === "elements" ? "[*]" : ".*")).join("")}` : ""} ${p.labels.join(",")}` + + `${p.unmanaged ? " @unmanaged" : ""}${p.rows !== undefined ? ` [${p.rows.column} in ${p.rows.values.join(",")}]` : ""}`; describe("meta verify --uuid-values — which places it reads", () => { test("every field.uuid column: keys, foreign keys and lists; never a field.string, even one stored as uuid", async () => { @@ -277,14 +279,14 @@ describe("meta verify --uuid-values — which places it reads", () => { // A subtype's schema repeats its base's fields, which are the base's places. const written = [...checked].filter((p) => !(p.startsWith("Person.") && checked.has(`Party.${p.slice("Person.".length)}`))); // The same notation for a place: a flattened member is a row key (home.placeId is homePlaceId). - const scanned = uuidPlacesOf(loaded).map((p) => { - const names = p.label.split("."); + const scanned = uuidPlacesOf(loaded).flatMap((p) => p.labels.map((label) => { + const names = label.split("."); const flat = names.length - 2 - p.steps.filter((s) => s.kind === "member").length; let out = `${names[0]}.${names.slice(1, 2 + flat).map((n, k) => (k === 0 ? n : `${n[0]!.toUpperCase()}${n.slice(1)}`)).join("")}`; let i = 2 + flat; for (const s of p.steps) out += s.kind === "member" ? `.${names[i++]}` : s.kind === "elements" ? "[*]" : ".*"; return out; - }); + })); expect(written.length).toBeGreaterThan(20); expect(scanned.sort()).toEqual(written.sort()); }); @@ -308,7 +310,7 @@ describe("meta verify --uuid-values — which places it reads", () => { "trees.top $.kids[*] Tree.top.kids", "trees.top $.nodeId Tree.top.nodeId", ]); - expect(places.find((p) => p.label === "Tree.top.kids")?.truncated).toContain("contains itself"); + expect(places.find((p) => p.labels.includes("Tree.top.kids"))?.truncated).toContain("contains itself"); const file = join(root, "trees.db"); const db = new Database(file); @@ -322,6 +324,34 @@ describe("meta verify --uuid-values — which places it reads", () => { expect(out).not.toContain("every stored field.uuid value is canonical"); }); + test("a value object that contains itself with no field.uuid inside is no place: nothing to scan", async () => { + const root = await project({ "metadata.root": { package: "acme", children: [ + { "object.value": { name: "MenuItem", children: [ + { "field.string": { name: "label" } }, + { "field.object": { name: "children", "@objectRef": "MenuItem", isArray: true } }, + ] } }, + // Mutual recursion, one way through a map of value objects. + { "object.value": { name: "Left", children: [{ "field.object": { name: "right", "@objectRef": "Right" } }] } }, + { "object.value": { name: "Right", children: [{ "field.map": { name: "lefts", "@objectRef": "Left" } }] } }, + { "object.entity": { name: "Menu", children: [ + { "source.rdb": { "@table": "menus" } }, + { "field.long": { name: "id" } }, + { "field.object": { name: "root", "@objectRef": "MenuItem" } }, + { "field.object": { name: "pair", "@objectRef": "Left" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + ] } }); + expect(uuidPlacesOf(await loadMemory(root))).toEqual([]); + const file = join(root, "menus.db"); + const db = new Database(file); + db.run("CREATE TABLE menus (id INTEGER PRIMARY KEY, root TEXT, pair TEXT)"); + db.close(); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); + expect(code).toBe(0); + expect(out).toContain("this model declares no stored field.uuid; nothing to scan"); + expect(out).not.toContain("NOT READ"); + }); + test("--uuid-values without a database is refused at parse time", () => { expect(() => parseVerifyArgs(["--uuid-values"])).toThrow(/--uuid-values reads a database/); expect(parseVerifyArgs(["--uuid-values", "--dialect", "d1"]).uuidValues).toBe(true); @@ -513,6 +543,60 @@ describe("meta verify --uuid-values — SQLite", () => { expect(out).toContain(`legacy_things.id (Legacy.id, @unmanaged): 1 value(s) not a canonical uuid, e.g. "leg1"`); }); + test("TPH siblings that declare different fields on one column: each is read, in its own subtypes' rows only", async () => { + // Auto, Home and Cabin share `detail` and Auto and Home share `external_id`, each with its own + // field node. Only Home's and Cabin's detail holds a uuid, and only Home's externalId is one. + const root = await project({ "metadata.root": { package: "acme", children: [ + { "object.value": { name: "AutoDetail", children: [{ "field.string": { name: "plate" } }] } }, + { "object.value": { name: "HomeDetail", children: [{ "field.uuid": { name: "ownerId" } }] } }, + { "object.entity": { name: "Party", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "parties" } }, + { "field.uuid": { name: "id" } }, + { "field.string": { name: "kind" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + { "object.entity": { name: "Auto", extends: "Party", "@discriminatorValue": "auto", children: [ + { "field.object": { name: "detail", "@objectRef": "AutoDetail" } }, + { "field.string": { name: "externalId" } }, + ] } }, + { "object.entity": { name: "Home", extends: "Party", "@discriminatorValue": "home", children: [ + { "field.object": { name: "detail", "@objectRef": "HomeDetail" } }, + { "field.uuid": { name: "externalId" } }, + ] } }, + { "object.entity": { name: "Cabin", extends: "Party", "@discriminatorValue": "cabin", children: [ + { "field.object": { name: "detail", "@objectRef": "HomeDetail" } }, + ] } }, + ] } }); + const loaded = await loadMemory(root); + // migrate's table is unchanged: one column per name, whichever sibling declares it. + expect(buildExpectedSchema(loaded, { dialect: "sqlite" }).tables.find((t) => t.name === "parties")?.columns.map((c) => c.name)) + .toEqual(["id", "kind", "detail", "external_id"]); + expect(uuidPlacesOf(loaded).map(placeKey).sort()).toEqual([ + "parties.detail $.ownerId Home.detail.ownerId,Cabin.detail.ownerId [kind in cabin,home]", + "parties.external_id Home.externalId [kind in home]", + "parties.id Party.id", + ]); + + const file = join(root, "parties.db"); + const db = new Database(file); + db.run("CREATE TABLE parties (id TEXT PRIMARY KEY, kind TEXT, detail TEXT, external_id TEXT)"); + const insert = (id: string, kind: string, detail: unknown, externalId: string | null): void => { + db.run("INSERT INTO parties VALUES (?, ?, ?, ?)", [id, kind, JSON.stringify(detail), externalId]); + }; + // An Auto's externalId is a field.string and its detail has no uuid member: never findings. + insert("00000000-0000-0000-0000-00000000000a", "auto", { plate: "AB-1", ownerId: "not-a-member" }, "ext-auto"); + insert("00000000-0000-0000-0000-00000000000b", "home", { ownerId: "mbr2" }, "mbr1"); + insert("00000000-0000-0000-0000-00000000000c", "cabin", { ownerId: "mbr3" }, null); + insert("00000000-0000-0000-0000-00000000000d", "home", { ownerId: CANONICAL_A }, CANONICAL_B); + db.close(); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); + expect(code).toBe(1); + expect(out).toContain(`parties.detail $.ownerId (Home.detail.ownerId, Cabin.detail.ownerId): 2 value(s) not a canonical uuid, e.g. "mbr2", "mbr3"`); + expect(out).toContain(`parties.external_id (Home.externalId): 1 value(s) not a canonical uuid, e.g. "mbr1"`); + expect(out).not.toContain("ext-auto"); + expect(out).not.toContain("not-a-member"); + }); + test("map values, flattened members holding JSON and a TPH subtype's flattened value object are read", async () => { const root = await project(KITCHEN); const file = join(root, "kitchen.db"); @@ -687,6 +771,39 @@ describe("meta verify --uuid-values — Postgres (env-gated: MIGRATE_TS_PG_URL)" }); }); + test("TPH siblings on one column: a uuid sibling is read in its own subtype's rows only", async () => { + await withPgDatabase([ + "CREATE TABLE parties (id uuid PRIMARY KEY, kind text, external_id text, detail jsonb)", + `INSERT INTO parties VALUES ('${CANONICAL_A}', 'auto', 'ext-auto', '{"ownerId":"not-a-member"}')`, + `INSERT INTO parties VALUES ('${CANONICAL_B}', 'home', 'mbr1', '{"ownerId":"mbr2"}')`, + ], async (url) => { + const root = await project({ "metadata.root": { package: "acme", children: [ + { "object.value": { name: "AutoDetail", children: [{ "field.string": { name: "plate" } }] } }, + { "object.value": { name: "HomeDetail", children: [{ "field.uuid": { name: "ownerId" } }] } }, + { "object.entity": { name: "Party", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "parties" } }, + { "field.uuid": { name: "id" } }, + { "field.string": { name: "kind" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + { "object.entity": { name: "Auto", extends: "Party", "@discriminatorValue": "auto", children: [ + { "field.string": { name: "externalId" } }, + { "field.object": { name: "detail", "@objectRef": "AutoDetail" } }, + ] } }, + { "object.entity": { name: "Home", extends: "Party", "@discriminatorValue": "home", children: [ + { "field.uuid": { name: "externalId" } }, + { "field.object": { name: "detail", "@objectRef": "HomeDetail" } }, + ] } }, + ] } }); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", url], root)); + expect(code).toBe(1); + expect(out).toContain(`parties.external_id (Home.externalId): 1 value(s) not a canonical uuid, e.g. "mbr1"`); + expect(out).toContain(`parties.detail $.ownerId (Home.detail.ownerId): 1 value(s) not a canonical uuid, e.g. "mbr2"`); + expect(out).not.toContain("ext-auto"); + expect(out).not.toContain("not-a-member"); + }); + }); + test("a value object in a column that is not json is unreadable; a table in another schema is read", async () => { await withPgDatabase([ "CREATE SCHEMA crm", diff --git a/server/typescript/packages/integration-tests/test/uuid-values-scan.test.ts b/server/typescript/packages/integration-tests/test/uuid-values-scan.test.ts index b5c3ee3a97..2e48f97045 100644 --- a/server/typescript/packages/integration-tests/test/uuid-values-scan.test.ts +++ b/server/typescript/packages/integration-tests/test/uuid-values-scan.test.ts @@ -183,7 +183,7 @@ async function differential( const cells = planted.get(p.table)!.map((r) => r.find((c) => c.column === p.column)!); const rootList = p.steps.length === 1 && p.steps[0]!.kind === "elements"; const want = cells.reduce((n, c) => n + (c.notJson ? (rootList ? 1 : 0) : refused(c.parsed, p.steps)), 0); - const got = results.find((r) => r.table === p.table && r.column === p.column && (r.jsonPath ?? "") === pathOf(p.steps) && r.fields[0] === p.label); + const got = results.find((r) => r.table === p.table && r.column === p.column && (r.jsonPath ?? "") === pathOf(p.steps) && r.fields[0] === p.labels[0]); expect({ place: `${p.table}.${p.column} ${pathOf(p.steps)}`, status: got?.status, reason: got?.reason, n: got?.nonCanonical }) .toEqual({ place: `${p.table}.${p.column} ${pathOf(p.steps)}`, status: "scanned", reason: undefined, n: want }); } diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 62146a3a53..122644fbb5 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -325,8 +325,13 @@ export interface StoredField { label: string; /** Set for a member of a `@storage: flattened` value object: the field that holds the object. */ flattenedIn?: MetaField; - /** Set for a column a TPH subtype adds to its base's table: the subtype. */ - subtype?: MetaObject; + /** + * Set for a column TPH subtypes add to their base's table: each concrete subtype that stores + * this field node there, with the discriminator value its rows carry (as stored). Sibling + * subtypes may declare different nodes on one column; each node is its own entry, in the + * order first seen, and the first entry for a column is the one the DDL is built from. + */ + subtypes?: { object: MetaObject; value: string }[]; } /** A table that stores an object's rows, whether or not `meta migrate` owns its DDL. */ @@ -337,6 +342,8 @@ export interface StoredTable { owner: string; /** The table's source is `@unmanaged`: `meta migrate` neither creates nor alters it. */ unmanaged: boolean; + /** A TPH discriminator base's table: the column that holds each row's discriminator value. */ + discriminatorColumn?: string; fields: StoredField[]; } @@ -351,11 +358,13 @@ export function storedTablesOf(root: MetaData): StoredTable[] { const { entities, fkTargetOnly } = collectTableOwners(root); const one = ({ entity, tableName }: TableOwner, unmanaged: boolean): StoredTable => { const schema = resolveTableSchema(entity); + const discriminator = discriminatorFieldOf(entity); return { ...(schema !== undefined ? { schema } : {}), table: tableName, owner: entity.resolutionKey(), unmanaged, + ...(discriminator !== undefined ? { discriminatorColumn: resolveColumnName(discriminator, strategy) } : {}), fields: storedFieldsOf(entity, root as MetaRoot, strategy), }; }; @@ -403,13 +412,20 @@ function storedFieldsOf(entity: MetaObject, root: MetaRoot, strategy: ColumnNami } // FR-017 TPH: if this is a discriminator base, fold each concrete subtype's - // OWN fields into the single table. Dedupe by column name so an - // inherited/overridden base column is not re-emitted. + // OWN fields into the single table. A column the base already stores is not + // re-emitted; sibling subtypes that declare different field nodes on one column + // each get an entry (buildTable builds the column from the first). // ADR-0039: effective attr — @discriminator may be inherited (deep TPH base). if (entity.attr(OBJECT_ATTR_DISCRIMINATOR) !== undefined) { - const existing = new Set(out.map((c) => c.column)); + const baseColumns = new Set(out.map((c) => c.column)); const baseFieldNames = new Set(entity.fields().map((f) => f.name)); + const discriminator = discriminatorFieldOf(entity); + const intMap = discriminator === undefined ? undefined : intValueMapOf(discriminator); + const byNode = new Map(); for (const sub of tphConcreteSubtypes(entity, root)) { + // ADR-0039: effective attr — a sub-subtype may inherit @discriminatorValue. + const symbol = String(sub.attr(OBJECT_ATTR_DISCRIMINATOR_VALUE)); + const value = intMap?.[symbol] !== undefined ? String(intMap[symbol]) : symbol; // ADR-0039: effective fields — a field declared on an ABSTRACT intermediate level // (Party → abstract Organization → Carrier) is a column of this table too, and // only the resolving view reaches it. Reading the subtype's own children dropped @@ -420,9 +436,15 @@ function storedFieldsOf(entity: MetaObject, root: MetaRoot, strategy: ColumnNami // #213 — a TPH subtype's derived field is read-only too; never a column. if (field.isDerived()) continue; const column = resolveColumnName(field, strategy); - if (existing.has(column)) continue; - out.push({ column, field, label: `${sub.name}.${field.name}`, subtype: sub }); - existing.add(column); + if (baseColumns.has(column)) continue; + const stored = byNode.get(field); + if (stored !== undefined) { + stored.subtypes?.push({ object: sub, value }); + continue; + } + const entry: StoredField = { column, field, label: `${sub.name}.${field.name}`, subtypes: [{ object: sub, value }] }; + byNode.set(field, entry); + out.push(entry); } } } @@ -754,6 +776,13 @@ function isTphSubtype(entity: MetaData): boolean { ); } +/** The field a TPH discriminator base names in `@discriminator`, or undefined. */ +function discriminatorFieldOf(entity: MetaObject): MetaField | undefined { + // ADR-0039: effective attr — @discriminator may be inherited (deep TPH base). + const name = entity.attr(OBJECT_ATTR_DISCRIMINATOR); + return typeof name === "string" ? entity.fields().find((f) => f.name === name) : undefined; +} + /** Concrete TPH subtypes whose discriminator base is `base` (root-level scan). */ function tphConcreteSubtypes(base: MetaObject, root: MetaData): MetaObject[] { // ADR-0039: effective attr — @discriminator may be inherited. @@ -798,7 +827,9 @@ function buildTable( const columns: ColumnDescriptor[] = []; for (const stored of storedFieldsOf(entity, root, strategy)) { const { field } = stored; - if (stored.subtype !== undefined) { + if (stored.subtypes !== undefined) { + // A sibling subtype's node on a column already built: the first node defines it. + if (columns.some((c) => c.name === stored.column)) continue; const col = buildColumn(field, false, undefined, strategy); // Subtype-only columns are always nullable in TPH: a row of any OTHER // subtype stores NULL here. A DB DEFAULT defeats exactly that — a sibling From 21905f57cabb523b45167dace02f69797514c988 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 21:02:45 -0500 Subject: [PATCH 5/7] no-mistakes(document): Fix uuid-values native status wording in CHANGELOG --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a4b93828a4..cbbe5499e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,7 +25,8 @@ here.** `field.string` sibling's values are not reported. Each place is named by its column and JSON path (`claims.meta $.memberId`); for each one holding values that are not canonical 8-4-4-4-12 uuids, such as `"mbr1"` on SQLite or D1, it gives the count and up to five samples, and it exits 1 when it - finds any. A native Postgres `uuid` or `uuid[]` column is reported as guaranteed and not read. + finds any. A native Postgres `uuid` or `uuid[]` column is reported as native: the database + already stores only canonical uuids, so there is nothing to scan. Every place ends as scanned, native, missing (the table or column is not in this database) or unreadable (the read failed, the column type cannot hold the value, the stored text is not JSON, or a value object that holds a `field.uuid` contains itself), and the check passes only when From cd80b61951380a3ded7292b4dfcf1934c6767956 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 21:33:27 -0500 Subject: [PATCH 6/7] fix(cli): uuid-values reads a TPH subtype's redeclared base field in its own rows; scheme-less --db is a run error A subtype that redeclares a field its base stores put its own node in the base's column, and the scan only walked the base's node: a uuid redeclaration was never read (a false all-clear), and a string redeclaration of a base uuid got that subtype's strings reported. storedTablesOf now records the redeclaration (the base's entry builds the column, so migrate's DDL is unchanged), and the scan reads each node in the rows that hold it. A --db with no URL scheme now fails the uuid-values gate with exit 1 and an errors[] entry instead of an uncaught throw. --- CHANGELOG.md | 3 +- docs/features/migrations-and-drift.md | 5 +- .../packages/cli/src/commands/verify.ts | 13 ++- .../packages/cli/src/lib/uuid-values-check.ts | 58 +++++++++---- .../cli/test/verify-uuid-values.test.ts | 69 ++++++++++++++- .../migrate-ts/src/expected-schema.ts | 85 ++++++++++++++----- 6 files changed, 191 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cbbe5499e5..13d261aca3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,7 +22,8 @@ here.** code `meta migrate` lays out its columns with, so a TPH subtype's flattened value object is read in the one JSON column migrate gives it. TPH sibling subtypes that declare different fields on one column are each read, in the rows whose discriminator names a subtype declaring that field, so a - `field.string` sibling's values are not reported. Each place is named by its column and JSON path + `field.string` sibling's values are not reported; a subtype that redeclares a base field is read + the same way, its field in its own rows and the base's field in every other row. Each place is named by its column and JSON path (`claims.meta $.memberId`); for each one holding values that are not canonical 8-4-4-4-12 uuids, such as `"mbr1"` on SQLite or D1, it gives the count and up to five samples, and it exits 1 when it finds any. A native Postgres `uuid` or `uuid[]` column is reported as native: the database diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index a6d950909a..f4db850d39 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -825,7 +825,10 @@ check follows the nesting the write check validates: subtype is one JSON column, as migrate stores it; - a column that TPH sibling subtypes each declare with a different field: every field is followed, and where only some siblings put a uuid at a place, only the rows whose discriminator names one of - those subtypes are read, so a sibling's `field.string` values are not reported. + those subtypes are read, so a sibling's `field.string` values are not reported. A subtype that + redeclares a field its base stores is handled the same way: the subtype's field is read in that + subtype's rows and the base's field in every other row, in either direction (a uuid replacing a + string, or a string replacing a uuid). Each place is reported with its column and JSON path, for example `claims.meta $.memberId`, `claims.history $[*].tagIds[*]` or `claims.by_region $.*.regionId`, with the count of values that diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index 19653360d7..349286769e 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -1707,8 +1707,17 @@ export async function verifyCommand( log.error(`verify: --db is not used for dialect 'd1' — wrangler.toml owns the connection; pass --d1 instead`); return 2; } - const scanDialect: UuidScanDialect = - flags.dialect !== "d1" && (flags.dialect ?? inferDialect(flags.db as string)) === "postgres" ? "postgres" : "sqlite"; + // A --db with no recognised scheme (`./app.db`) is a run error, reported like a failed + // connection: never an uncaught throw, and the JSON payload still carries it in errors[]. + let scanDialect: UuidScanDialect; + try { + scanDialect = + flags.dialect !== "d1" && (flags.dialect ?? inferDialect(flags.db as string)) === "postgres" ? "postgres" : "sqlite"; + } catch (err) { + uuidValuesRunError = describeError(err); + log.error(`verify: ${uuidValuesRunError}`); + return 1; + } // Every table the model stores rows in: the write check applies to `@unmanaged` tables and // tables outside migrate.scope too, and reading them changes nothing. const places = uuidPlacesOf(root); diff --git a/server/typescript/packages/cli/src/lib/uuid-values-check.ts b/server/typescript/packages/cli/src/lib/uuid-values-check.ts index 52cc26ab97..aa6c19c642 100644 --- a/server/typescript/packages/cli/src/lib/uuid-values-check.ts +++ b/server/typescript/packages/cli/src/lib/uuid-values-check.ts @@ -54,10 +54,11 @@ export interface UuidPlace { /** The table's source is `@unmanaged`: reported, never a reason to skip. */ unmanaged: boolean; /** - * Set when only some rows hold this place: TPH sibling subtypes that declare different fields - * on one column. Only rows whose discriminator column holds one of `values` are read. + * Set when only some rows hold this place: TPH subtypes that declare different fields on one + * column (siblings, or a subtype redeclaring a base field). Only rows whose discriminator column + * holds one of `values` are read, or, with `exclude`, rows whose discriminator holds none of them. */ - rows?: { column: string; values: string[] }; + rows?: { column: string; values: string[]; exclude?: true }; /** Set when the walk stopped early: a value object that contains itself. */ truncated?: string; } @@ -93,10 +94,11 @@ export type UuidScanDialect = "postgres" | "sqlite"; export function uuidPlacesOf(root: MetaData): UuidPlace[] { const places: UuidPlace[] = []; for (const t of storedTablesOf(root)) { - // One place per column and path; `values` is undefined when every row holds it, else the - // discriminator values of the subtypes whose field puts it there. - const found = new Map | undefined }>(); + // One place per column and path, with the rows that hold it: the union of the rows of every + // stored entry whose field puts a uuid there. + const found = new Map(); const visitStored = (stored: StoredField): void => { + const own = rowsOf(stored); const at = (steps: UuidStep[], label: string, truncated?: string): void => { const key = `${stored.column}\u0000${jsonPathOf(steps) ?? ""}`; const existing = found.get(key); @@ -111,13 +113,12 @@ export function uuidPlacesOf(root: MetaData): UuidPlace[] { unmanaged: t.unmanaged, ...(truncated !== undefined ? { truncated } : {}), }, - values: stored.subtypes === undefined ? undefined : new Set(stored.subtypes.map((s) => s.value)), + rows: own, }); return; } if (!existing.place.labels.includes(label)) existing.place.labels.push(label); - if (stored.subtypes === undefined) existing.values = undefined; - else for (const s of stored.subtypes) existing.values?.add(s.value); + existing.rows = unionRows(existing.rows, own); }; const visit = (field: MetaField, steps: UuidStep[], label: string, seen: ReadonlySet): void => { const list: UuidStep[] = field.resolvedIsArray() ? [{ kind: "elements" }] : []; @@ -141,14 +142,22 @@ export function uuidPlacesOf(root: MetaData): UuidPlace[] { }; for (const f of t.fields) visitStored(f); - // Every discriminator value that stores some field in a column. + // Per column: every discriminator value a subtype entry stores there, and whether some entry + // holds every row but a listed few (a base field), in which case no subtype set covers it. const carriers = new Map>(); + const baseHeld = new Set(); for (const f of t.fields) { + if (f.subtypes === undefined) baseHeld.add(f.column); for (const s of f.subtypes ?? []) carriers.set(f.column, (carriers.get(f.column) ?? new Set()).add(s.value)); } - for (const { place, values } of found.values()) { - if (values !== undefined && t.discriminatorColumn !== undefined && values.size < (carriers.get(place.column)?.size ?? 0)) { - place.rows = { column: t.discriminatorColumn, values: [...values].sort() }; + for (const { place, rows } of found.values()) { + if (t.discriminatorColumn !== undefined && rows.kind !== "all") { + const values = [...rows.values].sort(); + if (rows.kind === "except") { + if (values.length > 0) place.rows = { column: t.discriminatorColumn, values, exclude: true }; + } else if (baseHeld.has(place.column) || values.length < (carriers.get(place.column)?.size ?? 0)) { + place.rows = { column: t.discriminatorColumn, values }; + } } places.push(place); } @@ -156,6 +165,23 @@ export function uuidPlacesOf(root: MetaData): UuidPlace[] { return places; } +/** Which rows of a TPH table hold a stored entry: all, only some subtypes', or all but some. */ +type RowSet = { kind: "all" } | { kind: "only"; values: Set } | { kind: "except"; values: Set }; + +function rowsOf(stored: StoredField): RowSet { + if (stored.subtypes !== undefined) return { kind: "only", values: new Set(stored.subtypes.map((s) => s.value)) }; + if (stored.exceptSubtypes !== undefined) return { kind: "except", values: new Set(stored.exceptSubtypes.map((s) => s.value)) }; + return { kind: "all" }; +} + +function unionRows(a: RowSet, b: RowSet): RowSet { + if (a.kind === "all" || b.kind === "all") return { kind: "all" }; + if (a.kind === "only" && b.kind === "only") return { kind: "only", values: new Set([...a.values, ...b.values]) }; + if (a.kind === "except" && b.kind === "except") return { kind: "except", values: new Set([...a.values].filter((v) => b.values.has(v))) }; + const [only, except] = a.kind === "only" ? [a, b] : [b, a]; + return { kind: "except", values: new Set([...except.values].filter((v) => !only.values.has(v))) }; +} + /** The value object a `field.object` or `field.map` holds, or undefined for any other field. */ function valueObjectOf(field: MetaField): MetaObject | undefined { if (field.subType !== FIELD_SUBTYPE_OBJECT && field.subType !== FIELD_SUBTYPE_MAP) return undefined; @@ -199,7 +225,9 @@ function sqliteIsCanonical(v: string, type: string): string { /** ` AND IN (…)` when only some rows hold the place; empty when every row does. */ function rowsOnly(place: UuidPlace, discriminator: (column: string) => string): string { if (place.rows === undefined) return ""; - return ` AND ${discriminator(ident(place.rows.column))} IN (${place.rows.values.map(literal).join(", ")})`; + const d = discriminator(ident(place.rows.column)); + const list = place.rows.values.map(literal).join(", "); + return place.rows.exclude ? ` AND (${d} IS NULL OR ${d} NOT IN (${list}))` : ` AND ${d} IN (${list})`; } /** One row per stored value at the place that is not a canonical uuid, on SQLite or D1. */ @@ -392,7 +420,7 @@ export async function scanUuidPlaces( sql = sqliteOffenders(p); // A root uuid list reports text that is not JSON as a finding; anything deeper cannot read it. const rootList = p.steps.length === 1 && p.steps[0]?.kind === "elements"; - const colKey = `${p.table}\u0000${p.column}\u0000${p.rows?.values.join("\u0000") ?? ""}`; + const colKey = `${p.table}\u0000${p.column}\u0000${p.rows?.exclude ? "!" : ""}${p.rows?.values.join("\u0000") ?? ""}`; if (p.steps.length > 0 && !rootList && !parsedColumns.has(colKey)) { parsedColumns.add(colKey); const bad = await countAndSample(sqliteUnparsable(p)); diff --git a/server/typescript/packages/cli/test/verify-uuid-values.test.ts b/server/typescript/packages/cli/test/verify-uuid-values.test.ts index 716da3591c..5cdcea8880 100644 --- a/server/typescript/packages/cli/test/verify-uuid-values.test.ts +++ b/server/typescript/packages/cli/test/verify-uuid-values.test.ts @@ -169,7 +169,7 @@ const KITCHEN = { "metadata.root": { package: "acme", children: [ /** A place as `table.column $path Labels`, for comparing enumerations. */ const placeKey = (p: UuidPlace): string => `${p.table}.${p.column}${p.steps.length > 0 ? ` $${p.steps.map((s) => (s.kind === "member" ? `.${s.key}` : s.kind === "elements" ? "[*]" : ".*")).join("")}` : ""} ${p.labels.join(",")}` + - `${p.unmanaged ? " @unmanaged" : ""}${p.rows !== undefined ? ` [${p.rows.column} in ${p.rows.values.join(",")}]` : ""}`; + `${p.unmanaged ? " @unmanaged" : ""}${p.rows !== undefined ? ` [${p.rows.column} ${p.rows.exclude ? "not in" : "in"} ${p.rows.values.join(",")}]` : ""}`; describe("meta verify --uuid-values — which places it reads", () => { test("every field.uuid column: keys, foreign keys and lists; never a field.string, even one stored as uuid", async () => { @@ -597,6 +597,73 @@ describe("meta verify --uuid-values — SQLite", () => { expect(out).not.toContain("not-a-member"); }); + test("a TPH subtype that redeclares a base field: its node is read in its rows, the base's in every other row", async () => { + // Party stores `detail` (no uuid inside) and `ref` (a string). Home redeclares both with uuids; + // Auto inherits them. Party also stores `ownerId` as a uuid, which Cabin redeclares as a string. + const root = await project({ "metadata.root": { package: "acme", children: [ + { "object.value": { name: "A", children: [{ "field.string": { name: "plate" } }] } }, + { "object.value": { name: "B", children: [{ "field.uuid": { name: "ownerId" } }] } }, + { "object.entity": { name: "Party", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "parties" } }, + { "field.uuid": { name: "id" } }, + { "field.string": { name: "kind" } }, + { "field.object": { name: "detail", "@objectRef": "A" } }, + { "field.string": { name: "ref" } }, + { "field.uuid": { name: "ownerId" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + { "object.entity": { name: "Auto", extends: "Party", "@discriminatorValue": "auto" } }, + { "object.entity": { name: "Home", extends: "Party", "@discriminatorValue": "home", children: [ + { "field.object": { name: "detail", "@objectRef": "B" } }, + { "field.uuid": { name: "ref" } }, + ] } }, + { "object.entity": { name: "Cabin", extends: "Party", "@discriminatorValue": "cabin", children: [ + { "field.string": { name: "ownerId" } }, + ] } }, + ] } }); + const loaded = await loadMemory(root); + // migrate's table is unchanged: the base declares every column, and a redeclaration adds none. + expect(buildExpectedSchema(loaded, { dialect: "sqlite" }).tables.find((t) => t.name === "parties")?.columns.map((c) => c.name)) + .toEqual(["id", "kind", "detail", "ref", "owner_id"]); + expect(uuidPlacesOf(loaded).map(placeKey).sort()).toEqual([ + "parties.detail $.ownerId Home.detail.ownerId [kind in home]", + "parties.id Party.id", + "parties.owner_id Party.ownerId [kind not in cabin]", + "parties.ref Home.ref [kind in home]", + ]); + + const file = join(root, "override.db"); + const db = new Database(file); + db.run("CREATE TABLE parties (id TEXT PRIMARY KEY, kind TEXT, detail TEXT, ref TEXT, owner_id TEXT)"); + const insert = (id: string, kind: string, detail: unknown, ref: string | null, ownerId: string | null): void => { + db.run("INSERT INTO parties VALUES (?, ?, ?, ?, ?)", [id, kind, JSON.stringify(detail), ref, ownerId]); + }; + // Auto rows hold the base's nodes: a string ref and a detail with no uuid member. + insert("00000000-0000-0000-0000-00000000000a", "auto", { plate: "AB-1", ownerId: "not-a-member" }, "ext-auto", "own1"); + insert("00000000-0000-0000-0000-00000000000b", "home", { ownerId: "mbr2" }, "mbr1", null); + // A Cabin's ownerId is a field.string: never a finding. + insert("00000000-0000-0000-0000-00000000000c", "cabin", { plate: "C" }, "cab-ref", "cabin-owner"); + insert("00000000-0000-0000-0000-00000000000d", "home", { ownerId: CANONICAL_A }, CANONICAL_B, CANONICAL_A); + db.close(); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", `file:${file}`], root)); + expect(code).toBe(1); + expect(out).toContain(`parties.detail $.ownerId (Home.detail.ownerId): 1 value(s) not a canonical uuid, e.g. "mbr2"`); + expect(out).toContain(`parties.ref (Home.ref): 1 value(s) not a canonical uuid, e.g. "mbr1"`); + expect(out).toContain(`parties.owner_id (Party.ownerId): 1 value(s) not a canonical uuid, e.g. "own1"`); + for (const absent of ["ext-auto", "not-a-member", "cab-ref", "cabin-owner"]) expect(out).not.toContain(absent); + }); + + test("a --db with no URL scheme is a run error, not an uncaught throw", async () => { + const root = await project(); + const { code, out } = await capture(() => verifyCommand(["--uuid-values", "--db", "./app.db"], root)); + expect(code).toBe(1); + expect(out).toContain("unrecognized URL './app.db'"); + const json = await capture(() => verifyCommand(["--uuid-values", "--db", "./app.db"], root, undefined, "json")); + expect(json.code).toBe(1); + const payload = JSON.parse(json.stdout) as { errors: { gate: string; error: string }[] }; + expect(payload.errors).toContainEqual({ gate: "uuid-values", error: expect.stringContaining("unrecognized URL './app.db'") }); + }); + test("map values, flattened members holding JSON and a TPH subtype's flattened value object are read", async () => { const root = await project(KITCHEN); const file = join(root, "kitchen.db"); diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 122644fbb5..9148cd3981 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -332,6 +332,17 @@ export interface StoredField { * order first seen, and the first entry for a column is the one the DDL is built from. */ subtypes?: { object: MetaObject; value: string }[]; + /** + * Set on a subtype entry for a column the base already stores, where the subtype's own node + * differs from the base's (the subtype redeclares the field). The DDL is built from the base's + * entry and never from this one; a reader of stored values reads the subtype's rows with it. + */ + overridesBase?: true; + /** + * Set on a base entry whose column some TPH subtypes redeclare (see `overridesBase`): those + * subtypes' rows hold their own node here, not this one. + */ + exceptSubtypes?: { object: MetaObject; value: string }[]; } /** A table that stores an object's rows, whether or not `meta migrate` owns its DDL. */ @@ -387,28 +398,7 @@ function storedFieldsOf(entity: MetaObject, root: MetaRoot, strategy: ColumnNami // passthrough onto the write table (and collided with a hand-written // `SELECT o.*, extra` view's alias). if (field.isDerived()) continue; - const label = `${entity.name}.${field.name}`; - if ( - field.subType === FIELD_SUBTYPE_OBJECT && - // ADR-0039: resolving — @storage may be inherited via extends. - field.attr(FIELD_ATTR_STORAGE) === STORAGE_FLATTENED - ) { - // Flattened storage: expand nested value-object fields as prefixed columns. - // The parent field.object itself does NOT produce its own column. - // ADR-0039: resolving — @objectRef may be inherited via extends. - const targetObject = refTarget(field, FIELD_ATTR_OBJECT_REF); - if (targetObject === undefined || !isMetaObject(targetObject)) continue; - for (const nested of targetObject.fields()) { - out.push({ - column: resolveFlattenedColumnName(field, nested, strategy), - field: nested, - label: `${label}.${nested.name}`, - flattenedIn: field, - }); - } - } else { - out.push({ column: resolveColumnName(field, strategy), field, label }); - } + out.push(...ownerFieldEntries(entity, field, strategy)); } // FR-017 TPH: if this is a discriminator base, fold each concrete subtype's @@ -422,10 +412,32 @@ function storedFieldsOf(entity: MetaObject, root: MetaRoot, strategy: ColumnNami const discriminator = discriminatorFieldOf(entity); const intMap = discriminator === undefined ? undefined : intValueMapOf(discriminator); const byNode = new Map(); + const baseByColumn = new Map(out.map((c) => [c.column, c])); + const overrides = new Map(); + const overrideEntries: StoredField[] = []; for (const sub of tphConcreteSubtypes(entity, root)) { // ADR-0039: effective attr — a sub-subtype may inherit @discriminatorValue. const symbol = String(sub.attr(OBJECT_ATTR_DISCRIMINATOR_VALUE)); const value = intMap?.[symbol] !== undefined ? String(intMap[symbol]) : symbol; + // A subtype that redeclares a field the base stores (or names a field onto a base + // column) puts its OWN node in that base column for its rows. The column and its DDL + // stay the base's; the entry records which node those rows hold, for a reader. + for (const field of sub.fields()) { + if (field.isDerived()) continue; + for (const e of ownerFieldEntries(sub, field, strategy)) { + const base = baseByColumn.get(e.column); + if (base === undefined || base.field === e.field) continue; + (base.exceptSubtypes ??= []).push({ object: sub, value }); + const seen = overrides.get(e.field); + if (seen !== undefined && seen.column === e.column) { + seen.subtypes?.push({ object: sub, value }); + continue; + } + const entry: StoredField = { ...e, subtypes: [{ object: sub, value }], overridesBase: true }; + overrides.set(e.field, entry); + overrideEntries.push(entry); + } + } // ADR-0039: effective fields — a field declared on an ABSTRACT intermediate level // (Party → abstract Organization → Carrier) is a column of this table too, and // only the resolving view reaches it. Reading the subtype's own children dropped @@ -447,10 +459,37 @@ function storedFieldsOf(entity: MetaObject, root: MetaRoot, strategy: ColumnNami out.push(entry); } } + out.push(...overrideEntries); } return out; } +/** + * The stored entries one field of `owner` contributes: one column, or for a `@storage: + * flattened` value object one column per member and none of its own. + */ +function ownerFieldEntries(owner: MetaObject, field: MetaField, strategy: ColumnNamingStrategy): StoredField[] { + const label = `${owner.name}.${field.name}`; + if ( + field.subType === FIELD_SUBTYPE_OBJECT && + // ADR-0039: resolving — @storage may be inherited via extends. + field.attr(FIELD_ATTR_STORAGE) === STORAGE_FLATTENED + ) { + // Flattened storage: expand nested value-object fields as prefixed columns. + // The parent field.object itself does NOT produce its own column. + // ADR-0039: resolving — @objectRef may be inherited via extends. + const targetObject = refTarget(field, FIELD_ATTR_OBJECT_REF); + if (targetObject === undefined || !isMetaObject(targetObject)) return []; + return targetObject.fields().map((nested) => ({ + column: resolveFlattenedColumnName(field, nested, strategy), + field: nested, + label: `${label}.${nested.name}`, + flattenedIn: field, + })); + } + return [{ column: resolveColumnName(field, strategy), field, label }]; +} + /** * The expected schema as every existing caller wants it. Thin wrapper over * {@link buildExpectedSchemaWithProvenance}; byte-identical output. @@ -827,6 +866,8 @@ function buildTable( const columns: ColumnDescriptor[] = []; for (const stored of storedFieldsOf(entity, root, strategy)) { const { field } = stored; + // A subtype's redeclaration of a base column: the base's entry builds the column. + if (stored.overridesBase) continue; if (stored.subtypes !== undefined) { // A sibling subtype's node on a column already built: the first node defines it. if (columns.some((c) => c.name === stored.column)) continue; From e27dbb9f54a8ed039fff2fdcef33fc95106a9bcf Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 21:35:16 -0500 Subject: [PATCH 7/7] no-mistakes(review): apply reviewer inline fixes --- .../packages/migrate-ts/src/expected-schema.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 9148cd3981..488c5cbb9a 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -385,8 +385,9 @@ export function storedTablesOf(root: MetaData): StoredTable[] { /** * The fields a table stores, in column order: the owner's effective fields (a flattened value * object contributes one column per member, and no column of its own), then, for a TPH - * discriminator base, each concrete subtype's further fields. A derived field is never stored. - * The one definition of "which column holds which field": {@link buildTable} builds its + * discriminator base, each concrete subtype's further fields, then the `overridesBase` entries + * of subtypes that redeclare a base column (never a column of their own). A derived field is + * never stored. The one definition of "which column holds which field": {@link buildTable} builds its * columns from it. */ function storedFieldsOf(entity: MetaObject, root: MetaRoot, strategy: ColumnNamingStrategy): StoredField[] { @@ -402,9 +403,10 @@ function storedFieldsOf(entity: MetaObject, root: MetaRoot, strategy: ColumnNami } // FR-017 TPH: if this is a discriminator base, fold each concrete subtype's - // OWN fields into the single table. A column the base already stores is not - // re-emitted; sibling subtypes that declare different field nodes on one column - // each get an entry (buildTable builds the column from the first). + // OWN fields into the single table. A column the base already stores gets no + // new column: a subtype that redeclares it gets an `overridesBase` entry, which + // buildTable skips. Sibling subtypes that declare different field nodes on one + // subtype column each get an entry (buildTable builds the column from the first). // ADR-0039: effective attr — @discriminator may be inherited (deep TPH base). if (entity.attr(OBJECT_ATTR_DISCRIMINATOR) !== undefined) { const baseColumns = new Set(out.map((c) => c.column));