diff --git a/CHANGELOG.md b/CHANGELOG.md index a4931d13ba..13d261aca3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,36 @@ 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 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. 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; 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 + 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 + 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 @@ -371,7 +401,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..8258c73afc 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 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 a9ea20bf94..f4db850d39 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -796,6 +796,70 @@ 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 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; +- 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. 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 +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 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 +(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 +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 `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..349286769e 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 { + scanUuidPlaces, uuidPlacesOf, UUID_SAMPLE_LIMIT, uuidValuesReport, type UuidColumnResult, type UuidScanDialect, +} 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,92 @@ 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 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; } - - const allow = tokensToAllowOptions(flags.allow); - const expectedViews = buildProjectionViews(root, { dialect: "d1" }); - let driftResult; + // 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 { - 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), - }); + scanDialect = + flags.dialect !== "d1" && (flags.dialect ?? inferDialect(flags.db as string)) === "postgres" ? "postgres" : "sqlite"; } catch (err) { - log.error(`verify: ${describeError(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); - const displayUrl = `d1:${binding.binding}${remote ? " (--remote)" : " (local)"}`; - return reportSchemaDrift(driftResult, ledgerDrift, displayUrl); + 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 { + // 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}`); + return 1; + } + 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); + } 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; + 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)}`; + 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); + } + if (report.error !== undefined) uuidValuesRunError = report.error; + return report.failed ? 1 : 0; } // Shared drift-reporting + exit-code logic for BOTH schema-drift paths (sqlite/ @@ -2301,12 +2419,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 +2490,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 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 }[]; }): Record { @@ -2417,7 +2541,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 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")) { help.push( `the failing gate's drift DETAIL is printed as text on stderr — this payload carries the verdict only`, ); @@ -2480,6 +2609,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..3a6e7ca7c0 100644 --- a/server/typescript/packages/cli/src/index.ts +++ b/server/typescript/packages/cli/src/index.ts @@ -127,6 +127,14 @@ 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 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) --allow Accepted for parity with 'migrate'; does NOT affect the @@ -386,6 +394,14 @@ 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 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) --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..aa6c19c642 --- /dev/null +++ b/server/typescript/packages/cli/src/lib/uuid-values-check.ts @@ -0,0 +1,518 @@ +// `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 place, how many +// stored values are not canonical and a few of them. It never writes. +// +// 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_SUBTYPE_MAP, + FIELD_SUBTYPE_OBJECT, + FIELD_SUBTYPE_UUID, + isMetaObject, + refTarget, + type MetaData, + type MetaField, + type MetaObject, +} from "@metaobjectsdev/metadata"; +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}$"; + +/** How many distinct offending values a finding quotes. */ +export const UUID_SAMPLE_LIMIT = 5; + +/** 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) + +/** A position in stored data that the model types as `field.uuid`. */ +export interface UuidPlace { + schema?: string; + table: string; + column: string; + /** Empty: the column stores the uuid itself. Otherwise the walk into the column's JSON. */ + steps: UuidStep[]; + /** `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 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[]; exclude?: true }; + /** Set when the walk stopped early: a value object that contains itself. */ + truncated?: string; +} + +/** What the scan found at one place. */ +export interface UuidColumnResult { + table: string; + column: string; + /** 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[]; + 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[]; +} + +/** 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 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)) { + // 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); + 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 } : {}), + }, + rows: own, + }); + return; + } + if (!existing.place.labels.includes(label)) existing.place.labels.push(label); + existing.rows = unionRows(existing.rows, own); + }; + 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()); + }; + for (const f of t.fields) visitStored(f); + + // 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, 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); + } + } + 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; + // 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; + 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("'", "''")}'`; + +/** + * 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-]*')`; +} + +/** ` 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 ""; + 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. */ +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})`)}${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, + // so the SQL grows linearly with depth (D1 refuses a statement over 100 KB). + const from = [table]; + 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 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 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 (!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)}${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${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`)}${only} UNION ALL ${notAList}`; +} + +/** Rows whose stored text is not JSON at all: the uuids inside could not be read. */ +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. */ +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); + 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}${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})${only}` }; + } + if (typname !== "jsonb" && typname !== "json") { + return { unreadable: `column type ${typname} is not json or jsonb: the value inside it cannot be read` }; + } + const joins: string[] = []; + let v = `${column}::jsonb`; + const each = (want: "array" | "object"): void => { + const alias = `e${joins.length}`; + 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 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 => [`${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)}${only}` }; + } + 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)}${only} UNION ALL ${notAList}` }; +} + +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 { + // 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.labels, + 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}\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)); + if (bad.nonCanonical > 0) { + 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: [...new Set(p.labels.map(fieldOf))], + 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. */ +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 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[] = []; + 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 place(s) in ${displayUrl}:`); + let offending = 0; + let total = 0; + const unread: string[] = []; + for (const r of results) { + 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 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 { + offending++; + total += r.nonCanonical; + lines.push(`${where}: ${r.nonCanonical} value(s) not a canonical uuid, e.g. ${r.samples.map(quoteSample).join(", ")}`); + } + } + 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} 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." + + 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 c332533737..463fb16029 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,14 @@ 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 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) --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..5cdcea8880 --- /dev/null +++ b/server/typescript/packages/cli/test/verify-uuid-values.test.ts @@ -0,0 +1,918 @@ +/** + * `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, 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 { 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 }); }); + +const CANONICAL_A = "3f2b8c1e-9d4a-4b7e-8c21-5a6f0e9d1b23"; +const CANONICAL_B = "00000000-0000-0000-0000-000000000001"; + +/** 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"] } }, + ] } }, +] } }; + +/** 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, 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(config), "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; + } +} + +/** + * 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 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} ${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 () => { + 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", + "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" } }, + ] } }, + ] } }); + expect(uuidPlacesOf(await loadMemory(root)).map(placeKey).sort()).toEqual([ + "parties.household_id Person.householdId", + "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 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", + ]); + }); + + 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).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()); + }); + + 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.labels.includes("Tree.top.kids"))?.truncated).toContain("contains itself"); + + const file = join(root, "trees.db"); + const db = new Database(file); + 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("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("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); + }); + + 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); + 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); + 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"); + }); +}); + +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 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"); + }); + + 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 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(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 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(`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 { 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("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("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"); + 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 () => { + 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 place(s) are not canonical"); + }); +}); + +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") ? [{ 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" }] + : []; + 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)", () => { + /** 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 }); + 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 { + 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], 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"`); + }); + }); + + 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("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", + "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([ + "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"); + }); + }); +}); 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..2e48f97045 --- /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.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 }); + } + // 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..488c5cbb9a 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,220 @@ 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 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 }[]; + /** + * 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. */ +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; + /** A TPH discriminator base's table: the column that holds each row's discriminator value. */ + discriminatorColumn?: string; + 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); + 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), + }; + }; + 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, 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[] { + 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; + out.push(...ownerFieldEntries(entity, field, strategy)); + } + + // 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 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)); + 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(); + 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 + // 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 (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); + } + } + 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. + */ +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 @@ -624,6 +817,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. @@ -666,69 +866,39 @@ 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; + // 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; + 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 +1864,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 d3e2f6ef22..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, @@ -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);